1use ethnum::I256;
8use indexmap::IndexMap;
9use serde::de::{self, Visitor};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11
12use crate::RuntimeValue;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
30pub struct IntLit(pub I256);
31
32impl IntLit {
33 pub const ZERO: Self = Self(I256::ZERO);
34 pub const ONE: Self = Self(I256::ONE);
35
36 #[must_use]
37 pub fn from_i128(v: i128) -> Self {
38 Self(I256::from(v))
39 }
40
41 #[must_use]
42 pub fn from_u128(v: u128) -> Self {
43 Self(I256::from(v))
44 }
45
46 #[must_use]
48 pub fn as_u128(&self) -> Option<u128> {
49 if self.0 < I256::ZERO {
50 return None;
51 }
52 let (hi, lo) = self.0.into_words();
53 if hi != 0 {
54 return None;
55 }
56 Some(u128::from_ne_bytes(lo.to_ne_bytes()))
57 }
58
59 #[must_use]
61 pub fn as_i128(&self) -> Option<i128> {
62 let min = I256::from(i128::MIN);
63 let max = I256::from(i128::MAX);
64 if self.0 < min || self.0 > max {
65 return None;
66 }
67 let (_hi, lo) = self.0.into_words();
68 Some(lo)
69 }
70
71 #[must_use]
73 pub fn as_u32(&self) -> Option<u32> {
74 self.as_u128().and_then(|v| u32::try_from(v).ok())
75 }
76
77 #[must_use]
79 pub fn as_u64(&self) -> Option<u64> {
80 self.as_u128().and_then(|v| u64::try_from(v).ok())
81 }
82}
83
84impl std::fmt::Display for TypeDescriptor {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 let joined = |types: &[TypeDescriptor]| {
89 types
90 .iter()
91 .map(ToString::to_string)
92 .collect::<Vec<_>>()
93 .join(", ")
94 };
95 match self {
96 Self::Boolean => f.write_str("Boolean"),
97 Self::Field => f.write_str("Field"),
98 Self::JubjubScalar => f.write_str("JubjubScalar"),
99 Self::Secp256k1Base => f.write_str("Secp256k1Base"),
100 Self::Secp256k1Scalar => f.write_str("Secp256k1Scalar"),
101 Self::Secp256r1Base => f.write_str("Secp256r1Base"),
102 Self::Secp256r1Scalar => f.write_str("Secp256r1Scalar"),
103 Self::Curve25519Base => f.write_str("Curve25519Base"),
104 Self::Curve25519Scalar => f.write_str("Curve25519Scalar"),
105 Self::JubjubPoint => f.write_str("JubjubPoint"),
106 Self::Secp256k1Point => f.write_str("Secp256k1Point"),
107 Self::Secp256r1Point => f.write_str("Secp256r1Point"),
108 Self::Curve25519Point => f.write_str("Curve25519Point"),
109 Self::Uint { maxval, .. } => write!(f, "Uint<0..{maxval}>"),
110 Self::Bytes { length } => write!(f, "Bytes<{length}>"),
111 Self::Opaque { ts_type } => write!(f, "Opaque<{ts_type}>"),
112 Self::Tuple { types } => write!(f, "Tuple<{}>", joined(types)),
113 Self::Vector { length, elt_type } => write!(f, "Vector<{length}, {elt_type}>"),
114 Self::Set { of } => write!(f, "Set<{of}>"),
115 Self::List { of } => write!(f, "List<{of}>"),
116 Self::Map { key, value } => write!(f, "Map<{key}, {value}>"),
117 Self::MerkleTree { depth, of } => write!(f, "MerkleTree<{depth}, {of}>"),
118 Self::HistoricMerkleTree { depth, of } => {
119 write!(f, "HistoricMerkleTree<{depth}, {of}>")
120 }
121 Self::Counter => f.write_str("Counter"),
122 Self::Cell { of } => write!(f, "Cell<{of}>"),
123 Self::Struct { name, .. } => write!(f, "Struct<{name}>"),
124 Self::Enum { name, .. } => write!(f, "Enum<{name}>"),
125 Self::Alias { name, .. } => write!(f, "Alias<{name}>"),
126 Self::Contract { name, .. } => write!(f, "Contract<{name}>"),
127 Self::Unknown => f.write_str("Unknown"),
128 }
129 }
130}
131
132impl std::fmt::Display for IntLit {
133 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134 write!(f, "{}", self.0)
135 }
136}
137
138impl Serialize for IntLit {
139 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
140 match self.as_i128().and_then(|v| i64::try_from(v).ok()) {
141 Some(v) => s.serialize_i64(v),
143 None => s.serialize_str(&self.0.to_string()),
144 }
145 }
146}
147
148impl<'de> Deserialize<'de> for IntLit {
149 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
150 struct V;
151 impl Visitor<'_> for V {
152 type Value = IntLit;
153 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 f.write_str("an integer (JSON number or decimal string)")
155 }
156 fn visit_u64<E: de::Error>(self, v: u64) -> Result<IntLit, E> {
157 Ok(IntLit(I256::from(v)))
158 }
159 fn visit_i64<E: de::Error>(self, v: i64) -> Result<IntLit, E> {
160 Ok(IntLit(I256::from(v)))
161 }
162 fn visit_u128<E: de::Error>(self, v: u128) -> Result<IntLit, E> {
163 Ok(IntLit(I256::from(v)))
164 }
165 fn visit_i128<E: de::Error>(self, v: i128) -> Result<IntLit, E> {
166 Ok(IntLit(I256::from(v)))
167 }
168 fn visit_str<E: de::Error>(self, v: &str) -> Result<IntLit, E> {
169 v.parse::<I256>()
170 .map(IntLit)
171 .map_err(|e| E::custom(format!("invalid integer literal '{v}': {e}")))
172 }
173 fn visit_string<E: de::Error>(self, v: String) -> Result<IntLit, E> {
174 self.visit_str(&v)
175 }
176 }
177 d.deserialize_any(V)
178 }
179}
180
181#[derive(Debug, Clone, Serialize, Deserialize)]
186pub struct MoonIr {
187 #[serde(rename = "schema-version")]
188 pub schema_version: u32,
189 #[serde(rename = "compiler-version")]
190 pub compiler_version: String,
191 #[serde(rename = "language-version")]
192 pub language_version: String,
193 #[serde(rename = "runtime-version")]
194 pub runtime_version: String,
195
196 #[serde(default)]
201 pub contracts: Vec<TypeDescriptor>,
202 #[serde(default)]
203 pub ledger: Vec<LedgerField>,
204 #[serde(default)]
205 pub witnesses: Vec<Witness>,
206 #[serde(default)]
207 pub natives: Vec<Native>,
208 #[serde(default)]
209 pub circuits: Vec<CircuitBody>,
210 #[serde(default)]
211 pub descriptors: IndexMap<String, TypeDescriptor>,
212 pub constructor: Constructor,
213 #[serde(rename = "external-contracts", default)]
214 pub external_contracts: Vec<RuntimeValue>,
215 #[serde(rename = "pure-circuits", default)]
216 pub pure_circuits: Vec<RuntimeValue>,
217
218 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub frontend: Option<FrontendMeta>,
221 #[serde(
223 rename = "debug-info",
224 default,
225 skip_serializing_if = "Option::is_none"
226 )]
227 pub debug_info: Option<DebugInfo>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
230 pub capabilities: Option<CapabilitiesMeta>,
231 #[serde(default, skip_serializing_if = "Vec::is_empty")]
233 pub workflows: Vec<WorkflowMeta>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub privacy: Option<PrivacyMeta>,
237 #[serde(
240 rename = "type-roles",
241 default,
242 skip_serializing_if = "IndexMap::is_empty"
243 )]
244 pub type_roles: IndexMap<String, SemanticTypeRole>,
245}
246
247impl MoonIr {
248 #[must_use]
251 pub fn new_v3(
252 compiler_version: impl Into<String>,
253 language_version: impl Into<String>,
254 runtime_version: impl Into<String>,
255 ) -> Self {
256 Self {
257 schema_version: crate::loader::SUPPORTED_SCHEMA_VERSION,
258 compiler_version: compiler_version.into(),
259 language_version: language_version.into(),
260 runtime_version: runtime_version.into(),
261 contracts: Vec::new(),
262 ledger: Vec::new(),
263 witnesses: Vec::new(),
264 natives: Vec::new(),
265 circuits: Vec::new(),
266 descriptors: IndexMap::new(),
267 constructor: Constructor::default(),
268 external_contracts: Vec::new(),
269 pure_circuits: Vec::new(),
270 frontend: None,
271 debug_info: None,
272 capabilities: None,
273 workflows: Vec::new(),
274 privacy: None,
275 type_roles: IndexMap::new(),
276 }
277 }
278
279 #[must_use]
280 pub fn with_frontend(mut self, frontend: FrontendMeta) -> Self {
281 self.frontend = Some(frontend);
282 self
283 }
284
285 #[must_use]
286 pub fn with_debug_info(mut self, debug_info: DebugInfo) -> Self {
287 self.debug_info = Some(debug_info);
288 self
289 }
290
291 #[must_use]
292 pub fn with_capabilities(mut self, capabilities: CapabilitiesMeta) -> Self {
293 self.capabilities = Some(capabilities);
294 self
295 }
296
297 #[must_use]
298 pub fn with_workflows(mut self, workflows: Vec<WorkflowMeta>) -> Self {
299 self.workflows = workflows;
300 self
301 }
302
303 #[must_use]
304 pub fn with_privacy(mut self, privacy: PrivacyMeta) -> Self {
305 self.privacy = Some(privacy);
306 self
307 }
308
309 #[must_use]
310 pub fn with_type_roles(mut self, type_roles: IndexMap<String, SemanticTypeRole>) -> Self {
311 self.type_roles = type_roles;
312 self
313 }
314
315 #[must_use]
316 pub fn with_type_role(
317 mut self,
318 descriptor_key: impl Into<String>,
319 role: SemanticTypeRole,
320 ) -> Self {
321 self.type_roles.insert(descriptor_key.into(), role);
322 self
323 }
324
325 #[must_use]
326 pub fn with_constructor(mut self, constructor: Constructor) -> Self {
327 self.constructor = constructor;
328 self
329 }
330
331 pub fn add_ledger_field(&mut self, field: LedgerField) -> &mut Self {
332 self.ledger.push(field);
333 self
334 }
335
336 pub fn add_witness(&mut self, witness: Witness) -> &mut Self {
337 self.witnesses.push(witness);
338 self
339 }
340
341 pub fn add_native(&mut self, native: Native) -> &mut Self {
342 self.natives.push(native);
343 self
344 }
345
346 pub fn add_circuit(&mut self, circuit: CircuitBody) -> &mut Self {
347 self.circuits.push(circuit);
348 self
349 }
350
351 pub fn add_descriptor(
352 &mut self,
353 key: impl Into<String>,
354 descriptor: TypeDescriptor,
355 ) -> &mut Self {
356 self.descriptors.insert(key.into(), descriptor);
357 self
358 }
359
360 pub fn add_workflow(&mut self, workflow: WorkflowMeta) -> &mut Self {
361 self.workflows.push(workflow);
362 self
363 }
364}
365
366#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
372#[serde(rename_all = "kebab-case")]
373pub enum FrontendLanguage {
374 Compact,
375 Pact5,
376 Custom(String),
377}
378
379#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
381pub struct FrontendMeta {
382 pub language: FrontendLanguage,
383 #[serde(rename = "frontend-version")]
384 pub frontend_version: String,
385 #[serde(
386 rename = "source-module",
387 default,
388 skip_serializing_if = "Option::is_none"
389 )]
390 pub source_module: Option<String>,
391 #[serde(
392 rename = "source-hash",
393 default,
394 skip_serializing_if = "Option::is_none"
395 )]
396 pub source_hash: Option<String>,
397 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
398 pub metadata: IndexMap<String, String>,
399}
400
401#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
403pub struct SourceSpan {
404 #[serde(default, skip_serializing_if = "Option::is_none")]
405 pub file: Option<String>,
406 #[serde(rename = "start-line")]
407 pub start_line: u32,
408 #[serde(rename = "start-col")]
409 pub start_col: u32,
410 #[serde(rename = "end-line")]
411 pub end_line: u32,
412 #[serde(rename = "end-col")]
413 pub end_col: u32,
414}
415
416#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
418pub struct DebugInfo {
419 #[serde(default, skip_serializing_if = "Vec::is_empty")]
420 pub sources: Vec<String>,
421 #[serde(
422 rename = "circuit-spans",
423 default,
424 skip_serializing_if = "IndexMap::is_empty"
425 )]
426 pub circuit_spans: IndexMap<String, SourceSpan>,
427 #[serde(
428 rename = "field-spans",
429 default,
430 skip_serializing_if = "IndexMap::is_empty"
431 )]
432 pub field_spans: IndexMap<String, SourceSpan>,
433}
434
435#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
437#[serde(tag = "kind", rename_all = "kebab-case")]
438pub enum GovernanceSpec {
439 Keyset { name: String },
440 Capability { name: String },
441 Custom { description: String },
442}
443
444#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
446#[serde(rename_all = "kebab-case")]
447pub enum CapabilityKind {
448 Basic,
449 Managed,
450 Event,
451}
452
453#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
455pub struct CapabilityDef {
456 pub name: String,
457 pub kind: CapabilityKind,
458 #[serde(default, skip_serializing_if = "Vec::is_empty")]
459 pub arguments: Vec<Argument>,
460 #[serde(
461 rename = "managed-param",
462 default,
463 skip_serializing_if = "Option::is_none"
464 )]
465 pub managed_param: Option<String>,
466 #[serde(
467 rename = "manager-circuit",
468 default,
469 skip_serializing_if = "Option::is_none"
470 )]
471 pub manager_circuit: Option<String>,
472 #[serde(default, skip_serializing_if = "Vec::is_empty")]
473 pub composes: Vec<String>,
474}
475
476#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
478pub struct CircuitCapUsage {
479 #[serde(default, skip_serializing_if = "Vec::is_empty")]
480 pub acquires: Vec<String>,
481 #[serde(default, skip_serializing_if = "Vec::is_empty")]
482 pub requires: Vec<String>,
483 #[serde(default, skip_serializing_if = "Vec::is_empty")]
484 pub emits: Vec<String>,
485}
486
487#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
489pub struct CapabilitiesMeta {
490 #[serde(default, skip_serializing_if = "Option::is_none")]
491 pub governance: Option<GovernanceSpec>,
492 #[serde(default, skip_serializing_if = "Vec::is_empty")]
493 pub capabilities: Vec<CapabilityDef>,
494 #[serde(
495 rename = "circuit-usage",
496 default,
497 skip_serializing_if = "IndexMap::is_empty"
498 )]
499 pub circuit_usage: IndexMap<String, CircuitCapUsage>,
500}
501
502#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
504pub struct WorkflowStepMeta {
505 pub index: u32,
506 pub circuit: String,
507 #[serde(
508 rename = "rollback-circuit",
509 default,
510 skip_serializing_if = "Option::is_none"
511 )]
512 pub rollback_circuit: Option<String>,
513 #[serde(default, skip_serializing_if = "Option::is_none")]
514 pub entity: Option<String>,
515 #[serde(default, skip_serializing_if = "Vec::is_empty")]
516 pub yields: Vec<String>,
517}
518
519#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
521pub struct WorkflowMeta {
522 pub name: String,
523 #[serde(default, skip_serializing_if = "Vec::is_empty")]
524 pub steps: Vec<WorkflowStepMeta>,
525}
526
527#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
529#[serde(rename_all = "kebab-case")]
530pub enum PrivacyClass {
531 Public,
532 Private,
533 Shielded,
534 Disclosed,
535}
536
537#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
539#[serde(rename_all = "kebab-case")]
540pub enum FieldRole {
541 State,
542 Commitment,
543 Nullifier,
544 Ciphertext,
545 Authority,
546 Balance,
547}
548
549#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
551pub struct CircuitBoundsMeta {
552 #[serde(
553 rename = "max-constraints",
554 default,
555 skip_serializing_if = "Option::is_none"
556 )]
557 pub max_constraints: Option<u64>,
558 #[serde(
559 rename = "max-public-inputs",
560 default,
561 skip_serializing_if = "Option::is_none"
562 )]
563 pub max_public_inputs: Option<u32>,
564 #[serde(
565 rename = "max-witness-elements",
566 default,
567 skip_serializing_if = "Option::is_none"
568 )]
569 pub max_witness_elements: Option<u32>,
570}
571
572#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
574pub struct PrivacyMeta {
575 #[serde(
576 rename = "field-classes",
577 default,
578 skip_serializing_if = "IndexMap::is_empty"
579 )]
580 pub field_classes: IndexMap<String, PrivacyClass>,
581 #[serde(
582 rename = "field-roles",
583 default,
584 skip_serializing_if = "IndexMap::is_empty"
585 )]
586 pub field_roles: IndexMap<String, FieldRole>,
587 #[serde(
588 rename = "circuit-bounds",
589 default,
590 skip_serializing_if = "IndexMap::is_empty"
591 )]
592 pub circuit_bounds: IndexMap<String, CircuitBoundsMeta>,
593}
594
595#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
598#[serde(tag = "role", rename_all = "kebab-case")]
599pub enum SemanticTypeRole {
600 FixedDecimal {
601 scale: u8,
602 signed: bool,
603 },
604 SignedInt {
605 bits: u16,
606 },
607 BoundedList {
608 #[serde(rename = "max-len")]
609 max_len: u32,
610 },
611 Guard,
612 Timestamp,
613}
614
615#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
626pub enum FieldType {
627 Field,
628 JubjubScalar,
629 Secp256k1Base,
630 Secp256k1Scalar,
631 Secp256r1Base,
632 Secp256r1Scalar,
633 Curve25519Base,
634 Curve25519Scalar,
635}
636
637impl FieldType {
638 #[must_use]
640 pub fn descriptor(self) -> TypeDescriptor {
641 match self {
642 FieldType::Field => TypeDescriptor::Field,
643 FieldType::JubjubScalar => TypeDescriptor::JubjubScalar,
644 FieldType::Secp256k1Base => TypeDescriptor::Secp256k1Base,
645 FieldType::Secp256k1Scalar => TypeDescriptor::Secp256k1Scalar,
646 FieldType::Secp256r1Base => TypeDescriptor::Secp256r1Base,
647 FieldType::Secp256r1Scalar => TypeDescriptor::Secp256r1Scalar,
648 FieldType::Curve25519Base => TypeDescriptor::Curve25519Base,
649 FieldType::Curve25519Scalar => TypeDescriptor::Curve25519Scalar,
650 }
651 }
652
653 #[must_use]
657 pub fn of_descriptor(descriptor: &TypeDescriptor) -> Option<FieldType> {
658 Some(match descriptor {
659 TypeDescriptor::Field => FieldType::Field,
660 TypeDescriptor::JubjubScalar => FieldType::JubjubScalar,
661 TypeDescriptor::Secp256k1Base => FieldType::Secp256k1Base,
662 TypeDescriptor::Secp256k1Scalar => FieldType::Secp256k1Scalar,
663 TypeDescriptor::Secp256r1Base => FieldType::Secp256r1Base,
664 TypeDescriptor::Secp256r1Scalar => FieldType::Secp256r1Scalar,
665 TypeDescriptor::Curve25519Base => FieldType::Curve25519Base,
666 TypeDescriptor::Curve25519Scalar => FieldType::Curve25519Scalar,
667 _ => return None,
668 })
669 }
670}
671
672#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
673#[serde(tag = "type-name")]
674pub enum TypeDescriptor {
675 Boolean,
676 Field,
677 JubjubScalar,
682 Secp256k1Base,
687 Secp256k1Scalar,
690 Secp256r1Base,
693 Secp256r1Scalar,
696 Curve25519Base,
699 Curve25519Scalar,
702 JubjubPoint,
704 Secp256k1Point,
707 Secp256r1Point,
710 Curve25519Point,
713 Unknown,
718 Uint {
719 maxval: IntLit,
720 #[serde(default, rename = "alignment-bytes")]
721 alignment_bytes: Option<u32>,
722 },
723 Bytes {
724 length: u32,
725 },
726 Opaque {
727 #[serde(rename = "tsType")]
728 ts_type: String,
729 },
730 Vector {
731 length: u32,
732 #[serde(rename = "type")]
733 elt_type: Box<TypeDescriptor>,
734 },
735 Tuple {
736 types: Vec<TypeDescriptor>,
737 },
738 Struct {
739 name: String,
740 elements: Vec<StructField>,
741 },
742 Enum {
743 name: String,
744 elements: Vec<String>,
745 },
746 Alias {
747 name: String,
748 #[serde(rename = "type")]
749 of: Box<TypeDescriptor>,
750 },
751 Contract {
752 name: String,
753 circuits: Vec<ContractCircuitSig>,
754 },
755 Cell {
756 #[serde(rename = "type")]
757 of: Box<TypeDescriptor>,
758 },
759 Counter,
760 Map {
761 key: Box<TypeDescriptor>,
762 value: Box<TypeDescriptor>,
763 },
764 Set {
765 #[serde(rename = "type")]
766 of: Box<TypeDescriptor>,
767 },
768 List {
769 #[serde(rename = "type")]
770 of: Box<TypeDescriptor>,
771 },
772 MerkleTree {
773 depth: IntLit,
774 #[serde(rename = "type")]
775 of: Box<TypeDescriptor>,
776 },
777 HistoricMerkleTree {
778 depth: IntLit,
779 #[serde(rename = "type")]
780 of: Box<TypeDescriptor>,
781 },
782}
783
784impl TypeDescriptor {
785 #[must_use]
790 pub fn contract_address() -> Self {
791 TypeDescriptor::Struct {
792 name: "ContractAddress".to_owned(),
793 elements: vec![StructField {
794 name: "bytes".to_owned(),
795 field_type: TypeDescriptor::Bytes { length: 32 },
796 }],
797 }
798 }
799}
800
801#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
802pub struct StructField {
803 pub name: String,
804 #[serde(rename = "type")]
805 pub field_type: TypeDescriptor,
806}
807
808#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
809pub struct ContractCircuitSig {
810 pub name: String,
811 #[serde(rename = "argument-types")]
812 pub argument_types: Vec<TypeDescriptor>,
813 #[serde(rename = "result-type")]
814 pub result_type: TypeDescriptor,
815}
816
817#[derive(Debug, Clone, Serialize, Deserialize)]
822pub struct LedgerField {
823 pub name: String,
824 #[serde(
837 deserialize_with = "deserialize_field_index",
838 serialize_with = "serialize_field_index"
839 )]
840 pub index: Vec<u32>,
841 pub exported: bool,
842 #[serde(flatten)]
843 pub storage: Storage,
844}
845
846impl LedgerField {
847 #[must_use]
850 pub fn leaf_index(&self) -> u32 {
851 self.index.last().copied().unwrap_or(0)
852 }
853}
854
855fn serialize_field_index<S>(v: &[u32], s: S) -> Result<S::Ok, S::Error>
856where
857 S: serde::Serializer,
858{
859 use serde::ser::SerializeSeq;
860 if v.len() == 1 {
861 s.serialize_u32(v[0])
862 } else {
863 let mut seq = s.serialize_seq(Some(v.len()))?;
864 for n in v {
865 seq.serialize_element(n)?;
866 }
867 seq.end()
868 }
869}
870
871fn deserialize_field_index<'de, D>(d: D) -> Result<Vec<u32>, D::Error>
872where
873 D: serde::Deserializer<'de>,
874{
875 use serde::de::{self, Error, SeqAccess, Visitor};
876 use std::fmt;
877
878 struct V;
879 impl<'de> Visitor<'de> for V {
880 type Value = Vec<u32>;
881 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882 f.write_str("a non-negative integer or an array of non-negative integers")
883 }
884 fn visit_u64<E: Error>(self, v: u64) -> Result<Vec<u32>, E> {
885 u32::try_from(v)
886 .map(|n| vec![n])
887 .map_err(|_| Error::custom(format!("ledger field index {v} exceeds u32::MAX")))
888 }
889 fn visit_i64<E: Error>(self, v: i64) -> Result<Vec<u32>, E> {
890 u32::try_from(v)
891 .map(|n| vec![n])
892 .map_err(|_| Error::custom(format!("ledger field index {v} not in u32 range")))
893 }
894 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u32>, A::Error> {
895 let mut out: Vec<u32> = Vec::new();
896 while let Some(elem) = seq.next_element::<i64>()? {
897 let n = u32::try_from(elem).map_err(|_| {
898 de::Error::custom(format!(
899 "ledger field index path entry {elem} not in u32 range"
900 ))
901 })?;
902 out.push(n);
903 }
904 Ok(out)
905 }
906 }
907 d.deserialize_any(V)
908}
909
910#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
929#[serde(tag = "storage")]
930pub enum Storage {
931 Counter,
932 Cell {
933 #[serde(rename = "type")]
934 of: TypeDescriptor,
935 },
936 Map {
937 key: TypeDescriptor,
938 value: TypeDescriptor,
939 },
940 Set {
941 #[serde(rename = "type")]
942 of: TypeDescriptor,
943 },
944 List {
945 #[serde(rename = "type")]
946 of: TypeDescriptor,
947 },
948 MerkleTree {
949 #[serde(rename = "type")]
950 of: TypeDescriptor,
951 },
952 HistoricMerkleTree {
953 #[serde(rename = "type")]
954 of: TypeDescriptor,
955 },
956}
957
958impl Storage {
959 #[must_use]
962 pub fn kind(&self) -> &'static str {
963 match self {
964 Self::Counter => "Counter",
965 Self::Cell { .. } => "Cell",
966 Self::Map { .. } => "Map",
967 Self::Set { .. } => "Set",
968 Self::List { .. } => "List",
969 Self::MerkleTree { .. } => "MerkleTree",
970 Self::HistoricMerkleTree { .. } => "HistoricMerkleTree",
971 }
972 }
973}
974
975#[derive(Debug, Clone, Serialize, Deserialize)]
976pub struct Witness {
977 pub name: String,
978 #[serde(default)]
979 pub arguments: Vec<Argument>,
980 #[serde(rename = "result-type")]
981 pub result_type: TypeDescriptor,
982}
983
984#[derive(Debug, Clone, Serialize, Deserialize)]
985pub struct Native {
986 pub name: String,
987 #[serde(rename = "internal-uniq", default)]
991 pub internal_uniq: Option<u64>,
992 #[serde(rename = "host-symbol")]
993 pub host_symbol: String,
994 #[serde(default, skip_serializing_if = "Option::is_none")]
998 pub intrinsic: Option<String>,
999 pub class: String,
1000 #[serde(default)]
1001 pub arguments: Vec<Argument>,
1002 #[serde(rename = "result-type")]
1003 pub result_type: TypeDescriptor,
1004}
1005
1006impl Native {
1007 #[must_use]
1010 pub fn new_intrinsic(
1011 name: impl Into<String>,
1012 intrinsic: impl Into<String>,
1013 class: impl Into<String>,
1014 arguments: Vec<Argument>,
1015 result_type: TypeDescriptor,
1016 ) -> Self {
1017 let intr = intrinsic.into();
1018 Self {
1019 name: name.into(),
1020 internal_uniq: None,
1021 host_symbol: intr.clone(),
1022 intrinsic: Some(intr),
1023 class: class.into(),
1024 arguments,
1025 result_type,
1026 }
1027 }
1028
1029 #[must_use]
1035 pub fn resolve_intrinsic(&self) -> &str {
1036 if let Some(ref intrinsic) = self.intrinsic {
1037 intrinsic.as_str()
1038 } else {
1039 self.host_symbol
1040 .strip_prefix("__compactRuntime.")
1041 .unwrap_or(&self.host_symbol)
1042 }
1043 }
1044}
1045
1046#[must_use]
1051pub fn canonical_intrinsic_name(raw: &str) -> &str {
1052 let trimmed = raw.strip_prefix("__compactRuntime.").unwrap_or(raw);
1053 match trimmed {
1054 "mp:hash/persistent" => "persistentHash",
1056 "mp:hash/transient" | "mp:hash/poseidon" => "transientHash",
1057 "mp:commit/persistent" | "mp:hash/persistent-commit" => "persistentCommit",
1058 "mp:commit/transient" | "mp:hash/transient-commit" => "transientCommit",
1059 "mp:hash/degrade-to-transient" => "degradeToTransient",
1060 "mp:hash/upgrade-from-transient" => "upgradeFromTransient",
1061 "mp:hash/keccak256" => "keccak256",
1062 "mp:hash/sha512" => "sha512",
1063 "mp:hash/to-curve" | "mp:curve/hash-to-curve" => "hashToCurve",
1064
1065 "mp:coin/commitment" | "mp:zswap/coin-commitment" => "coinCommitment",
1067 "mp:coin/token-type" | "mp:zswap/token-type" => "tokenType",
1068 "mp:context/own-public-key"
1069 | "mp:zswap/own-public-key"
1070 | "mp:auth/own-public-key"
1071 | "mp:ledger/own-public-key" => "ownPublicKey",
1072 "mp:zswap/create-output" => "createZswapOutput",
1073 "mp:zswap/create-input" => "createZswapInput",
1074
1075 "mp:curve/jubjub-point-x" | "mp:ec/jubjub-point-x" => "jubjubPointX",
1077 "mp:curve/jubjub-point-y" | "mp:ec/jubjub-point-y" => "jubjubPointY",
1078 "mp:curve/jubjub-construct" | "mp:ec/jubjub-construct" => "constructJubjubPoint",
1079 "mp:curve/jubjub-add" | "mp:ec/add" | "mp:ec/jubjub-add" => "ecAdd",
1080 "mp:curve/jubjub-mul" | "mp:ec/mul" | "mp:ec/jubjub-mul" => "ecMul",
1081 "mp:curve/jubjub-mul-generator" | "mp:ec/mul-generator" | "mp:ec/jubjub-mul-generator" => {
1082 "ecMulGenerator"
1083 }
1084 "mp:curve/jubjub-neg" | "mp:ec/neg" | "mp:ec/jubjub-neg" => "ecNeg",
1085 "mp:curve/jubjub-scalar-from-native"
1086 | "mp:ec/jubjub-scalar-from-native"
1087 | "reduceModJubjubOrder" => "jubjubScalarFromNative",
1088 "mp:curve/secp256k1-add" | "mp:ec/secp256k1-add" => "secp256k1Add",
1089 "mp:curve/secp256r1-add" | "mp:ec/secp256r1-add" => "secp256r1Add",
1090 "mp:curve/curve25519-add" | "mp:ec/curve25519-add" => "curve25519Add",
1091 "mp:curve/secp256k1-mul" | "mp:ec/secp256k1-mul" => "secp256k1Mul",
1092 "mp:curve/secp256r1-mul" | "mp:ec/secp256r1-mul" => "secp256r1Mul",
1093 "mp:curve/curve25519-mul" | "mp:ec/curve25519-mul" => "curve25519Mul",
1094 "mp:curve/secp256k1-mul-generator" | "mp:ec/secp256k1-mul-generator" => {
1095 "secp256k1MulGenerator"
1096 }
1097 "mp:curve/secp256r1-mul-generator" | "mp:ec/secp256r1-mul-generator" => {
1098 "secp256r1MulGenerator"
1099 }
1100 "mp:curve/curve25519-mul-generator" | "mp:ec/curve25519-mul-generator" => {
1101 "curve25519MulGenerator"
1102 }
1103
1104 "mp:merkle/path-root" => "merkleTreePathRoot",
1106 "mp:merkle/path-root-no-leaf-hash" => "merkleTreePathRootNoLeafHash",
1107
1108 "mp:crypto/ed25519-verify" | "mp:sig/ed25519-verify" => "ed25519Verify",
1110 "mp:crypto/secp256r1-ecdsa-verify"
1111 | "mp:sig/secp256r1-ecdsa-verify"
1112 | "mp:crypto/ecdsa-p256-verify" => "secp256r1EcdsaVerify",
1113 "mp:crypto/secp256k1-ecdsa-verify"
1114 | "mp:sig/secp256k1-ecdsa-verify"
1115 | "mp:crypto/ecdsa-secp256k1-verify" => "secp256k1EcdsaVerify",
1116
1117 other => other,
1118 }
1119}
1120
1121#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1122pub struct Argument {
1123 pub name: String,
1124 #[serde(rename = "type")]
1125 pub arg_type: TypeDescriptor,
1126}
1127
1128#[derive(Debug, Clone, Serialize, Deserialize)]
1133pub struct Constructor {
1134 #[serde(default)]
1135 pub arguments: Vec<Argument>,
1136 #[serde(rename = "initial-state")]
1137 pub initial_state: StateValue,
1138 #[serde(rename = "init-ops", default)]
1139 pub init_ops: Vec<Expression>,
1140 #[serde(rename = "register-operations", default)]
1141 pub register_operations: Vec<String>,
1142 pub body: Statement,
1143}
1144
1145impl Default for Constructor {
1146 fn default() -> Self {
1147 Self {
1148 arguments: Vec::new(),
1149 initial_state: StateValue::Null,
1150 init_ops: Vec::new(),
1151 register_operations: Vec::new(),
1152 body: Statement::Noop,
1153 }
1154 }
1155}
1156
1157#[derive(Debug, Clone, Serialize, Deserialize)]
1162pub struct CircuitBody {
1163 pub name: String,
1164 #[serde(rename = "internal-name")]
1165 pub internal_name: String,
1166 #[serde(rename = "internal-uniq", default)]
1170 pub internal_uniq: Option<u64>,
1171 pub exported: bool,
1172 pub pure: bool,
1173 pub proof: bool,
1174 #[serde(default)]
1175 pub arguments: Vec<Argument>,
1176 #[serde(rename = "result-type")]
1177 pub result_type: TypeDescriptor,
1178 pub body: Statement,
1179}
1180
1181#[derive(Debug, Clone, Serialize, Deserialize)]
1186#[serde(tag = "stmt", rename_all = "kebab-case")]
1187pub enum Statement {
1188 Seq {
1189 items: Vec<Statement>,
1190 },
1191 If {
1192 cond: Expression,
1193 then: Box<Statement>,
1194 #[serde(default)]
1195 r#else: Option<Box<Statement>>,
1196 },
1197 Const {
1198 binding: BindingTarget,
1199 value: Expression,
1200 },
1201 ConstDestructure {
1202 bindings: Vec<BindingTarget>,
1203 },
1204 Expr {
1205 value: Expression,
1206 },
1207 Unimplemented,
1210 Noop,
1212}
1213
1214#[derive(Debug, Clone, Serialize, Deserialize)]
1215pub struct BindingTarget {
1216 pub name: String,
1217 #[serde(rename = "type")]
1218 pub binding_type: TypeDescriptor,
1219}
1220
1221#[derive(Debug, Clone, Serialize, Deserialize)]
1226#[serde(tag = "expr", rename_all = "kebab-case")]
1227pub enum Expression {
1228 Literal {
1229 value: crate::value::RuntimeValue,
1230 },
1231 Var {
1232 name: String,
1233 },
1234 Default {
1235 #[serde(rename = "type")]
1236 of_type: TypeDescriptor,
1237 },
1238 If {
1239 cond: Box<Expression>,
1240 then: Box<Expression>,
1241 r#else: Box<Expression>,
1242 },
1243 EltRef {
1244 value: Box<Expression>,
1245 field: String,
1246 index: IntLit,
1247 },
1248 EnumRef {
1249 #[serde(rename = "type")]
1250 of_type: TypeDescriptor,
1251 variant: String,
1252 },
1253 Tuple {
1254 items: Vec<TupleItem>,
1255 },
1256 Vector {
1257 items: Vec<TupleItem>,
1258 },
1259 TupleRef {
1260 value: Box<Expression>,
1261 index: IntLit,
1262 },
1263 TupleSlice {
1264 value: Box<Expression>,
1265 start: IntLit,
1266 length: IntLit,
1267 #[serde(rename = "result-type")]
1268 result_type: TypeDescriptor,
1269 },
1270 VectorRef {
1271 value: Box<Expression>,
1272 index: Box<Expression>,
1273 #[serde(rename = "result-type")]
1274 result_type: TypeDescriptor,
1275 },
1276 VectorSlice {
1277 value: Box<Expression>,
1278 start: Box<Expression>,
1279 length: IntLit,
1280 #[serde(rename = "result-type")]
1281 result_type: TypeDescriptor,
1282 },
1283 BytesRef {
1284 value: Box<Expression>,
1285 index: Box<Expression>,
1286 #[serde(rename = "result-type")]
1287 result_type: TypeDescriptor,
1288 },
1289 BytesSlice {
1290 value: Box<Expression>,
1291 start: Box<Expression>,
1292 length: IntLit,
1293 #[serde(rename = "result-type")]
1294 result_type: TypeDescriptor,
1295 },
1296 Binop {
1297 op: String,
1298 #[serde(default)]
1300 bits: Option<u32>,
1301 #[serde(rename = "type", default)]
1306 of_type: Option<TypeDescriptor>,
1307 left: Box<Expression>,
1308 right: Box<Expression>,
1309 },
1310 Eq {
1311 #[serde(rename = "type", default)]
1312 of_type: Option<TypeDescriptor>,
1313 left: Box<Expression>,
1314 right: Box<Expression>,
1315 },
1316 Neq {
1317 #[serde(rename = "type", default)]
1318 of_type: Option<TypeDescriptor>,
1319 left: Box<Expression>,
1320 right: Box<Expression>,
1321 },
1322 And {
1323 left: Box<Expression>,
1324 right: Box<Expression>,
1325 },
1326 Or {
1327 left: Box<Expression>,
1328 right: Box<Expression>,
1329 },
1330 Not {
1331 value: Box<Expression>,
1332 },
1333 Assign {
1334 name: String,
1335 value: Box<Expression>,
1336 },
1337 Call {
1338 function: String,
1339 #[serde(rename = "function-uniq", default)]
1346 function_uniq: Option<u64>,
1347 arguments: Vec<Expression>,
1348 },
1349 New {
1350 #[serde(rename = "type")]
1351 of_type: TypeDescriptor,
1352 arguments: Vec<Expression>,
1353 },
1354 Seq {
1355 items: Vec<Expression>,
1356 },
1357 Cast {
1358 to: TypeDescriptor,
1359 value: Box<Expression>,
1360 },
1361 SafeCast {
1362 to: TypeDescriptor,
1363 from: TypeDescriptor,
1364 value: Box<Expression>,
1365 },
1366 DowncastUnsigned {
1367 #[serde(rename = "from-bits")]
1368 from_bits: Option<IntLit>,
1369 #[serde(rename = "to-bits")]
1370 to_bits: IntLit,
1371 value: Box<Expression>,
1372 },
1373 #[serde(rename = "field->bytes")]
1374 FieldToBytes {
1375 length: u32,
1376 #[serde(rename = "field-type", default)]
1379 field_type: Option<FieldType>,
1380 value: Box<Expression>,
1381 },
1382 #[serde(rename = "cast-to-field")]
1385 CastToField {
1386 #[serde(rename = "field-type")]
1387 field_type: FieldType,
1388 from: TypeDescriptor,
1389 value: Box<Expression>,
1390 },
1391 #[serde(rename = "cast-from-field")]
1394 CastFromField {
1395 maxval: IntLit,
1396 #[serde(rename = "field-type")]
1397 field_type: FieldType,
1398 value: Box<Expression>,
1399 },
1400 Emit {
1404 #[serde(rename = "event-version")]
1405 event_version: u32,
1406 #[serde(rename = "event-tag")]
1407 event_tag: u32,
1408 #[serde(rename = "payload-length")]
1409 payload_length: u32,
1410 payload: Box<Expression>,
1411 #[serde(rename = "vm-ops", default)]
1412 vm_ops: Vec<VmInstr>,
1413 },
1414 #[serde(rename = "cast-from-bytes")]
1415 CastFromBytes {
1416 to: TypeDescriptor,
1417 length: u32,
1418 value: Box<Expression>,
1419 },
1420 #[serde(rename = "vector->bytes")]
1421 VectorToBytes {
1422 length: u32,
1423 value: Box<Expression>,
1424 },
1425 #[serde(rename = "bytes->vector")]
1426 BytesToVector {
1427 length: u32,
1428 value: Box<Expression>,
1429 },
1430 CastFromEnum {
1431 from: TypeDescriptor,
1432 to: TypeDescriptor,
1433 value: Box<Expression>,
1434 },
1435 CastToEnum {
1436 from: TypeDescriptor,
1437 to: TypeDescriptor,
1438 value: Box<Expression>,
1439 },
1440 Assert {
1441 cond: Box<Expression>,
1442 message: String,
1443 },
1444 Map {
1445 length: IntLit,
1446 function: crate::value::RuntimeValue,
1447 arguments: Vec<crate::value::RuntimeValue>,
1448 },
1449 Fold {
1450 length: IntLit,
1451 function: crate::value::RuntimeValue,
1452 initial: crate::value::RuntimeValue,
1453 arguments: Vec<crate::value::RuntimeValue>,
1454 },
1455 AdtOp(AdtOpInvocation),
1456 ContractCall {
1457 circuit: String,
1458 address: Box<Expression>,
1459 #[serde(rename = "address-type")]
1460 address_type: TypeDescriptor,
1461 arguments: Vec<Expression>,
1462 },
1463 Unimplemented,
1465}
1466
1467#[derive(Debug, Clone, Serialize, Deserialize)]
1468pub struct TupleItem {
1469 pub kind: String, #[serde(default)]
1471 pub length: Option<IntLit>,
1472 pub value: Expression,
1473}
1474
1475#[derive(Debug, Clone, Serialize, Deserialize)]
1480pub struct AdtOpInvocation {
1481 pub adt: String,
1482 pub operation: String,
1483 #[serde(rename = "op-class")]
1484 pub op_class: String,
1485 #[serde(rename = "op-class-coin-index", default)]
1493 pub op_class_coin_index: Option<u32>,
1494 #[serde(rename = "op-class-recipient-index", default)]
1498 pub op_class_recipient_index: Option<u32>,
1499 #[serde(default)]
1500 pub field: Option<String>,
1501 #[serde(rename = "field-path", default)]
1502 pub field_path: Vec<PathElement>,
1503 #[serde(default)]
1504 pub arguments: Vec<Expression>,
1505 #[serde(rename = "result-type")]
1506 pub result_type: TypeDescriptor,
1507 #[serde(rename = "vm-ops")]
1508 pub vm_ops: Vec<VmInstr>,
1509}
1510
1511#[derive(Debug, Clone, Serialize, Deserialize)]
1512#[serde(tag = "kind", rename_all = "kebab-case")]
1513pub enum PathElement {
1514 Literal {
1515 index: u32,
1516 },
1517 Expr {
1518 #[serde(rename = "type")]
1519 of_type: TypeDescriptor,
1520 value: Box<Expression>,
1524 },
1525}
1526
1527#[derive(Debug, Clone, Serialize, Deserialize)]
1536pub struct VmInstr(pub std::collections::BTreeMap<String, crate::value::RuntimeValue>);
1537
1538impl VmInstr {
1539 #[must_use]
1540 pub fn op(&self) -> Option<&str> {
1541 self.0
1542 .get("op")
1543 .and_then(crate::value::RuntimeValue::as_str)
1544 }
1545}
1546
1547pub type VmOp = crate::value::RuntimeValue;
1553
1554#[derive(Debug, Clone, Serialize, Deserialize)]
1559#[serde(tag = "kind", rename_all = "kebab-case")]
1560pub enum StateValue {
1561 Null,
1562 Cell {
1563 #[serde(default)]
1564 descriptor: Option<String>,
1565 value: crate::value::RuntimeValue,
1566 },
1567 CellExpr {
1568 #[serde(default)]
1569 descriptor: Option<String>,
1570 value: Box<Expression>,
1572 },
1573 Array {
1574 items: Vec<StateValue>,
1575 },
1576 Map {
1577 entries: Vec<MapEntry>,
1578 },
1579 MerkleTree {
1580 depth: IntLit,
1581 #[serde(default)]
1582 entries: Vec<MapEntry>,
1583 },
1584}
1585
1586#[derive(Debug, Clone, Serialize, Deserialize)]
1587pub struct MapEntry {
1588 pub key: StateValue,
1589 pub value: StateValue,
1590}