use ethnum::I256;
use indexmap::IndexMap;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::RuntimeValue;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct IntLit(pub I256);
impl IntLit {
pub const ZERO: Self = Self(I256::ZERO);
pub const ONE: Self = Self(I256::ONE);
#[must_use]
pub fn from_i128(v: i128) -> Self {
Self(I256::from(v))
}
#[must_use]
pub fn from_u128(v: u128) -> Self {
Self(I256::from(v))
}
#[must_use]
pub fn as_u256(&self) -> Option<ethnum::U256> {
if self.0 < I256::ZERO {
return None;
}
Some(ethnum::U256::from_le_bytes(self.0.to_le_bytes()))
}
#[must_use]
pub fn as_u128(&self) -> Option<u128> {
if self.0 < I256::ZERO {
return None;
}
let (hi, lo) = self.0.into_words();
if hi != 0 {
return None;
}
Some(u128::from_ne_bytes(lo.to_ne_bytes()))
}
#[must_use]
pub fn as_i128(&self) -> Option<i128> {
let min = I256::from(i128::MIN);
let max = I256::from(i128::MAX);
if self.0 < min || self.0 > max {
return None;
}
let (_hi, lo) = self.0.into_words();
Some(lo)
}
#[must_use]
pub fn as_u32(&self) -> Option<u32> {
self.as_u128().and_then(|v| u32::try_from(v).ok())
}
#[must_use]
pub fn as_u64(&self) -> Option<u64> {
self.as_u128().and_then(|v| u64::try_from(v).ok())
}
}
impl std::fmt::Display for TypeDescriptor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let joined = |types: &[TypeDescriptor]| {
types
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
};
match self {
Self::Boolean => f.write_str("Boolean"),
Self::Field => f.write_str("Field"),
Self::JubjubScalar => f.write_str("JubjubScalar"),
Self::Secp256k1Base => f.write_str("Secp256k1Base"),
Self::Secp256k1Scalar => f.write_str("Secp256k1Scalar"),
Self::Secp256r1Base => f.write_str("Secp256r1Base"),
Self::Secp256r1Scalar => f.write_str("Secp256r1Scalar"),
Self::Curve25519Base => f.write_str("Curve25519Base"),
Self::Curve25519Scalar => f.write_str("Curve25519Scalar"),
Self::JubjubPoint => f.write_str("JubjubPoint"),
Self::Secp256k1Point => f.write_str("Secp256k1Point"),
Self::Secp256r1Point => f.write_str("Secp256r1Point"),
Self::Curve25519Point => f.write_str("Curve25519Point"),
Self::Uint { maxval, .. } => write!(f, "Uint<0..{maxval}>"),
Self::Bytes { length } => write!(f, "Bytes<{length}>"),
Self::Opaque { ts_type } => write!(f, "Opaque<{ts_type}>"),
Self::Tuple { types } => write!(f, "Tuple<{}>", joined(types)),
Self::Vector { length, elt_type } => write!(f, "Vector<{length}, {elt_type}>"),
Self::Set { of } => write!(f, "Set<{of}>"),
Self::List { of } => write!(f, "List<{of}>"),
Self::Map { key, value } => write!(f, "Map<{key}, {value}>"),
Self::MerkleTree { depth, of } => write!(f, "MerkleTree<{depth}, {of}>"),
Self::HistoricMerkleTree { depth, of } => {
write!(f, "HistoricMerkleTree<{depth}, {of}>")
}
Self::Counter => f.write_str("Counter"),
Self::Cell { of } => write!(f, "Cell<{of}>"),
Self::Struct { name, .. } => write!(f, "Struct<{name}>"),
Self::Enum { name, .. } => write!(f, "Enum<{name}>"),
Self::Alias { name, .. } => write!(f, "Alias<{name}>"),
Self::Contract { name, .. } => write!(f, "Contract<{name}>"),
Self::Unknown => f.write_str("Unknown"),
}
}
}
impl std::fmt::Display for IntLit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl Serialize for IntLit {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self.as_i128().and_then(|v| i64::try_from(v).ok()) {
Some(v) => s.serialize_i64(v),
None => s.serialize_str(&self.0.to_string()),
}
}
}
impl<'de> Deserialize<'de> for IntLit {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = IntLit;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("an integer (JSON number or decimal string)")
}
fn visit_u64<E: de::Error>(self, v: u64) -> Result<IntLit, E> {
Ok(IntLit(I256::from(v)))
}
fn visit_i64<E: de::Error>(self, v: i64) -> Result<IntLit, E> {
Ok(IntLit(I256::from(v)))
}
fn visit_u128<E: de::Error>(self, v: u128) -> Result<IntLit, E> {
Ok(IntLit(I256::from(v)))
}
fn visit_i128<E: de::Error>(self, v: i128) -> Result<IntLit, E> {
Ok(IntLit(I256::from(v)))
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<IntLit, E> {
v.parse::<I256>()
.map(IntLit)
.map_err(|e| E::custom(format!("invalid integer literal '{v}': {e}")))
}
fn visit_string<E: de::Error>(self, v: String) -> Result<IntLit, E> {
self.visit_str(&v)
}
}
d.deserialize_any(V)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MoonIr {
#[serde(rename = "schema-version")]
pub schema_version: u32,
#[serde(rename = "compiler-version")]
pub compiler_version: String,
#[serde(rename = "language-version")]
pub language_version: String,
#[serde(rename = "runtime-version")]
pub runtime_version: String,
#[serde(default)]
pub contracts: Vec<TypeDescriptor>,
#[serde(default)]
pub ledger: Vec<LedgerField>,
#[serde(default)]
pub witnesses: Vec<Witness>,
#[serde(default)]
pub natives: Vec<Native>,
#[serde(default)]
pub circuits: Vec<CircuitBody>,
#[serde(default)]
pub descriptors: IndexMap<String, TypeDescriptor>,
pub constructor: Constructor,
#[serde(rename = "external-contracts", default)]
pub external_contracts: Vec<RuntimeValue>,
#[serde(rename = "pure-circuits", default)]
pub pure_circuits: Vec<RuntimeValue>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub frontend: Option<FrontendMeta>,
#[serde(
rename = "debug-info",
default,
skip_serializing_if = "Option::is_none"
)]
pub debug_info: Option<DebugInfo>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capabilities: Option<CapabilitiesMeta>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub workflows: Vec<WorkflowMeta>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub privacy: Option<PrivacyMeta>,
#[serde(
rename = "type-roles",
default,
skip_serializing_if = "IndexMap::is_empty"
)]
pub type_roles: IndexMap<String, SemanticTypeRole>,
}
impl MoonIr {
#[must_use]
pub fn new_v3(
compiler_version: impl Into<String>,
language_version: impl Into<String>,
runtime_version: impl Into<String>,
) -> Self {
Self {
schema_version: crate::loader::SUPPORTED_SCHEMA_VERSION,
compiler_version: compiler_version.into(),
language_version: language_version.into(),
runtime_version: runtime_version.into(),
contracts: Vec::new(),
ledger: Vec::new(),
witnesses: Vec::new(),
natives: Vec::new(),
circuits: Vec::new(),
descriptors: IndexMap::new(),
constructor: Constructor::default(),
external_contracts: Vec::new(),
pure_circuits: Vec::new(),
frontend: None,
debug_info: None,
capabilities: None,
workflows: Vec::new(),
privacy: None,
type_roles: IndexMap::new(),
}
}
#[must_use]
pub fn with_frontend(mut self, frontend: FrontendMeta) -> Self {
self.frontend = Some(frontend);
self
}
#[must_use]
pub fn with_debug_info(mut self, debug_info: DebugInfo) -> Self {
self.debug_info = Some(debug_info);
self
}
#[must_use]
pub fn with_capabilities(mut self, capabilities: CapabilitiesMeta) -> Self {
self.capabilities = Some(capabilities);
self
}
#[must_use]
pub fn with_workflows(mut self, workflows: Vec<WorkflowMeta>) -> Self {
self.workflows = workflows;
self
}
#[must_use]
pub fn with_privacy(mut self, privacy: PrivacyMeta) -> Self {
self.privacy = Some(privacy);
self
}
#[must_use]
pub fn with_type_roles(mut self, type_roles: IndexMap<String, SemanticTypeRole>) -> Self {
self.type_roles = type_roles;
self
}
#[must_use]
pub fn with_type_role(
mut self,
descriptor_key: impl Into<String>,
role: SemanticTypeRole,
) -> Self {
self.type_roles.insert(descriptor_key.into(), role);
self
}
#[must_use]
pub fn with_constructor(mut self, constructor: Constructor) -> Self {
self.constructor = constructor;
self
}
pub fn add_ledger_field(&mut self, field: LedgerField) -> &mut Self {
self.ledger.push(field);
self
}
pub fn add_witness(&mut self, witness: Witness) -> &mut Self {
self.witnesses.push(witness);
self
}
pub fn add_native(&mut self, native: Native) -> &mut Self {
self.natives.push(native);
self
}
pub fn add_circuit(&mut self, circuit: CircuitBody) -> &mut Self {
self.circuits.push(circuit);
self
}
pub fn add_descriptor(
&mut self,
key: impl Into<String>,
descriptor: TypeDescriptor,
) -> &mut Self {
self.descriptors.insert(key.into(), descriptor);
self
}
pub fn add_workflow(&mut self, workflow: WorkflowMeta) -> &mut Self {
self.workflows.push(workflow);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FrontendLanguage {
Compact,
Pact5,
Custom(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendMeta {
pub language: FrontendLanguage,
#[serde(rename = "frontend-version")]
pub frontend_version: String,
#[serde(
rename = "source-module",
default,
skip_serializing_if = "Option::is_none"
)]
pub source_module: Option<String>,
#[serde(
rename = "source-hash",
default,
skip_serializing_if = "Option::is_none"
)]
pub source_hash: Option<String>,
#[serde(default, skip_serializing_if = "IndexMap::is_empty")]
pub metadata: IndexMap<String, String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceSpan {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file: Option<String>,
#[serde(rename = "start-line")]
pub start_line: u32,
#[serde(rename = "start-col")]
pub start_col: u32,
#[serde(rename = "end-line")]
pub end_line: u32,
#[serde(rename = "end-col")]
pub end_col: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct DebugInfo {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sources: Vec<String>,
#[serde(
rename = "circuit-spans",
default,
skip_serializing_if = "IndexMap::is_empty"
)]
pub circuit_spans: IndexMap<String, SourceSpan>,
#[serde(
rename = "field-spans",
default,
skip_serializing_if = "IndexMap::is_empty"
)]
pub field_spans: IndexMap<String, SourceSpan>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum GovernanceSpec {
Keyset { name: String },
Capability { name: String },
Custom { description: String },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CapabilityKind {
Basic,
Managed,
Event,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CapabilityDef {
pub name: String,
pub kind: CapabilityKind,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub arguments: Vec<Argument>,
#[serde(
rename = "managed-param",
default,
skip_serializing_if = "Option::is_none"
)]
pub managed_param: Option<String>,
#[serde(
rename = "manager-circuit",
default,
skip_serializing_if = "Option::is_none"
)]
pub manager_circuit: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub composes: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CircuitCapUsage {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub acquires: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub requires: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub emits: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct CapabilitiesMeta {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub governance: Option<GovernanceSpec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub capabilities: Vec<CapabilityDef>,
#[serde(
rename = "circuit-usage",
default,
skip_serializing_if = "IndexMap::is_empty"
)]
pub circuit_usage: IndexMap<String, CircuitCapUsage>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkflowStepMeta {
pub index: u32,
pub circuit: String,
#[serde(
rename = "rollback-circuit",
default,
skip_serializing_if = "Option::is_none"
)]
pub rollback_circuit: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub entity: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub yields: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkflowMeta {
pub name: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub steps: Vec<WorkflowStepMeta>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PrivacyClass {
Public,
Private,
Shielded,
Disclosed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FieldRole {
State,
Commitment,
Nullifier,
Ciphertext,
Authority,
Balance,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CircuitBoundsMeta {
#[serde(
rename = "max-constraints",
default,
skip_serializing_if = "Option::is_none"
)]
pub max_constraints: Option<u64>,
#[serde(
rename = "max-public-inputs",
default,
skip_serializing_if = "Option::is_none"
)]
pub max_public_inputs: Option<u32>,
#[serde(
rename = "max-witness-elements",
default,
skip_serializing_if = "Option::is_none"
)]
pub max_witness_elements: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct PrivacyMeta {
#[serde(
rename = "field-classes",
default,
skip_serializing_if = "IndexMap::is_empty"
)]
pub field_classes: IndexMap<String, PrivacyClass>,
#[serde(
rename = "field-roles",
default,
skip_serializing_if = "IndexMap::is_empty"
)]
pub field_roles: IndexMap<String, FieldRole>,
#[serde(
rename = "circuit-bounds",
default,
skip_serializing_if = "IndexMap::is_empty"
)]
pub circuit_bounds: IndexMap<String, CircuitBoundsMeta>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "role", rename_all = "kebab-case")]
pub enum SemanticTypeRole {
FixedDecimal {
scale: u8,
signed: bool,
},
SignedInt {
bits: u16,
},
BoundedList {
#[serde(rename = "max-len")]
max_len: u32,
},
Guard,
Timestamp,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FieldType {
Field,
JubjubScalar,
Secp256k1Base,
Secp256k1Scalar,
Secp256r1Base,
Secp256r1Scalar,
Curve25519Base,
Curve25519Scalar,
}
impl FieldType {
#[must_use]
pub fn descriptor(self) -> TypeDescriptor {
match self {
FieldType::Field => TypeDescriptor::Field,
FieldType::JubjubScalar => TypeDescriptor::JubjubScalar,
FieldType::Secp256k1Base => TypeDescriptor::Secp256k1Base,
FieldType::Secp256k1Scalar => TypeDescriptor::Secp256k1Scalar,
FieldType::Secp256r1Base => TypeDescriptor::Secp256r1Base,
FieldType::Secp256r1Scalar => TypeDescriptor::Secp256r1Scalar,
FieldType::Curve25519Base => TypeDescriptor::Curve25519Base,
FieldType::Curve25519Scalar => TypeDescriptor::Curve25519Scalar,
}
}
#[must_use]
pub fn of_descriptor(descriptor: &TypeDescriptor) -> Option<FieldType> {
Some(match descriptor {
TypeDescriptor::Field => FieldType::Field,
TypeDescriptor::JubjubScalar => FieldType::JubjubScalar,
TypeDescriptor::Secp256k1Base => FieldType::Secp256k1Base,
TypeDescriptor::Secp256k1Scalar => FieldType::Secp256k1Scalar,
TypeDescriptor::Secp256r1Base => FieldType::Secp256r1Base,
TypeDescriptor::Secp256r1Scalar => FieldType::Secp256r1Scalar,
TypeDescriptor::Curve25519Base => FieldType::Curve25519Base,
TypeDescriptor::Curve25519Scalar => FieldType::Curve25519Scalar,
_ => return None,
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type-name")]
pub enum TypeDescriptor {
Boolean,
Field,
JubjubScalar,
Secp256k1Base,
Secp256k1Scalar,
Secp256r1Base,
Secp256r1Scalar,
Curve25519Base,
Curve25519Scalar,
JubjubPoint,
Secp256k1Point,
Secp256r1Point,
Curve25519Point,
Unknown,
Uint {
maxval: IntLit,
#[serde(default, rename = "alignment-bytes")]
alignment_bytes: Option<u32>,
},
Bytes {
length: u32,
},
Opaque {
#[serde(rename = "tsType")]
ts_type: String,
},
Vector {
length: u32,
#[serde(rename = "type")]
elt_type: Box<TypeDescriptor>,
},
Tuple {
types: Vec<TypeDescriptor>,
},
Struct {
name: String,
elements: Vec<StructField>,
},
Enum {
name: String,
elements: Vec<String>,
},
Alias {
name: String,
#[serde(rename = "type")]
of: Box<TypeDescriptor>,
},
Contract {
name: String,
circuits: Vec<ContractCircuitSig>,
},
Cell {
#[serde(rename = "type")]
of: Box<TypeDescriptor>,
},
Counter,
Map {
key: Box<TypeDescriptor>,
value: Box<TypeDescriptor>,
},
Set {
#[serde(rename = "type")]
of: Box<TypeDescriptor>,
},
List {
#[serde(rename = "type")]
of: Box<TypeDescriptor>,
},
MerkleTree {
depth: IntLit,
#[serde(rename = "type")]
of: Box<TypeDescriptor>,
},
HistoricMerkleTree {
depth: IntLit,
#[serde(rename = "type")]
of: Box<TypeDescriptor>,
},
}
impl TypeDescriptor {
#[must_use]
pub fn contract_address() -> Self {
TypeDescriptor::Struct {
name: "ContractAddress".to_owned(),
elements: vec![StructField {
name: "bytes".to_owned(),
field_type: TypeDescriptor::Bytes { length: 32 },
}],
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StructField {
pub name: String,
#[serde(rename = "type")]
pub field_type: TypeDescriptor,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ContractCircuitSig {
pub name: String,
#[serde(rename = "argument-types")]
pub argument_types: Vec<TypeDescriptor>,
#[serde(rename = "result-type")]
pub result_type: TypeDescriptor,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LedgerField {
pub name: String,
#[serde(
deserialize_with = "deserialize_field_index",
serialize_with = "serialize_field_index"
)]
pub index: Vec<u32>,
pub exported: bool,
#[serde(flatten)]
pub storage: Storage,
}
impl LedgerField {
#[must_use]
pub fn leaf_index(&self) -> u32 {
self.index.last().copied().unwrap_or(0)
}
}
fn serialize_field_index<S>(v: &[u32], s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeSeq;
if v.len() == 1 {
s.serialize_u32(v[0])
} else {
let mut seq = s.serialize_seq(Some(v.len()))?;
for n in v {
seq.serialize_element(n)?;
}
seq.end()
}
}
fn deserialize_field_index<'de, D>(d: D) -> Result<Vec<u32>, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::{self, Error, SeqAccess, Visitor};
use std::fmt;
struct V;
impl<'de> Visitor<'de> for V {
type Value = Vec<u32>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a non-negative integer or an array of non-negative integers")
}
fn visit_u64<E: Error>(self, v: u64) -> Result<Vec<u32>, E> {
u32::try_from(v)
.map(|n| vec![n])
.map_err(|_| Error::custom(format!("ledger field index {v} exceeds u32::MAX")))
}
fn visit_i64<E: Error>(self, v: i64) -> Result<Vec<u32>, E> {
u32::try_from(v)
.map(|n| vec![n])
.map_err(|_| Error::custom(format!("ledger field index {v} not in u32 range")))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u32>, A::Error> {
let mut out: Vec<u32> = Vec::new();
while let Some(elem) = seq.next_element::<i64>()? {
let n = u32::try_from(elem).map_err(|_| {
de::Error::custom(format!(
"ledger field index path entry {elem} not in u32 range"
))
})?;
out.push(n);
}
Ok(out)
}
}
d.deserialize_any(V)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "storage")]
pub enum Storage {
Counter,
Cell {
#[serde(rename = "type")]
of: TypeDescriptor,
},
Map {
key: TypeDescriptor,
value: TypeDescriptor,
},
Set {
#[serde(rename = "type")]
of: TypeDescriptor,
},
List {
#[serde(rename = "type")]
of: TypeDescriptor,
},
MerkleTree {
#[serde(rename = "type")]
of: TypeDescriptor,
},
HistoricMerkleTree {
#[serde(rename = "type")]
of: TypeDescriptor,
},
}
impl Storage {
#[must_use]
pub fn kind(&self) -> &'static str {
match self {
Self::Counter => "Counter",
Self::Cell { .. } => "Cell",
Self::Map { .. } => "Map",
Self::Set { .. } => "Set",
Self::List { .. } => "List",
Self::MerkleTree { .. } => "MerkleTree",
Self::HistoricMerkleTree { .. } => "HistoricMerkleTree",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Witness {
pub name: String,
#[serde(default)]
pub arguments: Vec<Argument>,
#[serde(rename = "result-type")]
pub result_type: TypeDescriptor,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Native {
pub name: String,
#[serde(rename = "internal-uniq", default)]
pub internal_uniq: Option<u64>,
#[serde(rename = "host-symbol")]
pub host_symbol: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub intrinsic: Option<String>,
pub class: String,
#[serde(default)]
pub arguments: Vec<Argument>,
#[serde(rename = "result-type")]
pub result_type: TypeDescriptor,
}
impl Native {
#[must_use]
pub fn new_intrinsic(
name: impl Into<String>,
intrinsic: impl Into<String>,
class: impl Into<String>,
arguments: Vec<Argument>,
result_type: TypeDescriptor,
) -> Self {
let intr = intrinsic.into();
Self {
name: name.into(),
internal_uniq: None,
host_symbol: intr.clone(),
intrinsic: Some(intr),
class: class.into(),
arguments,
result_type,
}
}
#[must_use]
pub fn resolve_intrinsic(&self) -> &str {
if let Some(ref intrinsic) = self.intrinsic {
intrinsic.as_str()
} else {
self.host_symbol
.strip_prefix("__compactRuntime.")
.unwrap_or(&self.host_symbol)
}
}
}
#[must_use]
pub fn canonical_intrinsic_name(raw: &str) -> &str {
let trimmed = raw.strip_prefix("__compactRuntime.").unwrap_or(raw);
match trimmed {
"mp:hash/persistent" => "persistentHash",
"mp:hash/transient" | "mp:hash/poseidon" => "transientHash",
"mp:commit/persistent" | "mp:hash/persistent-commit" => "persistentCommit",
"mp:commit/transient" | "mp:hash/transient-commit" => "transientCommit",
"mp:hash/degrade-to-transient" => "degradeToTransient",
"mp:hash/upgrade-from-transient" => "upgradeFromTransient",
"mp:hash/keccak256" => "keccak256",
"mp:hash/sha512" => "sha512",
"mp:hash/to-curve" | "mp:curve/hash-to-curve" => "hashToCurve",
"mp:coin/commitment" | "mp:zswap/coin-commitment" => "coinCommitment",
"mp:coin/token-type" | "mp:zswap/token-type" => "tokenType",
"mp:context/own-public-key"
| "mp:zswap/own-public-key"
| "mp:auth/own-public-key"
| "mp:ledger/own-public-key" => "ownPublicKey",
"mp:zswap/create-output" => "createZswapOutput",
"mp:zswap/create-input" => "createZswapInput",
"mp:curve/jubjub-point-x" | "mp:ec/jubjub-point-x" => "jubjubPointX",
"mp:curve/jubjub-point-y" | "mp:ec/jubjub-point-y" => "jubjubPointY",
"mp:curve/jubjub-construct" | "mp:ec/jubjub-construct" => "constructJubjubPoint",
"mp:curve/jubjub-add" | "mp:ec/add" | "mp:ec/jubjub-add" => "ecAdd",
"mp:curve/jubjub-mul" | "mp:ec/mul" | "mp:ec/jubjub-mul" => "ecMul",
"mp:curve/jubjub-mul-generator" | "mp:ec/mul-generator" | "mp:ec/jubjub-mul-generator" => {
"ecMulGenerator"
}
"mp:curve/jubjub-neg" | "mp:ec/neg" | "mp:ec/jubjub-neg" => "ecNeg",
"mp:curve/jubjub-scalar-from-native"
| "mp:ec/jubjub-scalar-from-native"
| "reduceModJubjubOrder" => "jubjubScalarFromNative",
"mp:curve/secp256k1-add" | "mp:ec/secp256k1-add" => "secp256k1Add",
"mp:curve/secp256r1-add" | "mp:ec/secp256r1-add" => "secp256r1Add",
"mp:curve/curve25519-add" | "mp:ec/curve25519-add" => "curve25519Add",
"mp:curve/secp256k1-mul" | "mp:ec/secp256k1-mul" => "secp256k1Mul",
"mp:curve/secp256r1-mul" | "mp:ec/secp256r1-mul" => "secp256r1Mul",
"mp:curve/curve25519-mul" | "mp:ec/curve25519-mul" => "curve25519Mul",
"mp:curve/secp256k1-mul-generator" | "mp:ec/secp256k1-mul-generator" => {
"secp256k1MulGenerator"
}
"mp:curve/secp256r1-mul-generator" | "mp:ec/secp256r1-mul-generator" => {
"secp256r1MulGenerator"
}
"mp:curve/curve25519-mul-generator" | "mp:ec/curve25519-mul-generator" => {
"curve25519MulGenerator"
}
"mp:merkle/path-root" => "merkleTreePathRoot",
"mp:merkle/path-root-no-leaf-hash" => "merkleTreePathRootNoLeafHash",
"mp:crypto/ed25519-verify" | "mp:sig/ed25519-verify" => "ed25519Verify",
"mp:crypto/secp256r1-ecdsa-verify"
| "mp:sig/secp256r1-ecdsa-verify"
| "mp:crypto/ecdsa-p256-verify" => "secp256r1EcdsaVerify",
"mp:crypto/secp256k1-ecdsa-verify"
| "mp:sig/secp256k1-ecdsa-verify"
| "mp:crypto/ecdsa-secp256k1-verify" => "secp256k1EcdsaVerify",
other => other,
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Argument {
pub name: String,
#[serde(rename = "type")]
pub arg_type: TypeDescriptor,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Constructor {
#[serde(default)]
pub arguments: Vec<Argument>,
#[serde(rename = "initial-state")]
pub initial_state: StateValue,
#[serde(rename = "init-ops", default)]
pub init_ops: Vec<Expression>,
#[serde(rename = "register-operations", default)]
pub register_operations: Vec<String>,
pub body: Statement,
}
impl Default for Constructor {
fn default() -> Self {
Self {
arguments: Vec::new(),
initial_state: StateValue::Null,
init_ops: Vec::new(),
register_operations: Vec::new(),
body: Statement::Noop,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CircuitBody {
pub name: String,
#[serde(rename = "internal-name")]
pub internal_name: String,
#[serde(rename = "internal-uniq", default)]
pub internal_uniq: Option<u64>,
pub exported: bool,
pub pure: bool,
pub proof: bool,
#[serde(default)]
pub arguments: Vec<Argument>,
#[serde(rename = "result-type")]
pub result_type: TypeDescriptor,
pub body: Statement,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "stmt", rename_all = "kebab-case")]
pub enum Statement {
Seq {
items: Vec<Statement>,
},
If {
cond: Expression,
then: Box<Statement>,
#[serde(default)]
r#else: Option<Box<Statement>>,
},
Const {
binding: BindingTarget,
value: Expression,
},
ConstDestructure {
bindings: Vec<BindingTarget>,
},
Expr {
value: Expression,
},
Unimplemented,
Noop,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BindingTarget {
pub name: String,
#[serde(rename = "type")]
pub binding_type: TypeDescriptor,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "expr", rename_all = "kebab-case")]
pub enum Expression {
Literal {
value: crate::value::RuntimeValue,
},
Var {
name: String,
},
Default {
#[serde(rename = "type")]
of_type: TypeDescriptor,
},
If {
cond: Box<Expression>,
then: Box<Expression>,
r#else: Box<Expression>,
},
EltRef {
value: Box<Expression>,
field: String,
index: IntLit,
},
EnumRef {
#[serde(rename = "type")]
of_type: TypeDescriptor,
variant: String,
},
Tuple {
items: Vec<TupleItem>,
},
Vector {
items: Vec<TupleItem>,
},
TupleRef {
value: Box<Expression>,
index: IntLit,
},
TupleSlice {
value: Box<Expression>,
start: IntLit,
length: IntLit,
#[serde(rename = "result-type")]
result_type: TypeDescriptor,
},
VectorRef {
value: Box<Expression>,
index: Box<Expression>,
#[serde(rename = "result-type")]
result_type: TypeDescriptor,
},
VectorSlice {
value: Box<Expression>,
start: Box<Expression>,
length: IntLit,
#[serde(rename = "result-type")]
result_type: TypeDescriptor,
},
BytesRef {
value: Box<Expression>,
index: Box<Expression>,
#[serde(rename = "result-type")]
result_type: TypeDescriptor,
},
BytesSlice {
value: Box<Expression>,
start: Box<Expression>,
length: IntLit,
#[serde(rename = "result-type")]
result_type: TypeDescriptor,
},
Binop {
op: String,
#[serde(default)]
bits: Option<u32>,
#[serde(rename = "type", default)]
of_type: Option<TypeDescriptor>,
left: Box<Expression>,
right: Box<Expression>,
},
Eq {
#[serde(rename = "type", default)]
of_type: Option<TypeDescriptor>,
left: Box<Expression>,
right: Box<Expression>,
},
Neq {
#[serde(rename = "type", default)]
of_type: Option<TypeDescriptor>,
left: Box<Expression>,
right: Box<Expression>,
},
And {
left: Box<Expression>,
right: Box<Expression>,
},
Or {
left: Box<Expression>,
right: Box<Expression>,
},
Not {
value: Box<Expression>,
},
Assign {
name: String,
value: Box<Expression>,
},
Call {
function: String,
#[serde(rename = "function-uniq", default)]
function_uniq: Option<u64>,
arguments: Vec<Expression>,
},
New {
#[serde(rename = "type")]
of_type: TypeDescriptor,
arguments: Vec<Expression>,
},
Seq {
items: Vec<Expression>,
},
Cast {
to: TypeDescriptor,
value: Box<Expression>,
},
SafeCast {
to: TypeDescriptor,
from: TypeDescriptor,
value: Box<Expression>,
},
DowncastUnsigned {
#[serde(rename = "from-bits")]
from_bits: Option<IntLit>,
#[serde(rename = "to-bits")]
to_bits: IntLit,
value: Box<Expression>,
},
#[serde(rename = "field->bytes")]
FieldToBytes {
length: u32,
#[serde(rename = "field-type", default)]
field_type: Option<FieldType>,
value: Box<Expression>,
},
#[serde(rename = "cast-to-field")]
CastToField {
#[serde(rename = "field-type")]
field_type: FieldType,
from: TypeDescriptor,
value: Box<Expression>,
},
#[serde(rename = "cast-from-field")]
CastFromField {
maxval: IntLit,
#[serde(rename = "field-type")]
field_type: FieldType,
value: Box<Expression>,
},
Emit {
#[serde(rename = "event-version")]
event_version: u32,
#[serde(rename = "event-tag")]
event_tag: u32,
#[serde(rename = "payload-length")]
payload_length: u32,
payload: Box<Expression>,
#[serde(rename = "vm-ops", default)]
vm_ops: Vec<VmInstr>,
},
#[serde(rename = "cast-from-bytes")]
CastFromBytes {
to: TypeDescriptor,
length: u32,
value: Box<Expression>,
},
#[serde(rename = "vector->bytes")]
VectorToBytes {
length: u32,
value: Box<Expression>,
},
#[serde(rename = "bytes->vector")]
BytesToVector {
length: u32,
value: Box<Expression>,
},
CastFromEnum {
from: TypeDescriptor,
to: TypeDescriptor,
value: Box<Expression>,
},
CastToEnum {
from: TypeDescriptor,
to: TypeDescriptor,
value: Box<Expression>,
},
Assert {
cond: Box<Expression>,
message: String,
},
Map {
length: IntLit,
function: crate::value::RuntimeValue,
arguments: Vec<crate::value::RuntimeValue>,
},
Fold {
length: IntLit,
function: crate::value::RuntimeValue,
initial: crate::value::RuntimeValue,
arguments: Vec<crate::value::RuntimeValue>,
},
AdtOp(AdtOpInvocation),
ContractCall {
circuit: String,
address: Box<Expression>,
#[serde(rename = "address-type")]
address_type: TypeDescriptor,
arguments: Vec<Expression>,
},
Unimplemented,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TupleItem {
pub kind: String, #[serde(default)]
pub length: Option<IntLit>,
pub value: Expression,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdtOpInvocation {
pub adt: String,
pub operation: String,
#[serde(rename = "op-class")]
pub op_class: String,
#[serde(rename = "op-class-coin-index", default)]
pub op_class_coin_index: Option<u32>,
#[serde(rename = "op-class-recipient-index", default)]
pub op_class_recipient_index: Option<u32>,
#[serde(default)]
pub field: Option<String>,
#[serde(rename = "field-path", default)]
pub field_path: Vec<PathElement>,
#[serde(default)]
pub arguments: Vec<Expression>,
#[serde(rename = "result-type")]
pub result_type: TypeDescriptor,
#[serde(rename = "vm-ops")]
pub vm_ops: Vec<VmInstr>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum PathElement {
Literal {
index: u32,
},
Expr {
#[serde(rename = "type")]
of_type: TypeDescriptor,
value: Box<Expression>,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VmInstr(pub std::collections::BTreeMap<String, crate::value::RuntimeValue>);
impl VmInstr {
#[must_use]
pub fn op(&self) -> Option<&str> {
self.0
.get("op")
.and_then(crate::value::RuntimeValue::as_str)
}
}
pub type VmOp = crate::value::RuntimeValue;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum StateValue {
Null,
Cell {
#[serde(default)]
descriptor: Option<String>,
value: crate::value::RuntimeValue,
},
CellExpr {
#[serde(default)]
descriptor: Option<String>,
value: Box<Expression>,
},
Array {
items: Vec<StateValue>,
},
Map {
entries: Vec<MapEntry>,
},
MerkleTree {
depth: IntLit,
#[serde(default)]
entries: Vec<MapEntry>,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MapEntry {
pub key: StateValue,
pub value: StateValue,
}