use std::collections::{BTreeMap, BTreeSet};
use moonproof_runtime_ir::value::ValueProjectionError;
use moonproof_runtime_ir::RuntimeValue;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
pub struct CompactMap<K, V> {
inner: BTreeMap<K, V>,
}
impl<K: Ord, V> CompactMap<K, V> {
#[must_use]
pub fn new(inner: BTreeMap<K, V>) -> Self {
Self { inner }
}
#[must_use]
pub fn lookup(&self, k: &K) -> Option<&V> {
self.inner.get(k)
}
#[must_use]
pub fn member(&self, k: &K) -> bool {
self.inner.contains_key(k)
}
#[must_use]
pub fn size(&self) -> u64 {
self.inner.len() as u64
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn iter(&self) -> std::collections::btree_map::Iter<'_, K, V> {
self.inner.iter()
}
#[must_use]
pub fn into_inner(self) -> BTreeMap<K, V> {
self.inner
}
}
impl<'a, K: Ord, V> IntoIterator for &'a CompactMap<K, V> {
type Item = (&'a K, &'a V);
type IntoIter = std::collections::btree_map::Iter<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<K: Ord, V> IntoIterator for CompactMap<K, V> {
type Item = (K, V);
type IntoIter = std::collections::btree_map::IntoIter<K, V>;
fn into_iter(self) -> Self::IntoIter {
self.inner.into_iter()
}
}
#[derive(Debug, Clone)]
pub struct CompactSet<T> {
inner: BTreeSet<T>,
}
impl<T: Ord> CompactSet<T> {
#[must_use]
pub fn new(elements: Vec<T>) -> Self {
Self {
inner: elements.into_iter().collect(),
}
}
#[must_use]
pub fn member(&self, t: &T) -> bool {
self.inner.contains(t)
}
#[must_use]
pub fn size(&self) -> u64 {
self.inner.len() as u64
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn iter(&self) -> std::collections::btree_set::Iter<'_, T> {
self.inner.iter()
}
}
impl<'a, T: Ord> IntoIterator for &'a CompactSet<T> {
type Item = &'a T;
type IntoIter = std::collections::btree_set::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Debug, Clone)]
pub struct CompactList<T> {
inner: Vec<T>,
}
impl<T> CompactList<T> {
#[must_use]
pub fn new(inner: Vec<T>) -> Self {
Self { inner }
}
#[must_use]
pub fn head(&self) -> Option<&T> {
self.inner.first()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
#[must_use]
pub fn length(&self) -> u64 {
self.inner.len() as u64
}
pub fn iter(&self) -> std::slice::Iter<'_, T> {
self.inner.iter()
}
#[must_use]
pub fn into_inner(self) -> Vec<T> {
self.inner
}
}
impl<'a, T> IntoIterator for &'a CompactList<T> {
type Item = &'a T;
type IntoIter = std::slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct JubjubPoint {
pub x: [u8; 32],
pub y: [u8; 32],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Secp256k1Point {
pub x: [u8; 32],
pub y: [u8; 32],
pub identity: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Secp256r1Point {
pub x: [u8; 32],
pub y: [u8; 32],
pub identity: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Curve25519Point {
pub x: [u8; 32],
pub y: [u8; 32],
}
fn point_object(
value: RuntimeValue,
what: &str,
) -> Result<BTreeMap<String, RuntimeValue>, ValueProjectionError> {
match value {
RuntimeValue::Object(o) => Ok(o),
other => Err(ValueProjectionError::new(format!(
"expected Object for {what}, got {}",
other.type_label()
))),
}
}
fn point_entry(
obj: &mut BTreeMap<String, RuntimeValue>,
key: &str,
what: &str,
) -> Result<RuntimeValue, ValueProjectionError> {
obj.remove(key)
.ok_or_else(|| ValueProjectionError::new(format!("{what} missing field `{key}`")))
}
macro_rules! edwards_point_value {
($ty:ident) => {
impl From<$ty> for RuntimeValue {
fn from(p: $ty) -> Self {
RuntimeValue::Object(BTreeMap::from([
("x".to_owned(), RuntimeValue::from(p.x)),
("y".to_owned(), RuntimeValue::from(p.y)),
]))
}
}
impl TryFrom<RuntimeValue> for $ty {
type Error = ValueProjectionError;
fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
let what = stringify!($ty);
let mut obj = point_object(value, what)?;
Ok(Self {
x: point_entry(&mut obj, "x", what)?.try_into()?,
y: point_entry(&mut obj, "y", what)?.try_into()?,
})
}
}
};
}
macro_rules! weierstrass_point_value {
($ty:ident) => {
impl From<$ty> for RuntimeValue {
fn from(p: $ty) -> Self {
RuntimeValue::Object(BTreeMap::from([
("x".to_owned(), RuntimeValue::from(p.x)),
("y".to_owned(), RuntimeValue::from(p.y)),
("identity".to_owned(), RuntimeValue::Bool(p.identity)),
]))
}
}
impl TryFrom<RuntimeValue> for $ty {
type Error = ValueProjectionError;
fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
let what = stringify!($ty);
let mut obj = point_object(value, what)?;
Ok(Self {
x: point_entry(&mut obj, "x", what)?.try_into()?,
y: point_entry(&mut obj, "y", what)?.try_into()?,
identity: point_entry(&mut obj, "identity", what)?.try_into()?,
})
}
}
};
}
edwards_point_value!(JubjubPoint);
edwards_point_value!(Curve25519Point);
weierstrass_point_value!(Secp256k1Point);
weierstrass_point_value!(Secp256r1Point);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct MerkleTreeDigest {
pub field: [u8; 32],
}
impl From<MerkleTreeDigest> for RuntimeValue {
fn from(v: MerkleTreeDigest) -> Self {
RuntimeValue::Object(BTreeMap::from([(
"field".to_owned(),
RuntimeValue::from(v.field),
)]))
}
}
impl TryFrom<RuntimeValue> for MerkleTreeDigest {
type Error = ValueProjectionError;
fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
let mut obj = expect_object(value, "MerkleTreeDigest")?;
Ok(Self {
field: take_field(&mut obj, "field", "MerkleTreeDigest")?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct MerkleTreePathEntry {
pub sibling: MerkleTreeDigest,
pub goes_left: bool,
}
impl From<MerkleTreePathEntry> for RuntimeValue {
fn from(v: MerkleTreePathEntry) -> Self {
RuntimeValue::Object(BTreeMap::from([
("sibling".to_owned(), RuntimeValue::from(v.sibling)),
("goes_left".to_owned(), RuntimeValue::from(v.goes_left)),
]))
}
}
impl TryFrom<RuntimeValue> for MerkleTreePathEntry {
type Error = ValueProjectionError;
fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
let mut obj = expect_object(value, "MerkleTreePathEntry")?;
Ok(Self {
sibling: take_field(&mut obj, "sibling", "MerkleTreePathEntry")?,
goes_left: take_field(&mut obj, "goes_left", "MerkleTreePathEntry")?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MerkleTreePath<A> {
pub leaf: A,
pub path: Vec<MerkleTreePathEntry>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ZswapCoinPublicKey {
pub bytes: [u8; 32],
}
impl From<ZswapCoinPublicKey> for RuntimeValue {
fn from(v: ZswapCoinPublicKey) -> Self {
RuntimeValue::Object(BTreeMap::from([(
"bytes".to_owned(),
RuntimeValue::from(v.bytes),
)]))
}
}
impl TryFrom<RuntimeValue> for ZswapCoinPublicKey {
type Error = ValueProjectionError;
fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
let mut obj = expect_object(value, "ZswapCoinPublicKey")?;
Ok(Self {
bytes: take_field(&mut obj, "bytes", "ZswapCoinPublicKey")?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContractAddress {
pub bytes: [u8; 32],
}
impl From<ContractAddress> for RuntimeValue {
fn from(v: ContractAddress) -> Self {
RuntimeValue::Object(BTreeMap::from([(
"bytes".to_owned(),
RuntimeValue::from(v.bytes),
)]))
}
}
impl TryFrom<RuntimeValue> for ContractAddress {
type Error = ValueProjectionError;
fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
let mut obj = expect_object(value, "ContractAddress")?;
Ok(Self {
bytes: take_field(&mut obj, "bytes", "ContractAddress")?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserAddress {
pub bytes: [u8; 32],
}
impl From<UserAddress> for RuntimeValue {
fn from(v: UserAddress) -> Self {
RuntimeValue::Object(BTreeMap::from([(
"bytes".to_owned(),
RuntimeValue::from(v.bytes),
)]))
}
}
impl TryFrom<RuntimeValue> for UserAddress {
type Error = ValueProjectionError;
fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
let mut obj = expect_object(value, "UserAddress")?;
Ok(Self {
bytes: take_field(&mut obj, "bytes", "UserAddress")?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct OwnerEither {
pub is_left: bool,
pub left: ZswapCoinPublicKey,
pub right: ContractAddress,
}
impl OwnerEither {
#[must_use]
pub const fn coin_public_key(bytes: [u8; 32]) -> Self {
Self {
is_left: true,
left: ZswapCoinPublicKey { bytes },
right: ContractAddress { bytes: [0u8; 32] },
}
}
#[must_use]
pub const fn contract(bytes: [u8; 32]) -> Self {
Self {
is_left: false,
left: ZswapCoinPublicKey { bytes: [0u8; 32] },
right: ContractAddress { bytes },
}
}
}
impl From<OwnerEither> for RuntimeValue {
fn from(v: OwnerEither) -> Self {
RuntimeValue::Object(BTreeMap::from([
("is_left".to_owned(), RuntimeValue::from(v.is_left)),
("left".to_owned(), RuntimeValue::from(v.left)),
("right".to_owned(), RuntimeValue::from(v.right)),
]))
}
}
impl TryFrom<RuntimeValue> for OwnerEither {
type Error = ValueProjectionError;
fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
let mut obj = expect_object(value, "Either")?;
Ok(Self {
is_left: take_field(&mut obj, "is_left", "Either")?,
left: take_field(&mut obj, "left", "Either")?,
right: take_field(&mut obj, "right", "Either")?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShieldedCoinInfo {
pub nonce: [u8; 32],
pub color: [u8; 32],
pub value: u128,
}
impl From<ShieldedCoinInfo> for RuntimeValue {
fn from(v: ShieldedCoinInfo) -> Self {
RuntimeValue::Object(BTreeMap::from([
("nonce".to_owned(), RuntimeValue::from(v.nonce)),
("color".to_owned(), RuntimeValue::from(v.color)),
("value".to_owned(), RuntimeValue::from(v.value)),
]))
}
}
impl TryFrom<RuntimeValue> for ShieldedCoinInfo {
type Error = ValueProjectionError;
fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
let mut obj = expect_object(value, "ShieldedCoinInfo")?;
Ok(Self {
nonce: take_field(&mut obj, "nonce", "ShieldedCoinInfo")?,
color: take_field(&mut obj, "color", "ShieldedCoinInfo")?,
value: take_field(&mut obj, "value", "ShieldedCoinInfo")?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct QualifiedShieldedCoinInfo {
pub nonce: [u8; 32],
pub color: [u8; 32],
pub value: u128,
pub mt_index: u64,
}
impl From<QualifiedShieldedCoinInfo> for RuntimeValue {
fn from(v: QualifiedShieldedCoinInfo) -> Self {
RuntimeValue::Object(BTreeMap::from([
("nonce".to_owned(), RuntimeValue::from(v.nonce)),
("color".to_owned(), RuntimeValue::from(v.color)),
("value".to_owned(), RuntimeValue::from(v.value)),
("mt_index".to_owned(), RuntimeValue::from(v.mt_index)),
]))
}
}
impl TryFrom<RuntimeValue> for QualifiedShieldedCoinInfo {
type Error = ValueProjectionError;
fn try_from(value: RuntimeValue) -> Result<Self, Self::Error> {
let mut obj = expect_object(value, "QualifiedShieldedCoinInfo")?;
Ok(Self {
nonce: take_field(&mut obj, "nonce", "QualifiedShieldedCoinInfo")?,
color: take_field(&mut obj, "color", "QualifiedShieldedCoinInfo")?,
value: take_field(&mut obj, "value", "QualifiedShieldedCoinInfo")?,
mt_index: take_field(&mut obj, "mt_index", "QualifiedShieldedCoinInfo")?,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Recipient {
pub is_left: bool,
pub left: ZswapCoinPublicKey,
pub right: ContractAddress,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ShieldedCoinRecipient {
pub is_left: bool,
pub left: ZswapCoinPublicKey,
pub right: ContractAddress,
}
pub fn expect_object(
value: RuntimeValue,
what: &str,
) -> Result<BTreeMap<String, RuntimeValue>, ValueProjectionError> {
point_object(value, what)
}
pub fn take_raw_field(
obj: &mut BTreeMap<String, RuntimeValue>,
key: &str,
what: &str,
) -> Result<RuntimeValue, ValueProjectionError> {
point_entry(obj, key, what)
}
pub fn take_field<T: TryFrom<RuntimeValue, Error = ValueProjectionError>>(
obj: &mut BTreeMap<String, RuntimeValue>,
key: &str,
what: &str,
) -> Result<T, ValueProjectionError> {
take_raw_field(obj, key, what)?.try_into()
}
pub fn expect_string(value: RuntimeValue, what: &str) -> Result<String, ValueProjectionError> {
match value {
RuntimeValue::String(s) => Ok(s),
other => Err(ValueProjectionError::new(format!(
"expected String for `{what}`, got {}",
other.type_label()
))),
}
}
#[must_use]
pub fn unknown_variant(variant: &str, what: &str) -> ValueProjectionError {
ValueProjectionError::new(format!("unknown variant `{variant}` for `{what}`"))
}
#[must_use]
pub fn encode_contract_address(bytes: [u8; 32]) -> RuntimeValue {
RuntimeValue::Object(BTreeMap::from([(
"bytes".to_owned(),
RuntimeValue::Bytes(bytes.to_vec()),
)]))
}
pub fn decode_contract_address(value: RuntimeValue) -> Result<[u8; 32], ValueProjectionError> {
let raw = match value {
RuntimeValue::Object(mut obj) => obj.remove("bytes").ok_or_else(|| {
ValueProjectionError::new("expected `bytes` field in ContractAddress object".to_owned())
})?,
other @ RuntimeValue::Bytes(_) => other,
other => {
return Err(ValueProjectionError::new(format!(
"expected ContractAddress Object or Bytes, got {}",
other.type_label()
)));
}
};
<[u8; 32]>::try_from(raw)
}
pub fn encode_array<T, const N: usize, F>(arr: [T; N], mut f: F) -> RuntimeValue
where
F: FnMut(T) -> RuntimeValue,
{
RuntimeValue::Array(arr.into_iter().map(&mut f).collect())
}
pub fn decode_array<T, const N: usize, F>(
value: RuntimeValue,
mut f: F,
) -> Result<[T; N], ValueProjectionError>
where
F: FnMut(RuntimeValue) -> Result<T, ValueProjectionError>,
{
let items = match value {
RuntimeValue::Array(a) => a,
other => {
return Err(ValueProjectionError::new(format!(
"expected Vector array, got {}",
other.type_label()
)));
}
};
if items.len() != N {
return Err(ValueProjectionError::new(format!(
"Vector expected {N} elements, got {}",
items.len()
)));
}
let mut out = Vec::with_capacity(N);
for item in items {
out.push(f(item)?);
}
out.try_into().map_err(|_| {
ValueProjectionError::new("Vector length mismatch after projection".to_owned())
})
}
#[macro_export]
macro_rules! define_contract_wrapper {
(
$(#[$meta:meta])*
pub struct $name:ident <W: $witness_trait:ident>,
cbor = $cbor:ident
) => {
$(#[$meta])*
pub struct $name<W: $witness_trait> {
witnesses: ::std::sync::Arc<W>,
executable: ::std::sync::Arc<$crate::IrExecutable<W>>,
}
impl<W: $witness_trait + ::std::clone::Clone + 'static> $name<W> {
pub fn new(witnesses: W) -> $crate::IrResult<Self> {
let witnesses = ::std::sync::Arc::new(witnesses);
let exec = $crate::IrExecutable::from_cbor_slice($cbor, witnesses.clone())?;
Ok(Self {
witnesses,
executable: ::std::sync::Arc::new(exec),
})
}
#[must_use]
pub fn with_verifier_keys(
mut self,
keys: ::std::collections::HashMap<$crate::types::CircuitId, $crate::types::VerifierKey>,
) -> Self {
let exec = ::std::sync::Arc::make_mut(&mut self.executable);
exec.set_verifier_keys(
keys.into_iter()
.map(|(id, vk)| (id.as_str().to_owned(), vk))
.collect(),
);
self
}
#[must_use]
pub fn witnesses(&self) -> &::std::sync::Arc<W> {
&self.witnesses
}
#[must_use]
pub fn executable(&self) -> &::std::sync::Arc<$crate::IrExecutable<W>> {
&self.executable
}
pub async fn initial_state(
&self,
ctx: $crate::executable::ConstructorContext,
) -> ::std::result::Result<
$crate::executable::InitializeResult,
$crate::ContractRuntimeError,
> {
self.executable
.initialize(ctx, $crate::runtime_ir::RuntimeValue::Null)
.await
}
}
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn map_view_methods() {
let m = CompactMap::new(BTreeMap::from([
("a".to_owned(), 1u64),
("b".to_owned(), 2),
]));
assert_eq!(m.size(), 2);
assert!(!m.is_empty());
assert_eq!(m.lookup(&"a".to_owned()).copied(), Some(1));
assert!(m.member(&"b".to_owned()));
assert!(!m.member(&"missing".to_owned()));
}
#[test]
fn points_round_trip_through_runtime_value() {
let (x, y) = ([1u8; 32], [2u8; 32]);
for p in [
Secp256k1Point {
x,
y,
identity: false,
},
Secp256k1Point {
x,
y,
identity: true,
},
] {
assert_eq!(Secp256k1Point::try_from(RuntimeValue::from(p)).unwrap(), p);
}
let p = Secp256r1Point {
x,
y,
identity: true,
};
assert_eq!(Secp256r1Point::try_from(RuntimeValue::from(p)).unwrap(), p);
let p = Curve25519Point { x, y };
assert_eq!(Curve25519Point::try_from(RuntimeValue::from(p)).unwrap(), p);
let p = JubjubPoint { x, y };
assert_eq!(JubjubPoint::try_from(RuntimeValue::from(p)).unwrap(), p);
}
#[test]
fn weierstrass_point_without_identity_flag_is_rejected() {
let edwards = RuntimeValue::from(Curve25519Point {
x: [1; 32],
y: [2; 32],
});
let err = Secp256r1Point::try_from(edwards).unwrap_err();
assert!(err.0.contains("identity"), "{err}");
}
#[test]
fn list_view_methods() {
let l: CompactList<u64> = CompactList::new(vec![10, 20, 30]);
assert_eq!(l.length(), 3);
assert_eq!(l.head().copied(), Some(10));
assert!(!l.is_empty());
}
}