1use std::collections::{BTreeMap, BTreeSet};
33use std::fmt::{self, Write as _};
34
35use moonproof_runtime_ir::ir::{
36 AdtOpInvocation, Argument, CircuitBody, Expression, FrontendLanguage, MoonIr, PathElement,
37 PrivacyClass, SourceSpan, Statement, TypeDescriptor, VmInstr,
38};
39use moonproof_runtime_ir::RuntimeValue;
40use serde::{Deserialize, Serialize};
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
48#[serde(rename_all = "lowercase")]
49pub enum Severity {
50 Low,
51 Medium,
52 High,
53}
54
55impl Severity {
56 #[must_use]
57 pub const fn as_str(self) -> &'static str {
58 match self {
59 Self::Low => "low",
60 Self::Medium => "medium",
61 Self::High => "high",
62 }
63 }
64
65 #[must_use]
66 pub const fn sarif_level(self) -> &'static str {
67 match self {
68 Self::High => "error",
69 Self::Medium => "warning",
70 Self::Low => "note",
71 }
72 }
73}
74
75impl fmt::Display for Severity {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 f.write_str(self.as_str())
78 }
79}
80
81impl std::str::FromStr for Severity {
82 type Err = String;
83
84 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
85 match s.trim().to_ascii_lowercase().as_str() {
86 "high" => Ok(Self::High),
87 "medium" | "med" => Ok(Self::Medium),
88 "low" => Ok(Self::Low),
89 other => Err(format!(
90 "invalid severity `{other}` (expected `high`, `medium`, or `low`)"
91 )),
92 }
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
98#[serde(rename_all = "kebab-case")]
99pub enum AuditRule {
100 DirectWitnessDisclosure,
101 DerivedWitnessDisclosure,
102 ImplicitControlFlowLeak,
103 WeakCommitmentRandomness,
104 UnconstrainedWitness,
105}
106
107impl AuditRule {
108 pub const ALL: [Self; 5] = [
110 Self::DirectWitnessDisclosure,
111 Self::DerivedWitnessDisclosure,
112 Self::ImplicitControlFlowLeak,
113 Self::WeakCommitmentRandomness,
114 Self::UnconstrainedWitness,
115 ];
116
117 #[must_use]
118 pub const fn id(self) -> &'static str {
119 match self {
120 Self::DirectWitnessDisclosure => "MP001",
121 Self::DerivedWitnessDisclosure => "MP002",
122 Self::ImplicitControlFlowLeak => "MP003",
123 Self::WeakCommitmentRandomness => "MP004",
124 Self::UnconstrainedWitness => "MP005",
125 }
126 }
127
128 #[must_use]
129 pub const fn slug(self) -> &'static str {
130 match self {
131 Self::DirectWitnessDisclosure => "direct-witness-disclosure",
132 Self::DerivedWitnessDisclosure => "derived-witness-disclosure",
133 Self::ImplicitControlFlowLeak => "implicit-control-flow-leak",
134 Self::WeakCommitmentRandomness => "weak-commitment-randomness",
135 Self::UnconstrainedWitness => "unconstrained-witness",
136 }
137 }
138
139 #[must_use]
140 pub const fn default_severity(self) -> Severity {
141 match self {
142 Self::DirectWitnessDisclosure
143 | Self::DerivedWitnessDisclosure
144 | Self::WeakCommitmentRandomness => Severity::High,
145 Self::ImplicitControlFlowLeak => Severity::Medium,
146 Self::UnconstrainedWitness => Severity::Low,
147 }
148 }
149
150 #[must_use]
151 pub const fn short_description(self) -> &'static str {
152 match self {
153 Self::DirectWitnessDisclosure => "Direct witness disclosure into public sink",
154 Self::DerivedWitnessDisclosure => "Derived witness value flows into public sink",
155 Self::ImplicitControlFlowLeak => {
156 "Secret-dependent control flow guards public side effect"
157 }
158 Self::WeakCommitmentRandomness => {
159 "Commitment uses constant or default opening randomness"
160 }
161 Self::UnconstrainedWitness => "Witness value is not constrained by any assert",
162 }
163 }
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
168#[serde(tag = "kind", rename_all = "snake_case")]
169pub enum SinkKind {
170 LedgerOp {
171 #[serde(default, skip_serializing_if = "Option::is_none")]
172 field: Option<String>,
173 adt: String,
174 operation: String,
175 },
176 EventEmit {
177 event_version: u32,
178 event_tag: u32,
179 },
180 CircuitReturn,
181 CrossContractCall {
182 circuit: String,
183 },
184 CommitmentOpening {
185 function: String,
186 },
187 ControlFlowGuard {
188 effect: String,
189 },
190 UnconstrainedWitness,
191}
192
193impl SinkKind {
194 #[must_use]
195 pub fn describe(&self) -> String {
196 match self {
197 Self::LedgerOp {
198 field: Some(f),
199 adt,
200 operation,
201 } => format!("ledger `{f}` ({adt}.{operation})"),
202 Self::LedgerOp {
203 field: None,
204 adt,
205 operation,
206 } => format!("ledger {adt}.{operation}"),
207 Self::EventEmit {
208 event_version,
209 event_tag,
210 } => format!("event emit (v{event_version}, tag {event_tag})"),
211 Self::CircuitReturn => "exported circuit return".to_owned(),
212 Self::CrossContractCall { circuit } => format!("cross-contract call `{circuit}`"),
213 Self::CommitmentOpening { function } => format!("`{function}` opening argument"),
214 Self::ControlFlowGuard { effect } => format!("secret-guarded {effect}"),
215 Self::UnconstrainedWitness => "no assert constraint".to_owned(),
216 }
217 }
218}
219
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222pub struct StaticFinding {
223 pub rule: AuditRule,
224 pub rule_id: String,
225 pub severity: Severity,
226 pub contract: String,
227 pub circuit: String,
228 pub source: String,
229 pub sink: SinkKind,
230 pub message: String,
231 pub remediation: String,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub span: Option<SourceSpan>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
235 pub source_file: Option<String>,
236}
237
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
240pub struct ContractAuditReport {
241 pub contract: String,
242 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub frontend_language: Option<FrontendLanguage>,
244 pub circuits_analyzed: usize,
245 pub witnesses_found: Vec<String>,
246 pub findings: Vec<StaticFinding>,
247}
248
249impl ContractAuditReport {
250 #[must_use]
252 pub fn count_at_least(&self, min_severity: Severity) -> usize {
253 self.findings
254 .iter()
255 .filter(|f| f.severity >= min_severity)
256 .count()
257 }
258}
259
260#[derive(Debug, Default, Clone, PartialEq, Eq)]
262pub struct StaticAuditOptions {
263 pub taint_args: bool,
266 pub allow: Vec<String>,
278}
279
280#[must_use]
286pub fn audit_ir(
287 contract_name: &str,
288 ir: &MoonIr,
289 opts: &StaticAuditOptions,
290) -> ContractAuditReport {
291 let ctx = IrCatalog::build(ir);
292 let summaries = compute_circuit_summaries(ir, &ctx);
293
294 let mut findings = Vec::new();
295 let mut circuits_analyzed = 0usize;
296
297 for circuit in &ir.circuits {
298 if !circuit.exported {
299 continue;
300 }
301 circuits_analyzed += 1;
302 let mut runner = CircuitAnalyzer::new(contract_name, ir, &ctx, &summaries, opts);
303 runner.analyze_exported_circuit(circuit);
304 findings.extend(runner.findings);
305 }
306
307 let findings = dedup_and_filter_findings(findings, &opts.allow);
308 let witnesses_found = ir.witnesses.iter().map(|w| w.name.clone()).collect();
309 let frontend_language = ir.frontend.as_ref().map(|f| f.language.clone());
310
311 ContractAuditReport {
312 contract: contract_name.to_owned(),
313 frontend_language,
314 circuits_analyzed,
315 witnesses_found,
316 findings,
317 }
318}
319
320#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
325struct TaintOrigin {
326 source: String,
327 direct: bool,
328}
329
330#[derive(Debug, Default, Clone, PartialEq, Eq)]
331struct TaintSet {
332 origins: BTreeMap<String, bool>,
336}
337
338impl TaintSet {
339 fn singleton(source: String, direct: bool) -> Self {
340 let mut origins = BTreeMap::new();
341 origins.insert(source, direct);
342 Self { origins }
343 }
344
345 fn is_empty(&self) -> bool {
346 self.origins.is_empty()
347 }
348
349 fn union_with(&mut self, other: &Self) {
350 for (src, &direct) in &other.origins {
351 self.origins
352 .entry(src.clone())
353 .and_modify(|d| *d = *d || direct)
354 .or_insert(direct);
355 }
356 }
357
358 fn derived(&self) -> Self {
359 Self {
360 origins: self.origins.keys().map(|k| (k.clone(), false)).collect(),
361 }
362 }
363
364 fn with_field(&self, field: &str) -> Self {
365 Self {
366 origins: self
367 .origins
368 .iter()
369 .map(|(k, &direct)| (format!("{k}.{field}"), direct))
370 .collect(),
371 }
372 }
373
374 fn origins_sorted(&self) -> Vec<TaintOrigin> {
375 self.origins
376 .iter()
377 .map(|(source, &direct)| TaintOrigin {
378 source: source.clone(),
379 direct,
380 })
381 .collect()
382 }
383}
384
385#[derive(Debug, Default, Clone, PartialEq, Eq)]
387struct AbstractVal {
388 taint: TaintSet,
390 fields: BTreeMap<String, AbstractVal>,
392 witness_deps: BTreeSet<String>,
395 is_constant: bool,
398}
399
400impl AbstractVal {
401 fn constant() -> Self {
402 Self {
403 is_constant: true,
404 ..Self::default()
405 }
406 }
407
408 fn witness(name: &str) -> Self {
409 let mut witness_deps = BTreeSet::new();
410 witness_deps.insert(name.to_owned());
411 Self {
412 taint: TaintSet::singleton(format!("witness:{name}"), true),
413 fields: BTreeMap::new(),
414 witness_deps,
415 is_constant: false,
416 }
417 }
418
419 fn argument(name: &str, tainted: bool) -> Self {
420 let taint = if tainted {
421 TaintSet::singleton(format!("arg:{name}"), true)
422 } else {
423 TaintSet::default()
424 };
425 Self {
426 taint,
427 fields: BTreeMap::new(),
428 witness_deps: BTreeSet::new(),
429 is_constant: false,
430 }
431 }
432
433 fn all_taint(&self) -> TaintSet {
435 let mut out = self.taint.clone();
436 for field in self.fields.values() {
437 out.union_with(&field.all_taint());
438 }
439 out
440 }
441
442 fn all_witness_deps(&self) -> BTreeSet<String> {
444 let mut out = self.witness_deps.clone();
445 for field in self.fields.values() {
446 out.extend(field.all_witness_deps());
447 }
448 out
449 }
450
451 fn derive(&self) -> Self {
453 Self {
454 taint: self.all_taint().derived(),
455 fields: BTreeMap::new(),
456 witness_deps: self.all_witness_deps(),
457 is_constant: self.is_constant,
458 }
459 }
460
461 fn sanitized_from(inputs: &[AbstractVal]) -> Self {
464 let mut deps = BTreeSet::new();
465 let mut all_const = true;
466 for v in inputs {
467 deps.extend(v.all_witness_deps());
468 all_const &= v.is_constant;
469 }
470 Self {
471 taint: TaintSet::default(),
472 fields: BTreeMap::new(),
473 witness_deps: deps,
474 is_constant: all_const,
475 }
476 }
477
478 fn join(&self, other: &Self) -> Self {
480 let mut taint = self.taint.clone();
481 taint.union_with(&other.taint);
482 let mut fields = self.fields.clone();
483 for (k, v) in &other.fields {
484 fields
485 .entry(k.clone())
486 .and_modify(|existing| *existing = existing.join(v))
487 .or_insert_with(|| v.clone());
488 }
489 let mut witness_deps = self.witness_deps.clone();
490 witness_deps.extend(other.witness_deps.iter().cloned());
491 Self {
492 taint,
493 fields,
494 witness_deps,
495 is_constant: self.is_constant && other.is_constant,
496 }
497 }
498
499 fn field_access(&self, field: &str) -> Self {
500 if let Some(sub) = self.fields.get(field) {
501 return sub.clone();
502 }
503 Self {
504 taint: self.taint.with_field(field),
505 fields: BTreeMap::new(),
506 witness_deps: self.witness_deps.clone(),
507 is_constant: self.is_constant,
508 }
509 }
510}
511
512#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
513struct CircuitKey {
514 name: String,
515 uniq: Option<u64>,
516}
517
518struct IrCatalog {
519 witness_names: BTreeSet<String>,
520 native_intrinsic_by_name: BTreeMap<(String, Option<u64>), String>,
521 native_intrinsic_fallback: BTreeMap<String, String>,
522 circuit_by_key: BTreeMap<CircuitKey, usize>,
523 circuit_fallback: BTreeMap<String, usize>,
524}
525
526impl IrCatalog {
527 fn build(ir: &MoonIr) -> Self {
528 let witness_names = ir.witnesses.iter().map(|w| w.name.clone()).collect();
529 let mut native_intrinsic_by_name = BTreeMap::new();
530 let mut native_intrinsic_fallback = BTreeMap::new();
531 for n in &ir.natives {
532 let intrinsic =
533 moonproof_runtime_ir::canonical_intrinsic_name(n.resolve_intrinsic()).to_owned();
534 native_intrinsic_by_name.insert((n.name.clone(), n.internal_uniq), intrinsic.clone());
535 native_intrinsic_fallback
536 .entry(n.name.clone())
537 .or_insert(intrinsic);
538 }
539 let mut circuit_by_key = BTreeMap::new();
540 let mut circuit_fallback = BTreeMap::new();
541 for (idx, c) in ir.circuits.iter().enumerate() {
542 circuit_by_key.insert(
543 CircuitKey {
544 name: c.name.clone(),
545 uniq: c.internal_uniq,
546 },
547 idx,
548 );
549 circuit_fallback.entry(c.name.clone()).or_insert(idx);
550 }
551 Self {
552 witness_names,
553 native_intrinsic_by_name,
554 native_intrinsic_fallback,
555 circuit_by_key,
556 circuit_fallback,
557 }
558 }
559
560 fn is_witness(&self, name: &str) -> bool {
561 self.witness_names.contains(name)
562 }
563
564 fn native_intrinsic(&self, name: &str, uniq: Option<u64>) -> Option<&str> {
565 if let Some(sym) = self.native_intrinsic_by_name.get(&(name.to_owned(), uniq)) {
566 return Some(sym.as_str());
567 }
568 self.native_intrinsic_fallback.get(name).map(String::as_str)
569 }
570
571 fn resolve_circuit<'a>(
572 &self,
573 ir: &'a MoonIr,
574 name: &str,
575 uniq: Option<u64>,
576 ) -> Option<(usize, &'a CircuitBody)> {
577 let key = CircuitKey {
578 name: name.to_owned(),
579 uniq,
580 };
581 let idx = self
582 .circuit_by_key
583 .get(&key)
584 .or_else(|| self.circuit_fallback.get(name))
585 .copied()?;
586 ir.circuits.get(idx).map(|c| (idx, c))
587 }
588}
589
590fn is_one_way_sanitizer(name: &str) -> bool {
596 matches!(
597 moonproof_runtime_ir::canonical_intrinsic_name(name),
598 "persistentHash"
599 | "transientHash"
600 | "keccak256"
601 | "sha512"
602 | "hashToCurve"
603 | "coinCommitment"
604 | "merkleTreePathRoot"
605 | "merkleTreePathRootNoLeafHash"
606 | "ecMulGenerator"
607 | "secp256k1MulGenerator"
608 | "secp256r1MulGenerator"
609 | "curve25519MulGenerator"
610 | "mp:hash/blake2b"
611 | "mp:hash/sha256"
612 )
613}
614
615fn is_commitment_primitive(name: &str) -> bool {
617 matches!(
618 moonproof_runtime_ir::canonical_intrinsic_name(name),
619 "persistentCommit" | "transientCommit"
620 )
621}
622
623fn is_zswap_constructor(name: &str) -> bool {
624 matches!(
625 moonproof_runtime_ir::canonical_intrinsic_name(name),
626 "createZswapOutput" | "createZswapInput"
627 )
628}
629
630fn is_own_public_key(name: &str) -> bool {
631 moonproof_runtime_ir::canonical_intrinsic_name(name) == "ownPublicKey"
632}
633
634const fn is_confidential_class(class: PrivacyClass) -> bool {
635 matches!(class, PrivacyClass::Private | PrivacyClass::Shielded)
636}
637
638fn resolve_alias(mut td: &TypeDescriptor) -> &TypeDescriptor {
639 for _ in 0..8 {
640 match td {
641 TypeDescriptor::Alias { of, .. } => td = of,
642 _ => break,
643 }
644 }
645 td
646}
647
648#[derive(Debug, Default, Clone, PartialEq, Eq)]
653struct CircuitSummary {
654 return_taint_from_param: BTreeMap<usize, bool>,
657 return_taint_from_witness: TaintSet,
659 return_deps_from_param: BTreeSet<usize>,
661 return_deps_from_witness: BTreeSet<String>,
663 invoked_witnesses: BTreeSet<String>,
666 constrained_params: BTreeSet<usize>,
668 sink_params: BTreeMap<usize, Vec<(bool, SinkKind)>>,
670 has_public_effect: bool,
672 returns_const_from_const: bool,
674}
675
676fn compute_circuit_summaries(ir: &MoonIr, ctx: &IrCatalog) -> Vec<CircuitSummary> {
677 let mut summaries = vec![CircuitSummary::default(); ir.circuits.len()];
678 let max_iters = ir.circuits.len().min(16) + 2;
680 for _ in 0..max_iters {
681 let mut changed = false;
682 for (idx, circuit) in ir.circuits.iter().enumerate() {
683 let next = summarize_circuit(ir, ctx, &summaries, circuit);
684 if next != summaries[idx] {
685 summaries[idx] = next;
686 changed = true;
687 }
688 }
689 if !changed {
690 break;
691 }
692 }
693 summaries
694}
695
696fn summarize_circuit(
697 ir: &MoonIr,
698 ctx: &IrCatalog,
699 summaries: &[CircuitSummary],
700 circuit: &CircuitBody,
701) -> CircuitSummary {
702 let opts = StaticAuditOptions::default();
703 let mut analyzer = CircuitAnalyzer::new("", ir, ctx, summaries, &opts);
704 analyzer.circuit_name.clone_from(&circuit.name);
705 analyzer.in_summary_mode = true;
706
707 for (i, arg) in circuit.arguments.iter().enumerate() {
708 let mut v = AbstractVal::default();
709 let tag = format!("__param:{i}");
710 v.taint = TaintSet::singleton(tag.clone(), true);
711 v.witness_deps.insert(tag);
712 v.is_constant = true;
713 analyzer.env.insert(arg.name.clone(), v);
714 }
715
716 let ret = analyzer.eval_stmt(&circuit.body);
717
718 let mut summary = CircuitSummary {
719 has_public_effect: analyzer.saw_public_effect,
720 returns_const_from_const: ret.is_constant,
721 ..CircuitSummary::default()
722 };
723
724 for origin in ret.all_taint().origins_sorted() {
725 if let Some(idx) = parse_param_tag(&origin.source) {
726 summary
727 .return_taint_from_param
728 .entry(idx)
729 .and_modify(|d| *d = *d || origin.direct)
730 .or_insert(origin.direct);
731 } else {
732 summary
733 .return_taint_from_witness
734 .union_with(&TaintSet::singleton(origin.source, origin.direct));
735 }
736 }
737
738 for dep in ret.all_witness_deps() {
739 if let Some(idx) = parse_param_tag(&dep) {
740 summary.return_deps_from_param.insert(idx);
741 } else {
742 summary.return_deps_from_witness.insert(dep);
743 }
744 }
745
746 summary.invoked_witnesses = analyzer
747 .invoked_witnesses
748 .difference(&analyzer.constrained_witnesses)
749 .cloned()
750 .collect();
751
752 for dep in &analyzer.constrained_witnesses {
753 if let Some(idx) = parse_param_tag(dep) {
754 summary.constrained_params.insert(idx);
755 }
756 }
757
758 for finding in &analyzer.findings {
759 if matches!(
760 finding.rule,
761 AuditRule::DirectWitnessDisclosure | AuditRule::DerivedWitnessDisclosure
762 ) {
763 if let Some(idx) = parse_param_tag(&finding.source) {
764 let direct = finding.rule == AuditRule::DirectWitnessDisclosure;
765 let entries = summary.sink_params.entry(idx).or_default();
766 if let Some((existing_direct, _)) =
767 entries.iter_mut().find(|(_, sink)| sink == &finding.sink)
768 {
769 *existing_direct = *existing_direct || direct;
770 } else {
771 entries.push((direct, finding.sink.clone()));
772 }
773 }
774 }
775 }
776
777 summary
778}
779
780fn parse_param_tag(tag: &str) -> Option<usize> {
781 let rest = tag.strip_prefix("__param:")?;
782 let head = rest.split('.').next()?;
783 head.parse::<usize>().ok()
784}
785
786struct CircuitAnalyzer<'a> {
791 contract_name: &'a str,
792 circuit_name: String,
793 ir: &'a MoonIr,
794 ctx: &'a IrCatalog,
795 summaries: &'a [CircuitSummary],
796 opts: &'a StaticAuditOptions,
797 in_summary_mode: bool,
798 env: BTreeMap<String, AbstractVal>,
799 pc_taint: TaintSet,
800 invoked_witnesses: BTreeSet<String>,
801 constrained_witnesses: BTreeSet<String>,
802 saw_public_effect: bool,
803 findings: Vec<StaticFinding>,
804}
805
806impl<'a> CircuitAnalyzer<'a> {
807 fn new(
808 contract_name: &'a str,
809 ir: &'a MoonIr,
810 ctx: &'a IrCatalog,
811 summaries: &'a [CircuitSummary],
812 opts: &'a StaticAuditOptions,
813 ) -> Self {
814 Self {
815 contract_name,
816 circuit_name: String::new(),
817 ir,
818 ctx,
819 summaries,
820 opts,
821 in_summary_mode: false,
822 env: BTreeMap::new(),
823 pc_taint: TaintSet::default(),
824 invoked_witnesses: BTreeSet::new(),
825 constrained_witnesses: BTreeSet::new(),
826 saw_public_effect: false,
827 findings: Vec::new(),
828 }
829 }
830
831 fn is_pact(&self) -> bool {
832 matches!(
833 self.ir.frontend.as_ref().map(|f| &f.language),
834 Some(FrontendLanguage::Pact5)
835 )
836 }
837
838 fn param_privacy(&self, circuit_name: &str, arg_name: &str) -> Option<PrivacyClass> {
839 let privacy = self.ir.privacy.as_ref()?;
840 privacy
841 .field_classes
842 .get(&format!("{circuit_name}.{arg_name}"))
843 .or_else(|| {
844 privacy
845 .field_classes
846 .get(&format!("{circuit_name}::{arg_name}"))
847 })
848 .copied()
849 }
850
851 fn struct_field_privacy(&self, struct_name: &str, field_name: &str) -> Option<PrivacyClass> {
852 let privacy = self.ir.privacy.as_ref()?;
853 privacy
854 .field_classes
855 .get(&format!("{struct_name}.{field_name}"))
856 .or_else(|| {
857 privacy
858 .field_classes
859 .get(&format!("{struct_name}::{field_name}"))
860 })
861 .copied()
862 }
863
864 fn initial_arg_val(&self, circuit_name: &str, arg: &Argument) -> AbstractVal {
865 let tainted = self.opts.taint_args
866 || self
867 .param_privacy(circuit_name, &arg.name)
868 .is_some_and(is_confidential_class);
869 if tainted {
870 return AbstractVal::argument(&arg.name, true);
871 }
872 let mut val = AbstractVal::argument(&arg.name, false);
873 self.populate_private_struct_fields(
874 &arg.arg_type,
875 &format!("arg:{}", arg.name),
876 &mut val,
877 0,
878 );
879 val
880 }
881
882 fn populate_private_struct_fields(
883 &self,
884 td: &TypeDescriptor,
885 prefix: &str,
886 out: &mut AbstractVal,
887 depth: usize,
888 ) {
889 if depth >= 8 || self.ir.privacy.is_none() {
890 return;
891 }
892 match resolve_alias(td) {
893 TypeDescriptor::Struct { name, elements } => {
894 for elt in elements {
895 let field_source = format!("{prefix}.{}", elt.name);
896 let mut field_val = if self
897 .struct_field_privacy(name, &elt.name)
898 .is_some_and(is_confidential_class)
899 {
900 AbstractVal {
901 taint: TaintSet::singleton(field_source.clone(), true),
902 fields: BTreeMap::new(),
903 witness_deps: BTreeSet::new(),
904 is_constant: false,
905 }
906 } else {
907 AbstractVal::default()
908 };
909 self.populate_private_struct_fields(
910 &elt.field_type,
911 &field_source,
912 &mut field_val,
913 depth + 1,
914 );
915 if !field_val.all_taint().is_empty() {
916 out.fields
917 .entry(elt.name.clone())
918 .and_modify(|existing| *existing = existing.join(&field_val))
919 .or_insert(field_val);
920 }
921 }
922 }
923 TypeDescriptor::Vector { elt_type, .. } => {
924 let elem_prefix = format!("{prefix}[]");
925 self.populate_private_struct_fields(elt_type, &elem_prefix, out, depth + 1);
926 }
927 TypeDescriptor::Tuple { types } => {
928 for (idx, item_ty) in types.iter().enumerate() {
929 let item_prefix = format!("{prefix}.{idx}");
930 self.populate_private_struct_fields(item_ty, &item_prefix, out, depth + 1);
931 }
932 }
933 _ => {}
934 }
935 }
936
937 fn resolve_location(&self, sink: &SinkKind) -> (Option<SourceSpan>, Option<String>) {
938 let Some(ref debug_info) = self.ir.debug_info else {
939 return (None, None);
940 };
941 let span = debug_info
942 .circuit_spans
943 .get(&self.circuit_name)
944 .cloned()
945 .or_else(|| match sink {
946 SinkKind::LedgerOp {
947 field: Some(ref f), ..
948 } => debug_info.field_spans.get(f).cloned(),
949 _ => None,
950 });
951 let source_file = span
952 .as_ref()
953 .and_then(|s| s.file.clone())
954 .or_else(|| debug_info.sources.first().cloned());
955 (span, source_file)
956 }
957
958 fn analyze_exported_circuit(&mut self, circuit: &CircuitBody) {
959 self.circuit_name.clone_from(&circuit.name);
960 for arg in &circuit.arguments {
961 let val = self.initial_arg_val(&circuit.name, arg);
962 self.env.insert(arg.name.clone(), val);
963 }
964
965 let ret = self.eval_stmt(&circuit.body);
966
967 self.check_public_sink(&ret, &SinkKind::CircuitReturn);
969
970 let unconstrained: Vec<String> = self
973 .invoked_witnesses
974 .difference(&self.constrained_witnesses)
975 .cloned()
976 .collect();
977 for witness in unconstrained {
978 let (message, remediation) = if self.is_pact() {
979 (
980 format!(
981 "witness `{witness}` in `{}.{}` is never constrained by `(enforce ...)`; a malicious prover can supply any value",
982 self.contract_name, self.circuit_name
983 ),
984 format!(
985 "Constrain `{witness}` (or a commitment/hash derived from it) with `(enforce ...)` against table state or public inputs."
986 ),
987 )
988 } else {
989 (
990 format!(
991 "witness `{witness}` in `{}.{}` is never constrained by an `assert`; a malicious prover can supply any value",
992 self.contract_name, self.circuit_name
993 ),
994 format!(
995 "Constrain `{witness}` (or a commitment/hash derived from it) with `assert(...)` against ledger state or public inputs."
996 ),
997 )
998 };
999 self.push_finding(
1000 AuditRule::UnconstrainedWitness,
1001 format!("witness:{witness}"),
1002 SinkKind::UnconstrainedWitness,
1003 message,
1004 remediation,
1005 );
1006 }
1007 }
1008
1009 fn eval_stmt(&mut self, stmt: &Statement) -> AbstractVal {
1010 match stmt {
1011 Statement::Seq { items } => {
1012 let mut last = AbstractVal::constant();
1013 for item in items {
1014 last = self.eval_stmt(item);
1015 }
1016 last
1017 }
1018 Statement::Const { binding, value } => {
1019 let v = self.eval_expr(value);
1020 self.env.insert(binding.name.clone(), v);
1021 AbstractVal::constant()
1022 }
1023 Statement::ConstDestructure { bindings } => {
1024 for b in bindings {
1025 self.env.insert(b.name.clone(), AbstractVal::constant());
1026 }
1027 AbstractVal::constant()
1028 }
1029 Statement::If { cond, then, r#else } => {
1030 self.eval_if_stmt(cond, then, r#else.as_deref())
1031 }
1032 Statement::Expr { value } => self.eval_expr(value),
1033 Statement::Unimplemented | Statement::Noop => AbstractVal::constant(),
1034 }
1035 }
1036
1037 fn eval_if_stmt(
1038 &mut self,
1039 cond: &Expression,
1040 then_stmt: &Statement,
1041 else_stmt: Option<&Statement>,
1042 ) -> AbstractVal {
1043 let cond_val = self.eval_expr(cond);
1044 let saved_pc = self.pc_taint.clone();
1045 self.pc_taint.union_with(&cond_val.all_taint());
1046
1047 let base_env = self.env.clone();
1048 let base_constrained = self.constrained_witnesses.clone();
1049 let then_val = self.eval_stmt(then_stmt);
1050 let then_env = std::mem::replace(&mut self.env, base_env);
1051 let then_constrained = std::mem::replace(&mut self.constrained_witnesses, base_constrained);
1052
1053 let else_val = else_stmt.map_or_else(AbstractVal::constant, |e| self.eval_stmt(e));
1054 let else_env = std::mem::take(&mut self.env);
1055 let else_constrained = std::mem::take(&mut self.constrained_witnesses);
1056
1057 self.env = join_envs(&then_env, &else_env);
1058 self.constrained_witnesses = then_constrained
1059 .intersection(&else_constrained)
1060 .cloned()
1061 .collect();
1062 self.pc_taint = saved_pc;
1063
1064 let mut merged = then_val.join(&else_val);
1065 merged.witness_deps.extend(cond_val.all_witness_deps());
1066 merged
1067 }
1068
1069 fn eval_expr(&mut self, expr: &Expression) -> AbstractVal {
1070 match expr {
1071 Expression::Literal { .. }
1072 | Expression::Default { .. }
1073 | Expression::EnumRef { .. }
1074 | Expression::Unimplemented => AbstractVal::constant(),
1075 Expression::Var { name } => self.env.get(name).cloned().unwrap_or_default(),
1076 Expression::If { cond, then, r#else } => self.eval_if_expr(cond, then, r#else),
1077 Expression::EltRef { value, field, .. } => self.eval_expr(value).field_access(field),
1078 Expression::Tuple { items } | Expression::Vector { items } => {
1079 let mut acc = AbstractVal::constant();
1080 for item in items {
1081 let v = self.eval_expr(&item.value);
1082 acc = acc.join(&v);
1083 }
1084 acc
1085 }
1086 Expression::TupleRef { value, .. }
1087 | Expression::TupleSlice { value, .. }
1088 | Expression::Not { value }
1089 | Expression::Cast { value, .. }
1090 | Expression::SafeCast { value, .. }
1091 | Expression::DowncastUnsigned { value, .. }
1092 | Expression::FieldToBytes { value, .. }
1093 | Expression::CastToField { value, .. }
1094 | Expression::CastFromField { value, .. }
1095 | Expression::CastFromBytes { value, .. }
1096 | Expression::VectorToBytes { value, .. }
1097 | Expression::BytesToVector { value, .. }
1098 | Expression::CastFromEnum { value, .. }
1099 | Expression::CastToEnum { value, .. } => self.eval_expr(value).derive(),
1100 Expression::VectorRef { value, index, .. }
1101 | Expression::BytesRef { value, index, .. } => {
1102 let v = self.eval_expr(value);
1103 let i = self.eval_expr(index);
1104 v.join(&i).derive()
1105 }
1106 Expression::VectorSlice { value, start, .. }
1107 | Expression::BytesSlice { value, start, .. } => {
1108 let v = self.eval_expr(value);
1109 let s = self.eval_expr(start);
1110 v.join(&s).derive()
1111 }
1112 Expression::Binop { left, right, .. }
1113 | Expression::Eq { left, right, .. }
1114 | Expression::Neq { left, right, .. }
1115 | Expression::And { left, right }
1116 | Expression::Or { left, right } => {
1117 let l = self.eval_expr(left);
1118 let r = self.eval_expr(right);
1119 l.join(&r).derive()
1120 }
1121 Expression::Assign { name, value } => {
1122 let v = self.eval_expr(value);
1123 self.env.insert(name.clone(), v.clone());
1124 v
1125 }
1126 Expression::Seq { items } => {
1127 let mut last = AbstractVal::constant();
1128 for item in items {
1129 last = self.eval_expr(item);
1130 }
1131 last
1132 }
1133 Expression::New { of_type, arguments } => self.eval_new(of_type, arguments),
1134 Expression::Assert { cond, .. } => {
1135 let c = self.eval_expr(cond);
1136 self.constrained_witnesses.extend(c.all_witness_deps());
1137 AbstractVal::constant()
1138 }
1139 Expression::Call {
1140 function,
1141 function_uniq,
1142 arguments,
1143 } => self.eval_call(function, *function_uniq, arguments),
1144 Expression::AdtOp(inv) => self.eval_adt_op(inv),
1145 Expression::Emit {
1146 event_version,
1147 event_tag,
1148 payload,
1149 vm_ops,
1150 ..
1151 } => self.eval_emit(*event_version, *event_tag, payload, vm_ops),
1152 Expression::ContractCall {
1153 circuit,
1154 address,
1155 arguments,
1156 ..
1157 } => self.eval_contract_call(circuit, address, arguments),
1158 Expression::Fold {
1159 function,
1160 initial,
1161 arguments,
1162 ..
1163 } => self.eval_fold(function, initial, arguments),
1164 Expression::Map {
1165 function,
1166 arguments,
1167 ..
1168 } => self.eval_map(function, arguments),
1169 }
1170 }
1171
1172 fn eval_if_expr(
1173 &mut self,
1174 cond: &Expression,
1175 then_expr: &Expression,
1176 else_expr: &Expression,
1177 ) -> AbstractVal {
1178 let cond_val = self.eval_expr(cond);
1179 let saved_pc = self.pc_taint.clone();
1180 self.pc_taint.union_with(&cond_val.all_taint());
1181
1182 let base_env = self.env.clone();
1183 let base_constrained = self.constrained_witnesses.clone();
1184 let then_val = self.eval_expr(then_expr);
1185 let then_env = std::mem::replace(&mut self.env, base_env);
1186 let then_constrained = std::mem::replace(&mut self.constrained_witnesses, base_constrained);
1187
1188 let else_val = self.eval_expr(else_expr);
1189 let else_env = std::mem::take(&mut self.env);
1190 let else_constrained = std::mem::take(&mut self.constrained_witnesses);
1191
1192 self.env = join_envs(&then_env, &else_env);
1193 self.constrained_witnesses = then_constrained
1194 .intersection(&else_constrained)
1195 .cloned()
1196 .collect();
1197 self.pc_taint = saved_pc;
1198
1199 let mut merged = then_val.join(&else_val);
1200 merged.taint.union_with(&cond_val.all_taint().derived());
1202 merged.witness_deps.extend(cond_val.all_witness_deps());
1203 merged
1204 }
1205
1206 fn eval_new(&mut self, of_type: &TypeDescriptor, arguments: &[Expression]) -> AbstractVal {
1207 let vals: Vec<AbstractVal> = arguments.iter().map(|a| self.eval_expr(a)).collect();
1208 let mut fields = BTreeMap::new();
1209 let mut deps = BTreeSet::new();
1210 let mut all_const = true;
1211 if let TypeDescriptor::Struct { name, elements } = resolve_alias(of_type) {
1212 for (elt, val) in elements.iter().zip(&vals) {
1213 deps.extend(val.all_witness_deps());
1214 let mut field_val = val.clone();
1215 if field_val.all_taint().is_empty()
1216 && self
1217 .struct_field_privacy(name, &elt.name)
1218 .is_some_and(is_confidential_class)
1219 {
1220 field_val.taint =
1221 TaintSet::singleton(format!("field:{name}.{}", elt.name), true);
1222 field_val.is_constant = false;
1223 }
1224 all_const &= field_val.is_constant;
1225 fields.insert(elt.name.clone(), field_val);
1226 }
1227 return AbstractVal {
1228 taint: TaintSet::default(),
1229 fields,
1230 witness_deps: deps,
1231 is_constant: all_const,
1232 };
1233 }
1234 let mut merged = AbstractVal::constant();
1235 for v in vals {
1236 merged = merged.join(&v);
1237 }
1238 merged
1239 }
1240
1241 fn eval_call(
1242 &mut self,
1243 function: &str,
1244 function_uniq: Option<u64>,
1245 arguments: &[Expression],
1246 ) -> AbstractVal {
1247 let arg_vals: Vec<AbstractVal> = arguments.iter().map(|a| self.eval_expr(a)).collect();
1248 self.apply_call(function, function_uniq, &arg_vals)
1249 }
1250
1251 fn apply_call(
1252 &mut self,
1253 function: &str,
1254 function_uniq: Option<u64>,
1255 arg_vals: &[AbstractVal],
1256 ) -> AbstractVal {
1257 if self.ctx.is_witness(function) {
1259 self.invoked_witnesses.insert(function.to_owned());
1260 return AbstractVal::witness(function);
1261 }
1262
1263 let canonical_fn = moonproof_runtime_ir::canonical_intrinsic_name(function);
1265 let intrinsic = self
1266 .ctx
1267 .native_intrinsic(function, function_uniq)
1268 .unwrap_or(canonical_fn);
1269
1270 if is_commitment_primitive(canonical_fn) || is_commitment_primitive(intrinsic) {
1271 return self.eval_commitment_call(intrinsic, arg_vals);
1272 }
1273 if is_one_way_sanitizer(canonical_fn) || is_one_way_sanitizer(intrinsic) {
1274 return AbstractVal::sanitized_from(arg_vals);
1275 }
1276 if is_zswap_constructor(canonical_fn) || is_zswap_constructor(intrinsic) {
1277 for arg in arg_vals {
1278 self.constrained_witnesses.extend(arg.all_witness_deps());
1279 }
1280 return AbstractVal::constant();
1281 }
1282 if is_own_public_key(canonical_fn) || is_own_public_key(intrinsic) {
1283 return AbstractVal::default();
1284 }
1285
1286 if let Some((idx, _)) = self.ctx.resolve_circuit(self.ir, function, function_uniq) {
1288 if let Some(summary) = self.summaries.get(idx).cloned() {
1289 return self.apply_circuit_summary(&summary, arg_vals);
1290 }
1291 }
1292
1293 let mut combined = AbstractVal::constant();
1296 for arg in arg_vals {
1297 combined = combined.join(arg);
1298 }
1299 combined.derive()
1300 }
1301
1302 fn eval_commitment_call(&mut self, func: &str, arg_vals: &[AbstractVal]) -> AbstractVal {
1303 let value_arg = arg_vals.first();
1306 let opening_arg = arg_vals.get(1);
1307
1308 let value_tainted = value_arg.is_some_and(|v| !v.all_taint().is_empty());
1309 let weak_opening = opening_arg.is_some_and(|o| o.is_constant);
1310
1311 if weak_opening && value_tainted {
1312 let sources = value_arg.map_or_default(|v| v.all_taint().origins_sorted());
1313 let is_pact = self.is_pact();
1314 for origin in sources {
1315 let remediation = if is_pact {
1316 format!(
1317 "Pass secret witness randomness as the blinding argument to `(zk.commit value blinding)` (`{func}`) instead of a constant or default value."
1318 )
1319 } else {
1320 format!(
1321 "Pass secret witness randomness as the opening argument to `{func}` instead of a constant/default value."
1322 )
1323 };
1324 self.push_finding(
1325 AuditRule::WeakCommitmentRandomness,
1326 origin.source.clone(),
1327 SinkKind::CommitmentOpening {
1328 function: func.to_owned(),
1329 },
1330 format!(
1331 "`{func}` in `{}.{}` commits `{}` with a constant or default opening, breaking hiding",
1332 self.contract_name, self.circuit_name, origin.source
1333 ),
1334 remediation,
1335 );
1336 }
1337 let mut combined = AbstractVal::constant();
1339 for arg in arg_vals {
1340 combined = combined.join(arg);
1341 }
1342 return combined.derive();
1343 }
1344
1345 AbstractVal::sanitized_from(arg_vals)
1347 }
1348
1349 fn apply_circuit_summary(
1350 &mut self,
1351 summary: &CircuitSummary,
1352 arg_vals: &[AbstractVal],
1353 ) -> AbstractVal {
1354 if summary.has_public_effect {
1355 self.saw_public_effect = true;
1356 self.check_implicit_flow("helper circuit public effect");
1357 }
1358 self.invoked_witnesses
1359 .extend(summary.invoked_witnesses.iter().cloned());
1360 for ¶m_idx in &summary.constrained_params {
1361 if let Some(arg) = arg_vals.get(param_idx) {
1362 self.constrained_witnesses.extend(arg.all_witness_deps());
1363 }
1364 }
1365 for (¶m_idx, sinks) in &summary.sink_params {
1366 if let Some(arg) = arg_vals.get(param_idx) {
1367 for &(direct, ref sink) in sinks {
1368 let effective = if direct { arg.clone() } else { arg.derive() };
1369 self.check_public_sink(&effective, sink);
1370 }
1371 }
1372 }
1373
1374 let mut ret = AbstractVal {
1375 taint: summary.return_taint_from_witness.clone(),
1376 fields: BTreeMap::new(),
1377 witness_deps: summary.return_deps_from_witness.clone(),
1378 is_constant: summary.returns_const_from_const && arg_vals.iter().all(|a| a.is_constant),
1379 };
1380 for (¶m_idx, &direct) in &summary.return_taint_from_param {
1381 if let Some(arg) = arg_vals.get(param_idx) {
1382 let t = if direct {
1383 arg.all_taint()
1384 } else {
1385 arg.all_taint().derived()
1386 };
1387 ret.taint.union_with(&t);
1388 }
1389 }
1390 for ¶m_idx in &summary.return_deps_from_param {
1391 if let Some(arg) = arg_vals.get(param_idx) {
1392 ret.witness_deps.extend(arg.all_witness_deps());
1393 }
1394 }
1395 ret
1396 }
1397
1398 fn eval_adt_op(&mut self, inv: &AdtOpInvocation) -> AbstractVal {
1399 let mut operand_deps = BTreeSet::new();
1400 let sink = SinkKind::LedgerOp {
1401 field: inv.field.clone(),
1402 adt: inv.adt.clone(),
1403 operation: inv.operation.clone(),
1404 };
1405
1406 for elem in &inv.field_path {
1407 if let PathElement::Expr { value, .. } = elem {
1408 let v = self.eval_expr(value);
1409 operand_deps.extend(v.all_witness_deps());
1410 self.check_public_sink(&v, &sink);
1411 }
1412 }
1413 for arg in &inv.arguments {
1414 let v = self.eval_expr(arg);
1415 operand_deps.extend(v.all_witness_deps());
1416 self.check_public_sink(&v, &sink);
1417 }
1418
1419 let mut vm_exprs = Vec::new();
1423 let mut vm_names = BTreeSet::new();
1424 collect_vm_refs(&inv.vm_ops, &mut vm_exprs, &mut vm_names);
1425 for expr in vm_exprs {
1426 let v = self.eval_expr(&expr);
1427 operand_deps.extend(v.all_witness_deps());
1428 self.check_public_sink(&v, &sink);
1429 }
1430 for name in vm_names {
1431 if let Some(v) = self.env.get(&name).cloned() {
1432 operand_deps.extend(v.all_witness_deps());
1433 self.check_public_sink(&v, &sink);
1434 }
1435 }
1436
1437 if is_mutating_adt_op(inv) {
1438 self.saw_public_effect = true;
1439 self.check_implicit_flow(&sink.describe());
1440 }
1441
1442 AbstractVal {
1446 taint: TaintSet::default(),
1447 fields: BTreeMap::new(),
1448 witness_deps: operand_deps,
1449 is_constant: false,
1450 }
1451 }
1452
1453 fn eval_emit(
1454 &mut self,
1455 event_version: u32,
1456 event_tag: u32,
1457 payload: &Expression,
1458 vm_ops: &[VmInstr],
1459 ) -> AbstractVal {
1460 let sink = SinkKind::EventEmit {
1461 event_version,
1462 event_tag,
1463 };
1464 let payload_val = self.eval_expr(payload);
1465 self.check_public_sink(&payload_val, &sink);
1466
1467 let mut vm_exprs = Vec::new();
1468 let mut vm_names = BTreeSet::new();
1469 collect_vm_refs(vm_ops, &mut vm_exprs, &mut vm_names);
1470 for expr in vm_exprs {
1471 let v = self.eval_expr(&expr);
1472 self.check_public_sink(&v, &sink);
1473 }
1474 for name in vm_names {
1475 if let Some(v) = self.env.get(&name).cloned() {
1476 self.check_public_sink(&v, &sink);
1477 }
1478 }
1479
1480 self.saw_public_effect = true;
1481 self.check_implicit_flow(&sink.describe());
1482 AbstractVal::constant()
1483 }
1484
1485 fn eval_contract_call(
1486 &mut self,
1487 circuit: &str,
1488 address: &Expression,
1489 arguments: &[Expression],
1490 ) -> AbstractVal {
1491 let sink = SinkKind::CrossContractCall {
1492 circuit: circuit.to_owned(),
1493 };
1494 let addr_val = self.eval_expr(address);
1495 self.check_public_sink(&addr_val, &sink);
1496
1497 let mut deps = addr_val.all_witness_deps();
1498 for arg in arguments {
1499 let v = self.eval_expr(arg);
1500 deps.extend(v.all_witness_deps());
1501 self.check_public_sink(&v, &sink);
1502 }
1503
1504 self.saw_public_effect = true;
1505 self.check_implicit_flow(&sink.describe());
1506
1507 AbstractVal {
1508 taint: TaintSet::default(),
1509 fields: BTreeMap::new(),
1510 witness_deps: deps,
1511 is_constant: false,
1512 }
1513 }
1514
1515 fn eval_fold(
1516 &mut self,
1517 function: &RuntimeValue,
1518 initial: &RuntimeValue,
1519 arguments: &[RuntimeValue],
1520 ) -> AbstractVal {
1521 let mut acc = extract_wrapped_expr(initial).map_or_default(|e| self.eval_expr(&e));
1522 let arg_vals: Vec<AbstractVal> = arguments
1523 .iter()
1524 .map(|a| extract_wrapped_expr(a).map_or_default(|e| self.eval_expr(&e)))
1525 .collect();
1526
1527 for _ in 0..2 {
1529 let mut call_args = Vec::with_capacity(1 + arg_vals.len());
1530 call_args.push(acc.clone());
1531 call_args.extend(arg_vals.iter().cloned());
1532 let next = self.eval_higher_order_fn(function, &call_args);
1533 acc = acc.join(&next);
1534 }
1535 acc
1536 }
1537
1538 fn eval_map(&mut self, function: &RuntimeValue, arguments: &[RuntimeValue]) -> AbstractVal {
1539 let arg_vals: Vec<AbstractVal> = arguments
1540 .iter()
1541 .map(|a| extract_wrapped_expr(a).map_or_default(|e| self.eval_expr(&e)))
1542 .collect();
1543 self.eval_higher_order_fn(function, &arg_vals)
1544 }
1545
1546 fn eval_higher_order_fn(
1547 &mut self,
1548 function: &RuntimeValue,
1549 call_args: &[AbstractVal],
1550 ) -> AbstractVal {
1551 let Some(obj) = function.as_object() else {
1552 return AbstractVal::default();
1553 };
1554 let kind = obj.get("kind").and_then(RuntimeValue::as_str);
1555 match kind {
1556 Some("fref") => {
1557 let name = obj
1558 .get("name")
1559 .and_then(RuntimeValue::as_str)
1560 .unwrap_or_default();
1561 let uniq = obj.get("uniq").and_then(RuntimeValue::as_u64);
1562 self.apply_call(name, uniq, call_args)
1563 }
1564 Some("lambda") => {
1565 let arg_names: Vec<String> = obj
1566 .get("arguments")
1567 .and_then(RuntimeValue::as_array)
1568 .map_or_default(|arr| {
1569 arr.iter()
1570 .filter_map(|item| {
1571 item.as_object()
1572 .and_then(|o| o.get("name"))
1573 .and_then(RuntimeValue::as_str)
1574 .or_else(|| item.as_str())
1575 .map(str::to_owned)
1576 })
1577 .collect()
1578 });
1579 let body = obj.get("body").and_then(|v| {
1580 moonproof_runtime_ir::from_runtime_value::<Statement>(v)
1581 .ok()
1582 .or_else(|| moonproof_runtime_ir::cbor_fast::decode_statement_value(v).ok())
1583 });
1584 let Some(body) = body else {
1585 let mut combined = AbstractVal::constant();
1586 for a in call_args {
1587 combined = combined.join(a);
1588 }
1589 return combined.derive();
1590 };
1591 let saved_env = self.env.clone();
1592 for (name, val) in arg_names.into_iter().zip(call_args.iter().cloned()) {
1593 self.env.insert(name, val);
1594 }
1595 let res = self.eval_stmt(&body);
1596 self.env = saved_env;
1597 res
1598 }
1599 _ => {
1600 let mut combined = AbstractVal::constant();
1601 for a in call_args {
1602 combined = combined.join(a);
1603 }
1604 combined.derive()
1605 }
1606 }
1607 }
1608
1609 fn check_public_sink(&mut self, val: &AbstractVal, sink: &SinkKind) {
1610 let taint = val.all_taint();
1611 if taint.is_empty() {
1612 return;
1613 }
1614 let sink_desc = sink.describe();
1615 let is_pact = self.is_pact();
1616 for origin in taint.origins_sorted() {
1617 let (rule, verb, remediation) = if origin.direct {
1618 (
1619 AuditRule::DirectWitnessDisclosure,
1620 "flows directly into",
1621 if is_pact {
1622 "Hash or commit this secret with `(zk.hash ...)` or `(zk.commit value blinding)` using secret randomness, or wrap intentional public reveals in `(zk.disclose ...)` before passing to public tables, events, or returns."
1623 } else {
1624 "Hash or commit this secret (`persistentHash` / `persistentCommit` with secret randomness) before passing it to public ledger state, events, or returns."
1625 },
1626 )
1627 } else {
1628 (
1629 AuditRule::DerivedWitnessDisclosure,
1630 "derives a value that flows into",
1631 if is_pact {
1632 "Ensure secret-derived values pass through a one-way cryptographic primitive (`(zk.hash ...)`, `(zk.commit value blinding)`) or explicit `(zk.disclose ...)` before reaching a public sink."
1633 } else {
1634 "Ensure secret-derived values pass through a one-way cryptographic primitive (`persistentHash`, `transientHash`, `persistentCommit`) before reaching a public sink."
1635 },
1636 )
1637 };
1638 self.push_finding(
1639 rule,
1640 origin.source.clone(),
1641 sink.clone(),
1642 format!(
1643 "`{}` {verb} {sink_desc} in `{}.{}`",
1644 origin.source, self.contract_name, self.circuit_name
1645 ),
1646 remediation.to_owned(),
1647 );
1648 }
1649 }
1650
1651 fn check_implicit_flow(&mut self, effect: &str) {
1652 if self.in_summary_mode || self.pc_taint.is_empty() {
1653 return;
1654 }
1655 let is_pact = self.is_pact();
1656 let remediation = if is_pact {
1657 "Avoid branching public table writes, event emissions, or cross-module calls on secret conditions in `(if ...)`, or make both branches perform uniform public operations or wrap intentional branch reveals in `(zk.disclose ...)`."
1658 } else {
1659 "Avoid branching public ledger writes, emits, or cross-contract calls on secret witness conditions, or make both branches perform uniform public operations."
1660 };
1661 for origin in self.pc_taint.origins_sorted() {
1662 self.push_finding(
1663 AuditRule::ImplicitControlFlowLeak,
1664 origin.source.clone(),
1665 SinkKind::ControlFlowGuard {
1666 effect: effect.to_owned(),
1667 },
1668 format!(
1669 "secret-dependent branch on `{}` guards public side effect ({effect}) in `{}.{}`",
1670 origin.source, self.contract_name, self.circuit_name
1671 ),
1672 remediation.to_owned(),
1673 );
1674 }
1675 }
1676
1677 fn push_finding(
1678 &mut self,
1679 rule: AuditRule,
1680 source: String,
1681 sink: SinkKind,
1682 message: String,
1683 remediation: String,
1684 ) {
1685 let (span, source_file) = self.resolve_location(&sink);
1686 self.findings.push(StaticFinding {
1687 rule,
1688 rule_id: rule.id().to_owned(),
1689 severity: rule.default_severity(),
1690 contract: self.contract_name.to_owned(),
1691 circuit: self.circuit_name.clone(),
1692 source,
1693 sink,
1694 message,
1695 remediation,
1696 span,
1697 source_file,
1698 });
1699 }
1700}
1701
1702fn join_envs(
1703 a: &BTreeMap<String, AbstractVal>,
1704 b: &BTreeMap<String, AbstractVal>,
1705) -> BTreeMap<String, AbstractVal> {
1706 let mut out = a.clone();
1707 for (k, v) in b {
1708 out.entry(k.clone())
1709 .and_modify(|existing| *existing = existing.join(v))
1710 .or_insert_with(|| v.clone());
1711 }
1712 out
1713}
1714
1715fn extract_wrapped_expr(val: &RuntimeValue) -> Option<Expression> {
1716 let inner = val.as_object()?.get("value")?;
1717 moonproof_runtime_ir::from_runtime_value(inner)
1718 .ok()
1719 .or_else(|| moonproof_runtime_ir::cbor_fast::decode_expression_value(inner).ok())
1720}
1721
1722fn collect_vm_refs(vm_ops: &[VmInstr], exprs: &mut Vec<Expression>, names: &mut BTreeSet<String>) {
1723 for instr in vm_ops {
1724 for v in instr.0.values() {
1725 collect_vm_refs_value(v, exprs, names);
1726 }
1727 }
1728}
1729
1730fn collect_vm_refs_value(
1731 val: &RuntimeValue,
1732 exprs: &mut Vec<Expression>,
1733 names: &mut BTreeSet<String>,
1734) {
1735 match val {
1736 RuntimeValue::Object(map) => {
1737 if map.get("vm").and_then(RuntimeValue::as_str) == Some("ref") {
1738 if let Some(name) = map.get("name").and_then(RuntimeValue::as_str) {
1739 names.insert(name.to_owned());
1740 }
1741 if let Some(inner) = map.get("value") {
1742 if let Some(expr) =
1743 moonproof_runtime_ir::from_runtime_value::<Expression>(inner)
1744 .ok()
1745 .or_else(|| {
1746 moonproof_runtime_ir::cbor_fast::decode_expression_value(inner).ok()
1747 })
1748 {
1749 exprs.push(expr);
1750 return;
1751 }
1752 }
1753 }
1754 for child in map.values() {
1755 collect_vm_refs_value(child, exprs, names);
1756 }
1757 }
1758 RuntimeValue::Array(items) => {
1759 for item in items {
1760 collect_vm_refs_value(item, exprs, names);
1761 }
1762 }
1763 _ => {}
1764 }
1765}
1766
1767fn is_mutating_adt_op(inv: &AdtOpInvocation) -> bool {
1768 if inv.adt == "Kernel" {
1769 return matches!(
1770 inv.operation.as_str(),
1771 "mintShielded"
1772 | "mintUnshielded"
1773 | "sendUnshielded"
1774 | "receiveUnshielded"
1775 | "claimZswapNullifier"
1776 | "claimZswapCoinSpend"
1777 | "claimZswapCoinReceive"
1778 | "claimContractCall"
1779 | "checkpoint"
1780 );
1781 }
1782 !matches!(
1783 inv.operation.as_str(),
1784 "read"
1785 | "lookup"
1786 | "member"
1787 | "isEmpty"
1788 | "size"
1789 | "length"
1790 | "head"
1791 | "checkRoot"
1792 | "isFull"
1793 | "lessThan"
1794 )
1795}
1796
1797fn dedup_and_filter_findings(findings: Vec<StaticFinding>, allow: &[String]) -> Vec<StaticFinding> {
1798 let mut seen = BTreeSet::new();
1799 let mut out = Vec::new();
1800 for f in findings {
1801 if is_allowed(&f, allow) {
1802 continue;
1803 }
1804 let key = (
1805 f.rule,
1806 f.contract.clone(),
1807 f.circuit.clone(),
1808 f.source.clone(),
1809 f.sink.clone(),
1810 );
1811 if seen.insert(key) {
1812 out.push(f);
1813 }
1814 }
1815 out.sort_by(|a, b| {
1816 b.severity
1817 .cmp(&a.severity)
1818 .then_with(|| a.rule_id.cmp(&b.rule_id))
1819 .then_with(|| a.contract.cmp(&b.contract))
1820 .then_with(|| a.circuit.cmp(&b.circuit))
1821 .then_with(|| a.source.cmp(&b.source))
1822 });
1823 out
1824}
1825
1826fn is_allowed(f: &StaticFinding, allow: &[String]) -> bool {
1827 if allow.is_empty() {
1828 return false;
1829 }
1830
1831 let mut source_keys = Vec::with_capacity(4);
1838 source_keys.push(f.source.clone());
1839 if let Some(bare_witness) = f.source.strip_prefix("witness:") {
1840 source_keys.push(bare_witness.to_owned());
1841 if let Some((root, _)) = bare_witness.split_once('.') {
1842 source_keys.push(format!("witness:{root}"));
1843 source_keys.push(root.to_owned());
1844 }
1845 }
1846
1847 allow.iter().any(|pat| {
1848 source_keys.iter().any(|src| {
1849 pat == src
1850 || *pat == format!("{}.{}::{src}", f.contract, f.circuit)
1851 || *pat == format!("{}::{src}", f.rule_id)
1852 || *pat == format!("{}::{}.{}::{src}", f.rule_id, f.contract, f.circuit)
1853 })
1854 })
1855}
1856
1857#[must_use]
1863pub fn format_human(reports: &[ContractAuditReport]) -> String {
1864 let mut out = String::new();
1865 let total_circuits: usize = reports.iter().map(|r| r.circuits_analyzed).sum();
1866 let total_findings: usize = reports.iter().map(|r| r.findings.len()).sum();
1867 let high: usize = reports
1868 .iter()
1869 .flat_map(|r| &r.findings)
1870 .filter(|f| f.severity == Severity::High)
1871 .count();
1872 let medium: usize = reports
1873 .iter()
1874 .flat_map(|r| &r.findings)
1875 .filter(|f| f.severity == Severity::Medium)
1876 .count();
1877 let low: usize = reports
1878 .iter()
1879 .flat_map(|r| &r.findings)
1880 .filter(|f| f.severity == Severity::Low)
1881 .count();
1882
1883 let _ = writeln!(
1884 out,
1885 "Static privacy audit: {} contract(s), {} exported circuit(s), {} finding(s) ({high} high, {medium} medium, {low} low)",
1886 reports.len(),
1887 total_circuits,
1888 total_findings
1889 );
1890
1891 for report in reports {
1892 if report.findings.is_empty() {
1893 let _ = writeln!(
1894 out,
1895 " [PASS] {} ({} circuit(s), {} witness(es))",
1896 report.contract,
1897 report.circuits_analyzed,
1898 report.witnesses_found.len()
1899 );
1900 continue;
1901 }
1902 let _ = writeln!(
1903 out,
1904 "\n {} ({} finding(s)):",
1905 report.contract,
1906 report.findings.len()
1907 );
1908 for f in &report.findings {
1909 let _ = writeln!(
1910 out,
1911 " [{:<6}] {} ({}) {}.{}",
1912 f.severity.as_str().to_ascii_uppercase(),
1913 f.rule_id,
1914 f.rule.slug(),
1915 f.contract,
1916 f.circuit
1917 );
1918 match (f.source_file.as_deref(), f.span.as_ref()) {
1919 (Some(file), Some(span)) => {
1920 let _ = writeln!(
1921 out,
1922 " at {file}:{}:{}",
1923 span.start_line, span.start_col
1924 );
1925 }
1926 (Some(file), None) => {
1927 let _ = writeln!(out, " at {file}");
1928 }
1929 (None, Some(span)) => {
1930 let _ = writeln!(
1931 out,
1932 " at line {}:{}",
1933 span.start_line, span.start_col
1934 );
1935 }
1936 (None, None) => {}
1937 }
1938 let _ = writeln!(out, " {}", f.message);
1939 let _ = writeln!(out, " fix: {}", f.remediation);
1940 }
1941 }
1942 out
1943}
1944
1945#[must_use]
1947pub fn format_json(reports: &[ContractAuditReport]) -> serde_json::Value {
1948 let high: usize = reports
1949 .iter()
1950 .flat_map(|r| &r.findings)
1951 .filter(|f| f.severity == Severity::High)
1952 .count();
1953 let medium: usize = reports
1954 .iter()
1955 .flat_map(|r| &r.findings)
1956 .filter(|f| f.severity == Severity::Medium)
1957 .count();
1958 let low: usize = reports
1959 .iter()
1960 .flat_map(|r| &r.findings)
1961 .filter(|f| f.severity == Severity::Low)
1962 .count();
1963 serde_json::json!({
1964 "schema_version": 1,
1965 "summary": {
1966 "contracts": reports.len(),
1967 "circuits_analyzed": reports.iter().map(|r| r.circuits_analyzed).sum::<usize>(),
1968 "findings_total": high + medium + low,
1969 "high": high,
1970 "medium": medium,
1971 "low": low,
1972 },
1973 "contracts": reports,
1974 })
1975}
1976
1977fn sarif_language_tag(lang: Option<&FrontendLanguage>, findings: &[StaticFinding]) -> String {
1978 match lang {
1979 Some(FrontendLanguage::Pact5) => "pact".to_owned(),
1980 Some(FrontendLanguage::Compact) => "compact".to_owned(),
1981 Some(FrontendLanguage::Custom(name)) => name.to_ascii_lowercase(),
1982 None => {
1983 if findings.iter().any(|f| {
1984 f.source_file.as_deref().is_some_and(|p| {
1985 std::path::Path::new(p)
1986 .extension()
1987 .is_some_and(|ext| ext.eq_ignore_ascii_case("pact"))
1988 })
1989 }) {
1990 "pact".to_owned()
1991 } else {
1992 "compact".to_owned()
1993 }
1994 }
1995 }
1996}
1997
1998fn sarif_artifact_uri(lang: Option<&FrontendLanguage>, finding: &StaticFinding) -> String {
1999 if let Some(ref file) = finding.source_file {
2000 return file.clone();
2001 }
2002 if let Some(file) = finding.span.as_ref().and_then(|s| s.file.as_ref()) {
2003 return file.clone();
2004 }
2005 match lang {
2006 Some(FrontendLanguage::Pact5) => format!("{}.pact", finding.contract),
2007 Some(FrontendLanguage::Compact) | None => format!("{}.compact", finding.contract),
2008 Some(FrontendLanguage::Custom(name)) => {
2009 format!("{}.{}", finding.contract, name.to_ascii_lowercase())
2010 }
2011 }
2012}
2013
2014#[must_use]
2017pub fn format_sarif(reports: &[ContractAuditReport]) -> serde_json::Value {
2018 let mut lang_tags = BTreeSet::new();
2019 for report in reports {
2020 lang_tags.insert(sarif_language_tag(
2021 report.frontend_language.as_ref(),
2022 &report.findings,
2023 ));
2024 }
2025 if lang_tags.is_empty() {
2026 lang_tags.insert("compact".to_owned());
2027 }
2028 let mut tags = Vec::with_capacity(2 + lang_tags.len());
2029 tags.push("privacy".to_owned());
2030 tags.push("zk".to_owned());
2031 tags.extend(lang_tags);
2032
2033 let rules: Vec<serde_json::Value> = AuditRule::ALL
2034 .iter()
2035 .map(|r| {
2036 serde_json::json!({
2037 "id": r.id(),
2038 "name": r.slug(),
2039 "shortDescription": { "text": r.short_description() },
2040 "defaultConfiguration": { "level": r.default_severity().sarif_level() },
2041 "properties": {
2042 "tags": tags,
2043 "severity": r.default_severity().as_str(),
2044 }
2045 })
2046 })
2047 .collect();
2048
2049 let results: Vec<serde_json::Value> = reports
2050 .iter()
2051 .flat_map(|report| {
2052 let lang = report.frontend_language.as_ref();
2053 report.findings.iter().map(move |f| (lang, f))
2054 })
2055 .map(|(lang, f)| {
2056 let uri = sarif_artifact_uri(lang, f);
2057 let mut physical_location = serde_json::json!({
2058 "artifactLocation": { "uri": uri }
2059 });
2060 if let Some(ref span) = f.span {
2061 physical_location["region"] = serde_json::json!({
2062 "startLine": span.start_line,
2063 "startColumn": span.start_col,
2064 "endLine": span.end_line,
2065 "endColumn": span.end_col,
2066 });
2067 }
2068 serde_json::json!({
2069 "ruleId": f.rule_id,
2070 "level": f.severity.sarif_level(),
2071 "message": { "text": format!("{} Remediation: {}", f.message, f.remediation) },
2072 "locations": [{
2073 "physicalLocation": physical_location,
2074 "logicalLocations": [{
2075 "name": f.circuit,
2076 "fullyQualifiedName": format!("{}.{}", f.contract, f.circuit),
2077 "kind": "function"
2078 }]
2079 }],
2080 "properties": {
2081 "contract": f.contract,
2082 "circuit": f.circuit,
2083 "source": f.source,
2084 "sink": f.sink,
2085 "severity": f.severity.as_str(),
2086 }
2087 })
2088 })
2089 .collect();
2090
2091 serde_json::json!({
2092 "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
2093 "version": "2.1.0",
2094 "runs": [{
2095 "tool": {
2096 "driver": {
2097 "name": "moonproof-audit",
2098 "version": env!("CARGO_PKG_VERSION"),
2099 "informationUri": "https://moonproof.dev",
2100 "rules": rules
2101 }
2102 },
2103 "results": results
2104 }]
2105 })
2106}
2107
2108#[cfg(test)]
2113mod tests {
2114 use super::*;
2115 use indexmap::IndexMap;
2116 use moonproof_runtime_ir::ir::{
2117 Argument, BindingTarget, Constructor, DebugInfo, FrontendLanguage, FrontendMeta, IntLit,
2118 Native, PrivacyClass, PrivacyMeta, SourceSpan, StateValue, StructField, TypeDescriptor,
2119 Witness,
2120 };
2121
2122 fn empty_ir() -> MoonIr {
2123 MoonIr {
2124 schema_version: 2,
2125 compiler_version: "test".to_owned(),
2126 language_version: "0.28".to_owned(),
2127 runtime_version: "0.14".to_owned(),
2128 contracts: Vec::new(),
2129 ledger: Vec::new(),
2130 witnesses: vec![Witness {
2131 name: "secret_key".to_owned(),
2132 arguments: Vec::new(),
2133 result_type: TypeDescriptor::Bytes { length: 32 },
2134 }],
2135 natives: vec![
2136 Native {
2137 name: "persistentHash".to_owned(),
2138 internal_uniq: Some(10),
2139 host_symbol: "persistentHash".to_owned(),
2140 intrinsic: None,
2141 class: "circuit".to_owned(),
2142 arguments: Vec::new(),
2143 result_type: TypeDescriptor::Bytes { length: 32 },
2144 },
2145 Native {
2146 name: "persistentCommit".to_owned(),
2147 internal_uniq: Some(11),
2148 host_symbol: "persistentCommit".to_owned(),
2149 intrinsic: None,
2150 class: "circuit".to_owned(),
2151 arguments: Vec::new(),
2152 result_type: TypeDescriptor::Bytes { length: 32 },
2153 },
2154 ],
2155 circuits: Vec::new(),
2156 descriptors: IndexMap::default(),
2157 constructor: Constructor {
2158 arguments: Vec::new(),
2159 initial_state: StateValue::Array { items: Vec::new() },
2160 init_ops: Vec::new(),
2161 register_operations: Vec::new(),
2162 body: Statement::Noop,
2163 },
2164 external_contracts: Vec::new(),
2165 pure_circuits: Vec::new(),
2166 frontend: None,
2167 debug_info: None,
2168 capabilities: None,
2169 workflows: Vec::new(),
2170 privacy: None,
2171 type_roles: IndexMap::default(),
2172 }
2173 }
2174
2175 fn circuit(name: &str, exported: bool, args: Vec<Argument>, body: Statement) -> CircuitBody {
2176 CircuitBody {
2177 name: name.to_owned(),
2178 internal_name: name.to_owned(),
2179 internal_uniq: None,
2180 exported,
2181 pure: false,
2182 proof: exported,
2183 arguments: args,
2184 result_type: TypeDescriptor::Bytes { length: 32 },
2185 body,
2186 }
2187 }
2188
2189 fn call_witness(name: &str) -> Expression {
2190 Expression::Call {
2191 function: name.to_owned(),
2192 function_uniq: None,
2193 arguments: Vec::new(),
2194 }
2195 }
2196
2197 #[test]
2198 fn mp001_detects_direct_witness_disclosure_and_sanitizes_after_hash() {
2199 let mut ir = empty_ir();
2200 ir.circuits.push(circuit(
2202 "leak",
2203 true,
2204 Vec::new(),
2205 Statement::Expr {
2206 value: call_witness("secret_key"),
2207 },
2208 ));
2209 ir.circuits.push(circuit(
2211 "safe",
2212 true,
2213 vec![Argument {
2214 name: "expected".to_owned(),
2215 arg_type: TypeDescriptor::Bytes { length: 32 },
2216 }],
2217 Statement::Seq {
2218 items: vec![
2219 Statement::Const {
2220 binding: BindingTarget {
2221 name: "s".to_owned(),
2222 binding_type: TypeDescriptor::Bytes { length: 32 },
2223 },
2224 value: call_witness("secret_key"),
2225 },
2226 Statement::Const {
2227 binding: BindingTarget {
2228 name: "h".to_owned(),
2229 binding_type: TypeDescriptor::Bytes { length: 32 },
2230 },
2231 value: Expression::Call {
2232 function: "persistentHash".to_owned(),
2233 function_uniq: Some(10),
2234 arguments: vec![Expression::Var {
2235 name: "s".to_owned(),
2236 }],
2237 },
2238 },
2239 Statement::Expr {
2240 value: Expression::Assert {
2241 cond: Box::new(Expression::Eq {
2242 of_type: None,
2243 left: Box::new(Expression::Var {
2244 name: "h".to_owned(),
2245 }),
2246 right: Box::new(Expression::Var {
2247 name: "expected".to_owned(),
2248 }),
2249 }),
2250 message: "bad secret".to_owned(),
2251 },
2252 },
2253 Statement::Expr {
2254 value: Expression::Var {
2255 name: "h".to_owned(),
2256 },
2257 },
2258 ],
2259 },
2260 ));
2261
2262 let report = audit_ir("vault", &ir, &StaticAuditOptions::default());
2263 assert!(report
2264 .findings
2265 .iter()
2266 .any(|f| f.circuit == "leak" && f.rule == AuditRule::DirectWitnessDisclosure));
2267 assert!(
2268 report.findings.iter().all(|f| f.circuit != "safe"),
2269 "expected zero findings for safe circuit, got {:?}",
2270 report.findings
2271 );
2272 }
2273
2274 #[test]
2275 #[allow(clippy::too_many_lines)]
2276 fn mp002_mp003_mp004_and_interprocedural_helper_propagation() {
2277 let mut ir = empty_ir();
2278 ir.circuits.push(circuit(
2280 "add_one",
2281 false,
2282 vec![Argument {
2283 name: "x".to_owned(),
2284 arg_type: TypeDescriptor::Field,
2285 }],
2286 Statement::Expr {
2287 value: Expression::Binop {
2288 op: "+".to_owned(),
2289 bits: None,
2290 of_type: None,
2291 left: Box::new(Expression::Var {
2292 name: "x".to_owned(),
2293 }),
2294 right: Box::new(Expression::Literal {
2295 value: RuntimeValue::Int(1),
2296 }),
2297 },
2298 },
2299 ));
2300 ir.circuits.push(circuit(
2303 "risky",
2304 true,
2305 Vec::new(),
2306 Statement::Seq {
2307 items: vec![
2308 Statement::Const {
2309 binding: BindingTarget {
2310 name: "s".to_owned(),
2311 binding_type: TypeDescriptor::Field,
2312 },
2313 value: call_witness("secret_key"),
2314 },
2315 Statement::Expr {
2316 value: Expression::Assert {
2317 cond: Box::new(Expression::Neq {
2318 of_type: None,
2319 left: Box::new(Expression::Var {
2320 name: "s".to_owned(),
2321 }),
2322 right: Box::new(Expression::Literal {
2323 value: RuntimeValue::Int(0),
2324 }),
2325 }),
2326 message: "non-zero".to_owned(),
2327 },
2328 },
2329 Statement::If {
2330 cond: Expression::Eq {
2331 of_type: None,
2332 left: Box::new(Expression::Var {
2333 name: "s".to_owned(),
2334 }),
2335 right: Box::new(Expression::Literal {
2336 value: RuntimeValue::Int(1),
2337 }),
2338 },
2339 then: Box::new(Statement::Expr {
2340 value: Expression::AdtOp(AdtOpInvocation {
2341 adt: "Counter".to_owned(),
2342 operation: "increment".to_owned(),
2343 op_class: "update".to_owned(),
2344 op_class_coin_index: None,
2345 op_class_recipient_index: None,
2346 field: Some("count".to_owned()),
2347 field_path: Vec::new(),
2348 arguments: vec![Expression::Literal {
2349 value: RuntimeValue::Int(1),
2350 }],
2351 result_type: TypeDescriptor::Tuple { types: Vec::new() },
2352 vm_ops: Vec::new(),
2353 }),
2354 }),
2355 r#else: None,
2356 },
2357 Statement::Const {
2358 binding: BindingTarget {
2359 name: "weak".to_owned(),
2360 binding_type: TypeDescriptor::Bytes { length: 32 },
2361 },
2362 value: Expression::Call {
2363 function: "persistentCommit".to_owned(),
2364 function_uniq: Some(11),
2365 arguments: vec![
2366 Expression::Var {
2367 name: "s".to_owned(),
2368 },
2369 Expression::Default {
2370 of_type: TypeDescriptor::Bytes { length: 32 },
2371 },
2372 ],
2373 },
2374 },
2375 Statement::Expr {
2376 value: Expression::Call {
2377 function: "add_one".to_owned(),
2378 function_uniq: None,
2379 arguments: vec![Expression::Var {
2380 name: "s".to_owned(),
2381 }],
2382 },
2383 },
2384 ],
2385 },
2386 ));
2387
2388 let report = audit_ir("demo", &ir, &StaticAuditOptions::default());
2389 let rules: BTreeSet<AuditRule> = report.findings.iter().map(|f| f.rule).collect();
2390 assert!(rules.contains(&AuditRule::DerivedWitnessDisclosure));
2391 assert!(rules.contains(&AuditRule::ImplicitControlFlowLeak));
2392 assert!(rules.contains(&AuditRule::WeakCommitmentRandomness));
2393 assert!(!rules.contains(&AuditRule::UnconstrainedWitness));
2395
2396 let sarif = format_sarif(std::slice::from_ref(&report));
2398 assert_eq!(sarif["version"], "2.1.0");
2399 assert_eq!(sarif["runs"][0]["results"].as_array().unwrap().len(), 3);
2400
2401 let allowed = audit_ir(
2402 "demo",
2403 &ir,
2404 &StaticAuditOptions {
2405 taint_args: false,
2406 allow: vec!["demo.risky::secret_key".to_owned()],
2407 },
2408 );
2409 assert_eq!(allowed.findings, Vec::new());
2410 }
2411
2412 #[test]
2413 #[allow(clippy::too_many_lines)]
2414 fn pact5_ir_v3_mp001_mp004_mp005_sarif_spans_and_remediation() {
2415 let mut circuit_spans = IndexMap::new();
2416 circuit_spans.insert(
2417 "unsafe_transfer".to_owned(),
2418 SourceSpan {
2419 file: Some("vault.pact".to_owned()),
2420 start_line: 24,
2421 start_col: 4,
2422 end_line: 39,
2423 end_col: 5,
2424 },
2425 );
2426 circuit_spans.insert(
2427 "safe_transfer".to_owned(),
2428 SourceSpan {
2429 file: None,
2430 start_line: 41,
2431 start_col: 4,
2432 end_line: 55,
2433 end_col: 5,
2434 },
2435 );
2436
2437 let mut field_classes = IndexMap::new();
2438 field_classes.insert(
2441 "unsafe_transfer.secret_amount".to_owned(),
2442 PrivacyClass::Private,
2443 );
2444 field_classes.insert(
2445 "unsafe_transfer.public_memo".to_owned(),
2446 PrivacyClass::Public,
2447 );
2448 field_classes.insert(
2449 "safe_transfer.secret_amount".to_owned(),
2450 PrivacyClass::Shielded,
2451 );
2452
2453 let mut ir = MoonIr::new_v3("pact5c-0.1.0", "pact-5.0", "0.14.0")
2454 .with_frontend(FrontendMeta {
2455 language: FrontendLanguage::Pact5,
2456 frontend_version: "0.1.0".to_owned(),
2457 source_module: Some("free.vault".to_owned()),
2458 source_hash: None,
2459 metadata: IndexMap::new(),
2460 })
2461 .with_debug_info(DebugInfo {
2462 sources: vec!["vault.pact".to_owned()],
2463 circuit_spans,
2464 field_spans: IndexMap::new(),
2465 })
2466 .with_privacy(PrivacyMeta {
2467 field_classes,
2468 field_roles: IndexMap::new(),
2469 circuit_bounds: IndexMap::new(),
2470 });
2471
2472 ir.add_witness(Witness {
2473 name: "blinding_nonce".to_owned(),
2474 arguments: Vec::new(),
2475 result_type: TypeDescriptor::Bytes { length: 32 },
2476 });
2477 ir.add_native(Native::new_intrinsic(
2478 "zk_hash",
2479 "mp:hash/persistent",
2480 "hash",
2481 Vec::new(),
2482 TypeDescriptor::Bytes { length: 32 },
2483 ));
2484 ir.add_native(Native::new_intrinsic(
2485 "zk_commit",
2486 "mp:commit/persistent",
2487 "commit",
2488 Vec::new(),
2489 TypeDescriptor::Bytes { length: 32 },
2490 ));
2491 ir.add_native(Native::new_intrinsic(
2492 "zk_transient_commit",
2493 "mp:commit/transient",
2494 "commit",
2495 Vec::new(),
2496 TypeDescriptor::Field,
2497 ));
2498
2499 ir.add_circuit(circuit(
2503 "unsafe_transfer",
2504 true,
2505 vec![
2506 Argument {
2507 name: "secret_amount".to_owned(),
2508 arg_type: TypeDescriptor::Field,
2509 },
2510 Argument {
2511 name: "public_memo".to_owned(),
2512 arg_type: TypeDescriptor::Bytes { length: 32 },
2513 },
2514 ],
2515 Statement::Seq {
2516 items: vec![
2517 Statement::Const {
2518 binding: BindingTarget {
2519 name: "unused_witness".to_owned(),
2520 binding_type: TypeDescriptor::Bytes { length: 32 },
2521 },
2522 value: call_witness("blinding_nonce"),
2523 },
2524 Statement::Const {
2525 binding: BindingTarget {
2526 name: "weak_commit".to_owned(),
2527 binding_type: TypeDescriptor::Bytes { length: 32 },
2528 },
2529 value: Expression::Call {
2530 function: "zk_commit".to_owned(),
2531 function_uniq: None,
2532 arguments: vec![
2533 Expression::Var {
2534 name: "secret_amount".to_owned(),
2535 },
2536 Expression::Default {
2537 of_type: TypeDescriptor::Bytes { length: 32 },
2538 },
2539 ],
2540 },
2541 },
2542 Statement::Expr {
2543 value: Expression::Var {
2544 name: "secret_amount".to_owned(),
2545 },
2546 },
2547 ],
2548 },
2549 ));
2550
2551 ir.add_circuit(circuit(
2554 "safe_transfer",
2555 true,
2556 vec![
2557 Argument {
2558 name: "secret_amount".to_owned(),
2559 arg_type: TypeDescriptor::Field,
2560 },
2561 Argument {
2562 name: "expected_digest".to_owned(),
2563 arg_type: TypeDescriptor::Bytes { length: 32 },
2564 },
2565 ],
2566 Statement::Seq {
2567 items: vec![
2568 Statement::Const {
2569 binding: BindingTarget {
2570 name: "r".to_owned(),
2571 binding_type: TypeDescriptor::Bytes { length: 32 },
2572 },
2573 value: call_witness("blinding_nonce"),
2574 },
2575 Statement::Const {
2576 binding: BindingTarget {
2577 name: "c".to_owned(),
2578 binding_type: TypeDescriptor::Field,
2579 },
2580 value: Expression::Call {
2581 function: "zk_transient_commit".to_owned(),
2582 function_uniq: None,
2583 arguments: vec![
2584 Expression::Var {
2585 name: "secret_amount".to_owned(),
2586 },
2587 Expression::Var {
2588 name: "r".to_owned(),
2589 },
2590 ],
2591 },
2592 },
2593 Statement::Const {
2594 binding: BindingTarget {
2595 name: "digest".to_owned(),
2596 binding_type: TypeDescriptor::Bytes { length: 32 },
2597 },
2598 value: Expression::Call {
2599 function: "zk_hash".to_owned(),
2600 function_uniq: None,
2601 arguments: vec![Expression::Var {
2602 name: "c".to_owned(),
2603 }],
2604 },
2605 },
2606 Statement::Expr {
2607 value: Expression::Assert {
2608 cond: Box::new(Expression::Eq {
2609 of_type: None,
2610 left: Box::new(Expression::Var {
2611 name: "digest".to_owned(),
2612 }),
2613 right: Box::new(Expression::Var {
2614 name: "expected_digest".to_owned(),
2615 }),
2616 }),
2617 message: "commitment mismatch".to_owned(),
2618 },
2619 },
2620 Statement::Expr {
2621 value: Expression::Var {
2622 name: "digest".to_owned(),
2623 },
2624 },
2625 ],
2626 },
2627 ));
2628
2629 let report = audit_ir("vault", &ir, &StaticAuditOptions::default());
2631 assert_eq!(report.frontend_language, Some(FrontendLanguage::Pact5));
2632 assert!(
2633 report.findings.iter().all(|f| f.circuit != "safe_transfer"),
2634 "expected zero findings for safe_transfer, got {:?}",
2635 report.findings
2636 );
2637
2638 let mp001 = report
2639 .findings
2640 .iter()
2641 .find(|f| f.rule == AuditRule::DirectWitnessDisclosure)
2642 .expect("expected MP001 on private Pact parameter");
2643 assert_eq!(mp001.source, "arg:secret_amount");
2644 assert_eq!(mp001.source_file.as_deref(), Some("vault.pact"));
2645 assert_eq!(
2646 mp001.span,
2647 Some(SourceSpan {
2648 file: Some("vault.pact".to_owned()),
2649 start_line: 24,
2650 start_col: 4,
2651 end_line: 39,
2652 end_col: 5,
2653 })
2654 );
2655 assert!(mp001.remediation.contains("(zk.commit"));
2656 assert!(mp001.remediation.contains("(zk.disclose"));
2657
2658 let mp004 = report
2659 .findings
2660 .iter()
2661 .find(|f| f.rule == AuditRule::WeakCommitmentRandomness)
2662 .expect("expected MP004 on mp:commit/persistent with default opening");
2663 assert!(mp004.remediation.contains("(zk.commit"));
2664
2665 let mp005 = report
2666 .findings
2667 .iter()
2668 .find(|f| f.rule == AuditRule::UnconstrainedWitness)
2669 .expect("expected MP005 on unconstrained blinding_nonce");
2670 assert_eq!(mp005.source, "witness:blinding_nonce");
2671 assert!(mp005.remediation.contains("(enforce"));
2672
2673 let sarif = format_sarif(std::slice::from_ref(&report));
2675 let rule_tags = sarif["runs"][0]["tool"]["driver"]["rules"][0]["properties"]["tags"]
2676 .as_array()
2677 .expect("tags array");
2678 assert!(rule_tags.iter().any(|t| t == "pact"));
2679 assert!(!rule_tags.iter().any(|t| t == "compact"));
2680
2681 let results = sarif["runs"][0]["results"].as_array().expect("results");
2682 assert_eq!(results.len(), 3);
2683 for res in results {
2684 let phys = &res["locations"][0]["physicalLocation"];
2685 assert_eq!(phys["artifactLocation"]["uri"], "vault.pact");
2686 assert_eq!(phys["region"]["startLine"], 24);
2687 assert_eq!(phys["region"]["startColumn"], 4);
2688 assert_eq!(phys["region"]["endLine"], 39);
2689 assert_eq!(phys["region"]["endColumn"], 5);
2690 }
2691 }
2692
2693 #[test]
2694 #[allow(clippy::too_many_lines)]
2695 fn privacy_meta_taints_private_struct_fields_on_args_and_new() {
2696 let note_ty = TypeDescriptor::Struct {
2697 name: "ShieldedNote".to_owned(),
2698 elements: vec![
2699 StructField {
2700 name: "owner".to_owned(),
2701 field_type: TypeDescriptor::Bytes { length: 32 },
2702 },
2703 StructField {
2704 name: "blinding".to_owned(),
2705 field_type: TypeDescriptor::Bytes { length: 32 },
2706 },
2707 ],
2708 };
2709
2710 let mut field_classes = IndexMap::new();
2711 field_classes.insert("ShieldedNote.blinding".to_owned(), PrivacyClass::Private);
2712
2713 let mut ir = MoonIr::new_v3("pact5c-0.1.0", "pact-5.0", "0.14.0")
2714 .with_frontend(FrontendMeta {
2715 language: FrontendLanguage::Pact5,
2716 frontend_version: "0.1.0".to_owned(),
2717 source_module: Some("free.notes".to_owned()),
2718 source_hash: None,
2719 metadata: IndexMap::new(),
2720 })
2721 .with_privacy(PrivacyMeta {
2722 field_classes,
2723 field_roles: IndexMap::new(),
2724 circuit_bounds: IndexMap::new(),
2725 });
2726
2727 ir.add_native(Native::new_intrinsic(
2728 "poseidon",
2729 "mp:hash/transient",
2730 "hash",
2731 Vec::new(),
2732 TypeDescriptor::Field,
2733 ));
2734
2735 ir.add_circuit(circuit(
2737 "read_owner",
2738 true,
2739 vec![Argument {
2740 name: "note".to_owned(),
2741 arg_type: note_ty.clone(),
2742 }],
2743 Statement::Expr {
2744 value: Expression::EltRef {
2745 value: Box::new(Expression::Var {
2746 name: "note".to_owned(),
2747 }),
2748 field: "owner".to_owned(),
2749 index: IntLit::ZERO,
2750 },
2751 },
2752 ));
2753
2754 ir.add_circuit(circuit(
2756 "leak_blinding",
2757 true,
2758 vec![Argument {
2759 name: "note".to_owned(),
2760 arg_type: note_ty.clone(),
2761 }],
2762 Statement::Expr {
2763 value: Expression::EltRef {
2764 value: Box::new(Expression::Var {
2765 name: "note".to_owned(),
2766 }),
2767 field: "blinding".to_owned(),
2768 index: IntLit::ONE,
2769 },
2770 },
2771 ));
2772
2773 ir.add_circuit(circuit(
2775 "leak_constructed_note",
2776 true,
2777 vec![
2778 Argument {
2779 name: "owner".to_owned(),
2780 arg_type: TypeDescriptor::Bytes { length: 32 },
2781 },
2782 Argument {
2783 name: "raw_blind".to_owned(),
2784 arg_type: TypeDescriptor::Bytes { length: 32 },
2785 },
2786 ],
2787 Statement::Expr {
2788 value: Expression::New {
2789 of_type: note_ty.clone(),
2790 arguments: vec![
2791 Expression::Var {
2792 name: "owner".to_owned(),
2793 },
2794 Expression::Var {
2795 name: "raw_blind".to_owned(),
2796 },
2797 ],
2798 },
2799 },
2800 ));
2801
2802 ir.add_circuit(circuit(
2804 "hash_blinding",
2805 true,
2806 vec![Argument {
2807 name: "note".to_owned(),
2808 arg_type: note_ty,
2809 }],
2810 Statement::Expr {
2811 value: Expression::Call {
2812 function: "poseidon".to_owned(),
2813 function_uniq: None,
2814 arguments: vec![Expression::EltRef {
2815 value: Box::new(Expression::Var {
2816 name: "note".to_owned(),
2817 }),
2818 field: "blinding".to_owned(),
2819 index: IntLit::ONE,
2820 }],
2821 },
2822 },
2823 ));
2824
2825 let report = audit_ir("notes", &ir, &StaticAuditOptions::default());
2826 assert!(report.findings.iter().all(|f| f.circuit != "read_owner"));
2827 assert!(report.findings.iter().all(|f| f.circuit != "hash_blinding"));
2828 assert!(report.findings.iter().any(|f| {
2829 f.circuit == "leak_blinding"
2830 && f.rule == AuditRule::DirectWitnessDisclosure
2831 && f.source == "arg:note.blinding"
2832 }));
2833 assert!(report.findings.iter().any(|f| {
2834 f.circuit == "leak_constructed_note"
2835 && f.rule == AuditRule::DirectWitnessDisclosure
2836 && f.source == "field:ShieldedNote.blinding"
2837 }));
2838
2839 let sarif = format_sarif(std::slice::from_ref(&report));
2841 let first_phys = &sarif["runs"][0]["results"][0]["locations"][0]["physicalLocation"];
2842 assert_eq!(first_phys["artifactLocation"]["uri"], "notes.pact");
2843 assert!(first_phys.get("region").is_none());
2844 }
2845
2846 #[test]
2847 fn native_resolve_intrinsic_strips_compact_runtime_prefix() {
2848 let mut ir = empty_ir();
2849 ir.natives = vec![Native {
2850 name: "hash_prefixed".to_owned(),
2851 internal_uniq: Some(99),
2852 host_symbol: "__compactRuntime.persistentHash".to_owned(),
2853 intrinsic: None,
2854 class: "circuit".to_owned(),
2855 arguments: Vec::new(),
2856 result_type: TypeDescriptor::Bytes { length: 32 },
2857 }];
2858 ir.circuits.push(circuit(
2859 "sanitized",
2860 true,
2861 vec![Argument {
2862 name: "expected".to_owned(),
2863 arg_type: TypeDescriptor::Bytes { length: 32 },
2864 }],
2865 Statement::Seq {
2866 items: vec![
2867 Statement::Const {
2868 binding: BindingTarget {
2869 name: "h".to_owned(),
2870 binding_type: TypeDescriptor::Bytes { length: 32 },
2871 },
2872 value: Expression::Call {
2873 function: "hash_prefixed".to_owned(),
2874 function_uniq: Some(99),
2875 arguments: vec![call_witness("secret_key")],
2876 },
2877 },
2878 Statement::Expr {
2879 value: Expression::Assert {
2880 cond: Box::new(Expression::Eq {
2881 of_type: None,
2882 left: Box::new(Expression::Var {
2883 name: "h".to_owned(),
2884 }),
2885 right: Box::new(Expression::Var {
2886 name: "expected".to_owned(),
2887 }),
2888 }),
2889 message: "match".to_owned(),
2890 },
2891 },
2892 Statement::Expr {
2893 value: Expression::Var {
2894 name: "h".to_owned(),
2895 },
2896 },
2897 ],
2898 },
2899 ));
2900
2901 let report = audit_ir("prefixed", &ir, &StaticAuditOptions::default());
2902 assert_eq!(report.findings, Vec::new());
2903 }
2904
2905 #[test]
2906 fn nested_vector_and_tuple_struct_fields_propagate_taint() {
2907 let note_ty = TypeDescriptor::Struct {
2908 name: "ShieldedNote".to_owned(),
2909 elements: vec![
2910 StructField {
2911 name: "owner".to_owned(),
2912 field_type: TypeDescriptor::Bytes { length: 32 },
2913 },
2914 StructField {
2915 name: "blinding".to_owned(),
2916 field_type: TypeDescriptor::Bytes { length: 32 },
2917 },
2918 ],
2919 };
2920 let vec_notes_ty = TypeDescriptor::Vector {
2921 length: 4,
2922 elt_type: Box::new(note_ty.clone()),
2923 };
2924 let tuple_note_ty = TypeDescriptor::Tuple {
2925 types: vec![TypeDescriptor::Field, note_ty],
2926 };
2927
2928 let mut field_classes = IndexMap::new();
2929 field_classes.insert("ShieldedNote.blinding".to_owned(), PrivacyClass::Private);
2930
2931 let mut ir = MoonIr::new_v3("0.1.0", "0.1.0", "0.1.0").with_privacy(PrivacyMeta {
2932 field_classes,
2933 field_roles: IndexMap::new(),
2934 circuit_bounds: IndexMap::new(),
2935 });
2936
2937 ir.add_circuit(circuit(
2939 "leak_vec",
2940 true,
2941 vec![Argument {
2942 name: "notes".to_owned(),
2943 arg_type: vec_notes_ty.clone(),
2944 }],
2945 Statement::Expr {
2946 value: Expression::Var {
2947 name: "notes".to_owned(),
2948 },
2949 },
2950 ));
2951
2952 ir.add_circuit(circuit(
2954 "leak_vec_elem",
2955 true,
2956 vec![Argument {
2957 name: "notes".to_owned(),
2958 arg_type: vec_notes_ty,
2959 }],
2960 Statement::Expr {
2961 value: Expression::VectorRef {
2962 value: Box::new(Expression::Var {
2963 name: "notes".to_owned(),
2964 }),
2965 index: Box::new(Expression::Literal {
2966 value: RuntimeValue::Int(0),
2967 }),
2968 result_type: TypeDescriptor::Field,
2969 },
2970 },
2971 ));
2972
2973 ir.add_circuit(circuit(
2975 "leak_tuple",
2976 true,
2977 vec![Argument {
2978 name: "pair".to_owned(),
2979 arg_type: tuple_note_ty,
2980 }],
2981 Statement::Expr {
2982 value: Expression::Var {
2983 name: "pair".to_owned(),
2984 },
2985 },
2986 ));
2987
2988 let report = audit_ir("batch", &ir, &StaticAuditOptions::default());
2989 assert!(
2990 report.findings.iter().any(|f| {
2991 f.circuit == "leak_vec"
2992 && f.rule == AuditRule::DirectWitnessDisclosure
2993 && f.source == "arg:notes[].blinding"
2994 }),
2995 "expected MP001 on Vector<4, ShieldedNote>, got {:?}",
2996 report.findings
2997 );
2998 assert!(
2999 report.findings.iter().any(|f| {
3000 f.circuit == "leak_vec_elem"
3001 && f.rule == AuditRule::DerivedWitnessDisclosure
3002 && f.source == "arg:notes[].blinding"
3003 }),
3004 "expected MP002 on notes[0], got {:?}",
3005 report.findings
3006 );
3007 assert!(
3008 report.findings.iter().any(|f| {
3009 f.circuit == "leak_tuple"
3010 && f.rule == AuditRule::DirectWitnessDisclosure
3011 && f.source == "arg:pair.1.blinding"
3012 }),
3013 "expected MP001 on Tuple<Field, ShieldedNote>, got {:?}",
3014 report.findings
3015 );
3016 }
3017
3018 #[test]
3019 fn no_bare_name_privacy_contamination() {
3020 let public_struct = TypeDescriptor::Struct {
3021 name: "PublicInfo".to_owned(),
3022 elements: vec![StructField {
3023 name: "amount".to_owned(),
3024 field_type: TypeDescriptor::Field,
3025 }],
3026 };
3027
3028 let mut field_classes = IndexMap::new();
3029 field_classes.insert("amount".to_owned(), PrivacyClass::Private);
3031 field_classes.insert("other_circuit.amount".to_owned(), PrivacyClass::Private);
3033 field_classes.insert("OtherStruct.amount".to_owned(), PrivacyClass::Private);
3034
3035 let mut ir = MoonIr::new_v3("0.1.0", "0.1.0", "0.1.0").with_privacy(PrivacyMeta {
3036 field_classes,
3037 field_roles: IndexMap::new(),
3038 circuit_bounds: IndexMap::new(),
3039 });
3040
3041 ir.add_circuit(circuit(
3042 "read_public_arg",
3043 true,
3044 vec![Argument {
3045 name: "amount".to_owned(),
3046 arg_type: TypeDescriptor::Field,
3047 }],
3048 Statement::Expr {
3049 value: Expression::Var {
3050 name: "amount".to_owned(),
3051 },
3052 },
3053 ));
3054 ir.add_circuit(circuit(
3055 "read_public_struct",
3056 true,
3057 vec![Argument {
3058 name: "info".to_owned(),
3059 arg_type: public_struct,
3060 }],
3061 Statement::Expr {
3062 value: Expression::EltRef {
3063 value: Box::new(Expression::Var {
3064 name: "info".to_owned(),
3065 }),
3066 field: "amount".to_owned(),
3067 index: IntLit::ZERO,
3068 },
3069 },
3070 ));
3071
3072 let report = audit_ir("clean", &ir, &StaticAuditOptions::default());
3073 assert_eq!(report.findings, Vec::new());
3074 }
3075
3076 #[test]
3077 #[allow(clippy::too_many_lines)]
3078 fn allowlist_never_over_suppresses_field_struct_or_cross_namespace() {
3079 let note_ty = TypeDescriptor::Struct {
3080 name: "ShieldedNote".to_owned(),
3081 elements: vec![
3082 StructField {
3083 name: "blinding".to_owned(),
3084 field_type: TypeDescriptor::Bytes { length: 32 },
3085 },
3086 StructField {
3087 name: "secret".to_owned(),
3088 field_type: TypeDescriptor::Bytes { length: 32 },
3089 },
3090 ],
3091 };
3092
3093 let mut field_classes = IndexMap::new();
3094 field_classes.insert("ShieldedNote.blinding".to_owned(), PrivacyClass::Private);
3095 field_classes.insert("ShieldedNote.secret".to_owned(), PrivacyClass::Private);
3096 field_classes.insert("leak_arg.secret_key".to_owned(), PrivacyClass::Private);
3097
3098 let mut ir = empty_ir().with_privacy(PrivacyMeta {
3099 field_classes,
3100 field_roles: IndexMap::new(),
3101 circuit_bounds: IndexMap::new(),
3102 });
3103
3104 ir.add_circuit(circuit(
3106 "leak_struct",
3107 true,
3108 vec![
3109 Argument {
3110 name: "a".to_owned(),
3111 arg_type: TypeDescriptor::Bytes { length: 32 },
3112 },
3113 Argument {
3114 name: "b".to_owned(),
3115 arg_type: TypeDescriptor::Bytes { length: 32 },
3116 },
3117 ],
3118 Statement::Expr {
3119 value: Expression::New {
3120 of_type: note_ty,
3121 arguments: vec![
3122 Expression::Var {
3123 name: "a".to_owned(),
3124 },
3125 Expression::Var {
3126 name: "b".to_owned(),
3127 },
3128 ],
3129 },
3130 },
3131 ));
3132
3133 ir.add_circuit(circuit(
3135 "leak_arg",
3136 true,
3137 vec![Argument {
3138 name: "secret_key".to_owned(),
3139 arg_type: TypeDescriptor::Bytes { length: 32 },
3140 }],
3141 Statement::Expr {
3142 value: Expression::Var {
3143 name: "secret_key".to_owned(),
3144 },
3145 },
3146 ));
3147
3148 let report = audit_ir(
3152 "vault",
3153 &ir,
3154 &StaticAuditOptions {
3155 taint_args: false,
3156 allow: vec![
3157 "ShieldedNote".to_owned(),
3158 "field:ShieldedNote".to_owned(),
3159 "vault.leak_struct::ShieldedNote".to_owned(),
3160 "vault.leak_struct::field:ShieldedNote".to_owned(),
3161 "ShieldedNote.blinding".to_owned(),
3162 "secret_key".to_owned(),
3163 "witness:secret_key".to_owned(),
3164 "vault.leak_arg::secret_key".to_owned(),
3165 ],
3166 },
3167 );
3168 assert!(report
3169 .findings
3170 .iter()
3171 .any(|f| { f.circuit == "leak_struct" && f.source == "field:ShieldedNote.blinding" }));
3172 assert!(report
3173 .findings
3174 .iter()
3175 .any(|f| { f.circuit == "leak_struct" && f.source == "field:ShieldedNote.secret" }));
3176 assert!(report
3177 .findings
3178 .iter()
3179 .any(|f| { f.circuit == "leak_arg" && f.source == "arg:secret_key" }));
3180
3181 let exact = audit_ir(
3185 "vault",
3186 &ir,
3187 &StaticAuditOptions {
3188 taint_args: false,
3189 allow: vec![
3190 "vault.leak_struct::field:ShieldedNote.blinding".to_owned(),
3191 "vault.leak_arg::arg:secret_key".to_owned(),
3192 ],
3193 },
3194 );
3195 assert_eq!(exact.findings.len(), 1);
3196 assert_eq!(exact.findings[0].source, "field:ShieldedNote.secret");
3197 }
3198
3199 #[test]
3200 #[allow(clippy::too_many_lines)]
3201 fn helper_mp005_witness_propagation_and_multi_sink_params() {
3202 let mut ir = empty_ir();
3203 ir.circuits.push(circuit(
3205 "read_secret_helper",
3206 false,
3207 Vec::new(),
3208 Statement::Expr {
3209 value: call_witness("secret_key"),
3210 },
3211 ));
3212 ir.circuits.push(circuit(
3214 "verified_secret_helper",
3215 false,
3216 vec![Argument {
3217 name: "expected".to_owned(),
3218 arg_type: TypeDescriptor::Bytes { length: 32 },
3219 }],
3220 Statement::Seq {
3221 items: vec![
3222 Statement::Const {
3223 binding: BindingTarget {
3224 name: "h".to_owned(),
3225 binding_type: TypeDescriptor::Bytes { length: 32 },
3226 },
3227 value: Expression::Call {
3228 function: "persistentHash".to_owned(),
3229 function_uniq: Some(10),
3230 arguments: vec![call_witness("secret_key")],
3231 },
3232 },
3233 Statement::Expr {
3234 value: Expression::Assert {
3235 cond: Box::new(Expression::Eq {
3236 of_type: None,
3237 left: Box::new(Expression::Var {
3238 name: "h".to_owned(),
3239 }),
3240 right: Box::new(Expression::Var {
3241 name: "expected".to_owned(),
3242 }),
3243 }),
3244 message: "bad".to_owned(),
3245 },
3246 },
3247 Statement::Expr {
3248 value: Expression::Var {
3249 name: "h".to_owned(),
3250 },
3251 },
3252 ],
3253 },
3254 ));
3255 ir.circuits.push(circuit(
3257 "dual_sink_helper",
3258 false,
3259 vec![Argument {
3260 name: "x".to_owned(),
3261 arg_type: TypeDescriptor::Bytes { length: 32 },
3262 }],
3263 Statement::Seq {
3264 items: vec![
3265 Statement::Expr {
3266 value: Expression::AdtOp(AdtOpInvocation {
3267 adt: "Cell".to_owned(),
3268 operation: "write".to_owned(),
3269 op_class: "update".to_owned(),
3270 op_class_coin_index: None,
3271 op_class_recipient_index: None,
3272 field: Some("slot_a".to_owned()),
3273 field_path: Vec::new(),
3274 arguments: vec![Expression::Var {
3275 name: "x".to_owned(),
3276 }],
3277 result_type: TypeDescriptor::Tuple { types: Vec::new() },
3278 vm_ops: Vec::new(),
3279 }),
3280 },
3281 Statement::Expr {
3282 value: Expression::Emit {
3283 event_version: 1,
3284 event_tag: 7,
3285 payload_length: 32,
3286 payload: Box::new(Expression::Var {
3287 name: "x".to_owned(),
3288 }),
3289 vm_ops: Vec::new(),
3290 },
3291 },
3292 ],
3293 },
3294 ));
3295
3296 ir.circuits.push(circuit(
3298 "caller_unconstrained",
3299 true,
3300 Vec::new(),
3301 Statement::Expr {
3302 value: Expression::Call {
3303 function: "persistentHash".to_owned(),
3304 function_uniq: Some(10),
3305 arguments: vec![Expression::Call {
3306 function: "read_secret_helper".to_owned(),
3307 function_uniq: None,
3308 arguments: Vec::new(),
3309 }],
3310 },
3311 },
3312 ));
3313
3314 ir.circuits.push(circuit(
3316 "caller_verified",
3317 true,
3318 vec![Argument {
3319 name: "expected".to_owned(),
3320 arg_type: TypeDescriptor::Bytes { length: 32 },
3321 }],
3322 Statement::Expr {
3323 value: Expression::Call {
3324 function: "verified_secret_helper".to_owned(),
3325 function_uniq: None,
3326 arguments: vec![Expression::Var {
3327 name: "expected".to_owned(),
3328 }],
3329 },
3330 },
3331 ));
3332
3333 ir.circuits.push(circuit(
3335 "caller_dual_sink",
3336 true,
3337 Vec::new(),
3338 Statement::Seq {
3339 items: vec![
3340 Statement::Const {
3341 binding: BindingTarget {
3342 name: "s".to_owned(),
3343 binding_type: TypeDescriptor::Bytes { length: 32 },
3344 },
3345 value: call_witness("secret_key"),
3346 },
3347 Statement::Expr {
3348 value: Expression::Assert {
3349 cond: Box::new(Expression::Neq {
3350 of_type: None,
3351 left: Box::new(Expression::Var {
3352 name: "s".to_owned(),
3353 }),
3354 right: Box::new(Expression::Default {
3355 of_type: TypeDescriptor::Bytes { length: 32 },
3356 }),
3357 }),
3358 message: "nz".to_owned(),
3359 },
3360 },
3361 Statement::Expr {
3362 value: Expression::Call {
3363 function: "dual_sink_helper".to_owned(),
3364 function_uniq: None,
3365 arguments: vec![Expression::Var {
3366 name: "s".to_owned(),
3367 }],
3368 },
3369 },
3370 ],
3371 },
3372 ));
3373
3374 let report = audit_ir("helpers", &ir, &StaticAuditOptions::default());
3375 assert!(
3376 report.findings.iter().any(|f| {
3377 f.circuit == "caller_unconstrained"
3378 && f.rule == AuditRule::UnconstrainedWitness
3379 && f.source == "witness:secret_key"
3380 }),
3381 "expected MP005 propagated from helper, got {:?}",
3382 report.findings
3383 );
3384 assert!(
3385 report
3386 .findings
3387 .iter()
3388 .all(|f| f.circuit != "caller_verified"),
3389 "expected 0 findings for caller_verified, got {:?}",
3390 report.findings
3391 );
3392 let dual_sinks: Vec<&StaticFinding> = report
3393 .findings
3394 .iter()
3395 .filter(|f| {
3396 f.circuit == "caller_dual_sink" && f.rule == AuditRule::DirectWitnessDisclosure
3397 })
3398 .collect();
3399 assert_eq!(
3400 dual_sinks.len(),
3401 2,
3402 "expected both LedgerOp and EventEmit sinks, got {dual_sinks:?}"
3403 );
3404 assert!(dual_sinks
3405 .iter()
3406 .any(|f| matches!(f.sink, SinkKind::LedgerOp { .. })));
3407 assert!(dual_sinks
3408 .iter()
3409 .any(|f| matches!(f.sink, SinkKind::EventEmit { .. })));
3410 }
3411
3412 #[test]
3413 #[allow(clippy::too_many_lines)]
3414 fn branch_local_assert_does_not_silence_mp005() {
3415 let mut ir = empty_ir();
3416 let assert_secret = || Statement::Expr {
3417 value: Expression::Assert {
3418 cond: Box::new(Expression::Neq {
3419 of_type: None,
3420 left: Box::new(Expression::Var {
3421 name: "s".to_owned(),
3422 }),
3423 right: Box::new(Expression::Default {
3424 of_type: TypeDescriptor::Bytes { length: 32 },
3425 }),
3426 }),
3427 message: "nz".to_owned(),
3428 },
3429 };
3430
3431 ir.circuits.push(circuit(
3433 "only_then_assert",
3434 true,
3435 vec![Argument {
3436 name: "flag".to_owned(),
3437 arg_type: TypeDescriptor::Boolean,
3438 }],
3439 Statement::Seq {
3440 items: vec![
3441 Statement::Const {
3442 binding: BindingTarget {
3443 name: "s".to_owned(),
3444 binding_type: TypeDescriptor::Bytes { length: 32 },
3445 },
3446 value: call_witness("secret_key"),
3447 },
3448 Statement::If {
3449 cond: Expression::Var {
3450 name: "flag".to_owned(),
3451 },
3452 then: Box::new(assert_secret()),
3453 r#else: None,
3454 },
3455 Statement::Expr {
3456 value: Expression::Call {
3457 function: "persistentHash".to_owned(),
3458 function_uniq: Some(10),
3459 arguments: vec![Expression::Var {
3460 name: "s".to_owned(),
3461 }],
3462 },
3463 },
3464 ],
3465 },
3466 ));
3467
3468 ir.circuits.push(circuit(
3470 "both_branches_assert",
3471 true,
3472 vec![Argument {
3473 name: "flag".to_owned(),
3474 arg_type: TypeDescriptor::Boolean,
3475 }],
3476 Statement::Seq {
3477 items: vec![
3478 Statement::Const {
3479 binding: BindingTarget {
3480 name: "s".to_owned(),
3481 binding_type: TypeDescriptor::Bytes { length: 32 },
3482 },
3483 value: call_witness("secret_key"),
3484 },
3485 Statement::If {
3486 cond: Expression::Var {
3487 name: "flag".to_owned(),
3488 },
3489 then: Box::new(assert_secret()),
3490 r#else: Some(Box::new(assert_secret())),
3491 },
3492 Statement::Expr {
3493 value: Expression::Call {
3494 function: "persistentHash".to_owned(),
3495 function_uniq: Some(10),
3496 arguments: vec![Expression::Var {
3497 name: "s".to_owned(),
3498 }],
3499 },
3500 },
3501 ],
3502 },
3503 ));
3504
3505 let report = audit_ir("branches", &ir, &StaticAuditOptions::default());
3506 assert!(
3507 report.findings.iter().any(|f| {
3508 f.circuit == "only_then_assert"
3509 && f.rule == AuditRule::UnconstrainedWitness
3510 && f.source == "witness:secret_key"
3511 }),
3512 "branch-local assert must not silence MP005, got {:?}",
3513 report.findings
3514 );
3515 assert!(
3516 report
3517 .findings
3518 .iter()
3519 .all(|f| f.circuit != "both_branches_assert"),
3520 "assert in both branches must satisfy MP005, got {:?}",
3521 report.findings
3522 );
3523 }
3524
3525 #[test]
3526 fn vm_ref_expression_with_i128_literal_still_detects_taint() {
3527 let mut ir = empty_ir();
3528 let big_expr = Expression::Binop {
3531 op: "+".to_owned(),
3532 bits: None,
3533 of_type: None,
3534 left: Box::new(Expression::Var {
3535 name: "s".to_owned(),
3536 }),
3537 right: Box::new(Expression::Literal {
3538 value: RuntimeValue::Int(i128::from(u64::MAX) + 1),
3539 }),
3540 };
3541 let big_expr_rv = moonproof_runtime_ir::to_runtime_value(&big_expr).unwrap();
3542 let mut ref_obj = BTreeMap::new();
3543 ref_obj.insert("vm".to_owned(), RuntimeValue::String("ref".to_owned()));
3544 ref_obj.insert("value".to_owned(), big_expr_rv);
3545 let mut vm_map = BTreeMap::new();
3546 vm_map.insert("op".to_owned(), RuntimeValue::String("push".to_owned()));
3547 vm_map.insert("value".to_owned(), RuntimeValue::Object(ref_obj));
3548
3549 ir.circuits.push(circuit(
3550 "vm_ref_big_int",
3551 true,
3552 Vec::new(),
3553 Statement::Seq {
3554 items: vec![
3555 Statement::Const {
3556 binding: BindingTarget {
3557 name: "s".to_owned(),
3558 binding_type: TypeDescriptor::Field,
3559 },
3560 value: call_witness("secret_key"),
3561 },
3562 Statement::Expr {
3563 value: Expression::AdtOp(AdtOpInvocation {
3564 adt: "Cell".to_owned(),
3565 operation: "write".to_owned(),
3566 op_class: "update".to_owned(),
3567 op_class_coin_index: None,
3568 op_class_recipient_index: None,
3569 field: Some("slot".to_owned()),
3570 field_path: Vec::new(),
3571 arguments: Vec::new(),
3572 result_type: TypeDescriptor::Tuple { types: Vec::new() },
3573 vm_ops: vec![VmInstr(vm_map)],
3574 }),
3575 },
3576 ],
3577 },
3578 ));
3579
3580 let report = audit_ir("vmref", &ir, &StaticAuditOptions::default());
3581 assert!(
3582 report.findings.iter().any(|f| {
3583 f.circuit == "vm_ref_big_int"
3584 && f.rule == AuditRule::DerivedWitnessDisclosure
3585 && f.source == "witness:secret_key"
3586 }),
3587 "expected MP002 via vm_ops ref containing i128 > u64::MAX, got {:?}",
3588 report.findings
3589 );
3590 }
3591}