use ethnum::{I256, U256};
use crate::ir::{FieldType, IntLit, TypeDescriptor};
pub const FR_BYTES_STORED: u32 = 31;
pub const FR_BYTES: u32 = 32;
pub const JUBJUB_SCALAR_MODULUS: U256 = U256::from_words(
0x0E7D_B4EA_6533_AFA9_0667_3B01_0134_3B00,
0xA668_2093_CCC8_1082_D097_0E5E_D6F7_2CB7,
);
pub const SECP256K1_BASE_MODULUS: U256 = U256::from_words(
0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFE_FFFF_FC2F,
);
pub const SECP256K1_SCALAR_MODULUS: U256 = U256::from_words(
0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFE,
0xBAAE_DCE6_AF48_A03B_BFD2_5E8C_D036_4141,
);
pub const SECP256R1_BASE_MODULUS: U256 = U256::from_words(
0xFFFF_FFFF_0000_0001_0000_0000_0000_0000,
0x0000_0000_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
);
pub const SECP256R1_SCALAR_MODULUS: U256 = U256::from_words(
0xFFFF_FFFF_0000_0000_FFFF_FFFF_FFFF_FFFF,
0xBCE6_FAAD_A717_9E84_F3B9_CAC2_FC63_2551,
);
pub const CURVE25519_BASE_MODULUS: U256 = U256::from_words(
0x7FFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF,
0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFED,
);
pub const CURVE25519_SCALAR_MODULUS: U256 = U256::from_words(
0x1000_0000_0000_0000_0000_0000_0000_0000,
0x14DE_F9DE_A2F7_9CD6_5812_631A_5CF5_D3ED,
);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ChunkOrder {
MsbFirst,
LsbFirst,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ForeignFieldSplit {
pub low_bits: u32,
pub low_bytes: u32,
pub high_bytes: u32,
}
impl ForeignFieldSplit {
pub const SPLIT_192: Self = Self {
low_bits: 192,
low_bytes: 24,
high_bytes: 8,
};
pub const SPLIT_204: Self = Self {
low_bits: 204,
low_bytes: 26,
high_bytes: 7,
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AtomLayout {
Bytes { length: u32 },
Field,
Compress,
}
impl AtomLayout {
#[must_use]
pub const fn field_slots(self) -> usize {
match self {
Self::Field | Self::Compress => 1,
Self::Bytes { length } => length.div_ceil(FR_BYTES_STORED) as usize,
}
}
#[must_use]
pub const fn binary_len(self) -> usize {
match self {
Self::Field | Self::Compress => FR_BYTES as usize,
Self::Bytes { length } => length as usize,
}
}
#[must_use]
pub const fn is_multi_chunk_bytes(self) -> bool {
matches!(self, Self::Bytes { length } if length > FR_BYTES_STORED)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldLayout {
pub atoms: Vec<AtomLayout>,
}
impl FieldLayout {
#[must_use]
pub const fn empty() -> Self {
Self { atoms: Vec::new() }
}
#[must_use]
pub fn from_field_type(field_type: FieldType) -> Self {
match foreign_field_split(field_type) {
None => Self {
atoms: vec![AtomLayout::Field],
},
Some(split) => Self {
atoms: vec![
AtomLayout::Bytes {
length: split.low_bytes,
},
AtomLayout::Bytes {
length: split.high_bytes,
},
],
},
}
}
#[must_use]
pub fn from_descriptor(descriptor: &TypeDescriptor) -> Option<Self> {
let mut atoms = Vec::new();
push_descriptor_atoms(descriptor, &mut atoms)?;
Some(Self { atoms })
}
#[must_use]
pub fn atom_count(&self) -> usize {
self.atoms.len()
}
#[must_use]
pub fn field_slots(&self) -> usize {
self.atoms.iter().map(|a| a.field_slots()).sum()
}
#[must_use]
pub fn binary_len(&self) -> usize {
self.atoms.iter().map(|a| a.binary_len()).sum()
}
#[must_use]
pub fn needs_chunk_reordering(&self) -> bool {
self.atoms.iter().any(|a| a.is_multi_chunk_bytes())
}
#[must_use]
pub fn reorder_field_slots<T: Clone>(
&self,
slots: &[T],
from: ChunkOrder,
to: ChunkOrder,
) -> Option<Vec<T>> {
if slots.len() != self.field_slots() {
return None;
}
if from == to || !self.needs_chunk_reordering() {
return Some(slots.to_vec());
}
let mut out = Vec::with_capacity(slots.len());
let mut offset = 0;
for atom in &self.atoms {
let n = atom.field_slots();
let slice = &slots[offset..offset + n];
if atom.is_multi_chunk_bytes() {
out.extend(slice.iter().rev().cloned());
} else {
out.extend_from_slice(slice);
}
offset += n;
}
Some(out)
}
}
fn push_foreign_split(split: ForeignFieldSplit, out: &mut Vec<AtomLayout>) {
out.push(AtomLayout::Bytes {
length: split.low_bytes,
});
out.push(AtomLayout::Bytes {
length: split.high_bytes,
});
}
fn push_descriptor_atoms(descriptor: &TypeDescriptor, out: &mut Vec<AtomLayout>) -> Option<()> {
match descriptor {
TypeDescriptor::Boolean | TypeDescriptor::Enum { .. } => {
out.push(AtomLayout::Bytes { length: 1 });
}
TypeDescriptor::Field | TypeDescriptor::JubjubScalar => {
out.push(AtomLayout::Field);
}
TypeDescriptor::Secp256k1Base
| TypeDescriptor::Secp256k1Scalar
| TypeDescriptor::Secp256r1Base
| TypeDescriptor::Secp256r1Scalar
| TypeDescriptor::Curve25519Base => {
push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
}
TypeDescriptor::Curve25519Scalar => {
push_foreign_split(ForeignFieldSplit::SPLIT_204, out);
}
TypeDescriptor::JubjubPoint => {
out.push(AtomLayout::Field);
out.push(AtomLayout::Field);
}
TypeDescriptor::Secp256k1Point | TypeDescriptor::Secp256r1Point => {
push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
out.push(AtomLayout::Field);
}
TypeDescriptor::Curve25519Point => {
push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
push_foreign_split(ForeignFieldSplit::SPLIT_192, out);
}
TypeDescriptor::Uint {
maxval,
alignment_bytes,
} => {
let length = uint_byte_width(maxval, *alignment_bytes)?;
out.push(AtomLayout::Bytes { length });
}
TypeDescriptor::Bytes { length } => {
out.push(AtomLayout::Bytes { length: *length });
}
TypeDescriptor::Counter => {
out.push(AtomLayout::Bytes { length: 8 });
}
TypeDescriptor::Opaque { ts_type } => {
if ts_type == "JubjubPoint" {
out.push(AtomLayout::Field);
out.push(AtomLayout::Field);
} else {
out.push(AtomLayout::Compress);
}
}
TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => {
push_descriptor_atoms(of, out)?;
}
TypeDescriptor::Contract { .. } => {
out.push(AtomLayout::Bytes { length: 32 });
}
TypeDescriptor::Tuple { types } => {
for ty in types {
push_descriptor_atoms(ty, out)?;
}
}
TypeDescriptor::Vector { length, elt_type } => {
if *length == 0 {
return Some(());
}
let mut elem_atoms = Vec::new();
push_descriptor_atoms(elt_type, &mut elem_atoms)?;
let count = usize::try_from(*length).ok()?;
out.reserve(elem_atoms.len().checked_mul(count)?);
for _ in 0..count {
out.extend_from_slice(&elem_atoms);
}
}
TypeDescriptor::Struct { elements, .. } => {
for field in elements {
push_descriptor_atoms(&field.field_type, out)?;
}
}
TypeDescriptor::Map { .. }
| TypeDescriptor::Set { .. }
| TypeDescriptor::List { .. }
| TypeDescriptor::MerkleTree { .. }
| TypeDescriptor::HistoricMerkleTree { .. }
| TypeDescriptor::Unknown => return None,
}
Some(())
}
#[must_use]
pub fn uint_byte_width(maxval: &IntLit, alignment_bytes: Option<u32>) -> Option<u32> {
if maxval.0 < I256::ZERO {
return None;
}
if let Some(explicit) = alignment_bytes
&& explicit > 0
{
return Some(explicit);
}
if let Some(max) = maxval.as_u128() {
let width = if max <= u128::from(u8::MAX) {
1
} else if max <= u128::from(u16::MAX) {
2
} else if max <= u128::from(u32::MAX) {
4
} else if max <= u128::from(u64::MAX) {
8
} else {
16
};
return Some(width);
}
let bits = 256u32.saturating_sub(maxval.0.leading_zeros());
Some(bits.div_ceil(8).max(1))
}
#[must_use]
pub const fn bytes_field_slots(byte_len: u32) -> usize {
byte_len.div_ceil(FR_BYTES_STORED) as usize
}
#[must_use]
pub fn bytes_to_field_chunks(bytes: &[u8], order: ChunkOrder) -> Vec<[u8; 32]> {
let chunk_size = FR_BYTES_STORED as usize;
let mut chunks: Vec<[u8; 32]> = bytes
.chunks(chunk_size)
.map(|slice| {
let mut limb = [0u8; 32];
limb[..slice.len()].copy_from_slice(slice);
limb
})
.collect();
if order == ChunkOrder::MsbFirst {
chunks.reverse();
}
chunks
}
#[must_use]
pub fn field_chunks_to_bytes(
chunks: &[[u8; 32]],
byte_len: u32,
order: ChunkOrder,
) -> Option<Vec<u8>> {
let expected = bytes_field_slots(byte_len);
if chunks.len() != expected {
return None;
}
let total = byte_len as usize;
if total == 0 {
return Some(Vec::new());
}
let chunk_size = FR_BYTES_STORED as usize;
let mut out = vec![0u8; total];
for lsb_idx in 0..expected {
let src_idx = match order {
ChunkOrder::LsbFirst => lsb_idx,
ChunkOrder::MsbFirst => expected - 1 - lsb_idx,
};
let start = lsb_idx * chunk_size;
let width = (total - start).min(chunk_size);
let limb = &chunks[src_idx];
if limb[width..].iter().any(|&b| b != 0) {
return None;
}
out[start..start + width].copy_from_slice(&limb[..width]);
}
Some(out)
}
#[must_use]
pub fn reorder_chunks<T: Clone>(chunks: &[T], from: ChunkOrder, to: ChunkOrder) -> Vec<T> {
if from == to {
chunks.to_vec()
} else {
chunks.iter().rev().cloned().collect()
}
}
#[must_use]
pub const fn foreign_field_modulus(field_type: FieldType) -> Option<U256> {
match field_type {
FieldType::Field => None,
FieldType::JubjubScalar => Some(JUBJUB_SCALAR_MODULUS),
FieldType::Secp256k1Base => Some(SECP256K1_BASE_MODULUS),
FieldType::Secp256k1Scalar => Some(SECP256K1_SCALAR_MODULUS),
FieldType::Secp256r1Base => Some(SECP256R1_BASE_MODULUS),
FieldType::Secp256r1Scalar => Some(SECP256R1_SCALAR_MODULUS),
FieldType::Curve25519Base => Some(CURVE25519_BASE_MODULUS),
FieldType::Curve25519Scalar => Some(CURVE25519_SCALAR_MODULUS),
}
}
#[must_use]
pub const fn foreign_field_split(field_type: FieldType) -> Option<ForeignFieldSplit> {
match field_type {
FieldType::Field | FieldType::JubjubScalar => None,
FieldType::Curve25519Scalar => Some(ForeignFieldSplit::SPLIT_204),
FieldType::Secp256k1Base
| FieldType::Secp256k1Scalar
| FieldType::Secp256r1Base
| FieldType::Secp256r1Scalar
| FieldType::Curve25519Base => Some(ForeignFieldSplit::SPLIT_192),
}
}
#[must_use]
pub fn rotate_foreign_to_wire(field_type: FieldType, value: U256) -> Option<U256> {
foreign_field_split(field_type)?;
let modulus = foreign_field_modulus(field_type)?;
if value >= modulus {
return None;
}
let max = modulus - U256::ONE;
Some(if value == U256::ZERO {
max
} else {
value - U256::ONE
})
}
#[must_use]
pub fn rotate_foreign_from_wire(field_type: FieldType, wire: U256) -> Option<U256> {
foreign_field_split(field_type)?;
let modulus = foreign_field_modulus(field_type)?;
if wire >= modulus {
return None;
}
let max = modulus - U256::ONE;
Some(if wire == max {
U256::ZERO
} else {
wire + U256::ONE
})
}
#[must_use]
pub fn split_foreign_limbs(field_type: FieldType, value: U256) -> Option<(Vec<u8>, Vec<u8>)> {
let split = foreign_field_split(field_type)?;
let rotated = rotate_foreign_to_wire(field_type, value)?;
let low_mask = (U256::ONE << split.low_bits) - U256::ONE;
let low = rotated & low_mask;
let high = rotated >> split.low_bits;
let low_le = low.to_le_bytes()[..split.low_bytes as usize].to_vec();
let high_le = high.to_le_bytes()[..split.high_bytes as usize].to_vec();
Some((low_le, high_le))
}
#[must_use]
pub fn join_foreign_limbs(field_type: FieldType, low_le: &[u8], high_le: &[u8]) -> Option<U256> {
let split = foreign_field_split(field_type)?;
if low_le.len() > split.low_bytes as usize || high_le.len() > split.high_bytes as usize {
return None;
}
let mut low_buf = [0u8; 32];
low_buf[..low_le.len()].copy_from_slice(low_le);
let low = U256::from_le_bytes(low_buf);
if low >= (U256::ONE << split.low_bits) {
return None;
}
let mut high_buf = [0u8; 32];
high_buf[..high_le.len()].copy_from_slice(high_le);
let high = U256::from_le_bytes(high_buf);
if high >= (U256::ONE << (256 - split.low_bits)) {
return None;
}
let wire = (high << split.low_bits) | low;
rotate_foreign_from_wire(field_type, wire)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ir::StructField;
#[test]
fn bytes_chunking_msb_vs_lsb_32_bytes() {
let mut raw = [0u8; 32];
for (i, b) in raw.iter_mut().enumerate() {
#[allow(clippy::cast_possible_truncation)]
{
*b = (i as u8) + 1;
}
}
let fab = bytes_to_field_chunks(&raw, ChunkOrder::MsbFirst);
let zkir = bytes_to_field_chunks(&raw, ChunkOrder::LsbFirst);
assert_eq!(fab.len(), 2);
assert_eq!(zkir.len(), 2);
assert_eq!(fab[0][0], 32);
assert!(fab[0][1..].iter().all(|&b| b == 0));
assert_eq!(&fab[1][..31], &raw[..31]);
assert_eq!(fab[1][31], 0);
assert_eq!(zkir[0], fab[1]);
assert_eq!(zkir[1], fab[0]);
assert_eq!(
reorder_chunks(&fab, ChunkOrder::MsbFirst, ChunkOrder::LsbFirst),
zkir
);
assert_eq!(
field_chunks_to_bytes(&fab, 32, ChunkOrder::MsbFirst).as_deref(),
Some(&raw[..])
);
assert_eq!(
field_chunks_to_bytes(&zkir, 32, ChunkOrder::LsbFirst).as_deref(),
Some(&raw[..])
);
}
#[test]
fn bytes_chunking_edge_lengths() {
assert_eq!(bytes_field_slots(0), 0);
assert_eq!(
bytes_to_field_chunks(&[], ChunkOrder::MsbFirst),
Vec::<[u8; 32]>::new()
);
assert_eq!(
field_chunks_to_bytes(&[], 0, ChunkOrder::LsbFirst),
Some(Vec::new())
);
let b31 = [0x5au8; 31];
let msb31 = bytes_to_field_chunks(&b31, ChunkOrder::MsbFirst);
let lsb31 = bytes_to_field_chunks(&b31, ChunkOrder::LsbFirst);
assert_eq!(msb31.len(), 1);
assert_eq!(msb31, lsb31);
assert_eq!(
field_chunks_to_bytes(&msb31, 31, ChunkOrder::MsbFirst).as_deref(),
Some(&b31[..])
);
let b64: Vec<u8> = (0u8..64).collect();
let msb64 = bytes_to_field_chunks(&b64, ChunkOrder::MsbFirst);
let lsb64 = bytes_to_field_chunks(&b64, ChunkOrder::LsbFirst);
assert_eq!(msb64.len(), 3);
assert_eq!(&msb64[0][..2], &[62, 63]);
assert!(msb64[0][2..].iter().all(|&b| b == 0));
assert_eq!(&msb64[1][..31], &b64[31..62]);
assert_eq!(&msb64[2][..31], &b64[0..31]);
assert_eq!(
field_chunks_to_bytes(&msb64, 64, ChunkOrder::MsbFirst),
Some(b64.clone())
);
assert_eq!(
field_chunks_to_bytes(&lsb64, 64, ChunkOrder::LsbFirst),
Some(b64)
);
let mut bad = msb64;
bad[0][2] = 1;
assert_eq!(field_chunks_to_bytes(&bad, 64, ChunkOrder::MsbFirst), None);
}
#[test]
fn uint_byte_widths_match_runtime_convention() {
assert_eq!(uint_byte_width(&IntLit::from_u128(0), None), Some(1));
assert_eq!(uint_byte_width(&IntLit::from_u128(255), None), Some(1));
assert_eq!(uint_byte_width(&IntLit::from_u128(256), None), Some(2));
assert_eq!(
uint_byte_width(&IntLit::from_u128(u128::from(u16::MAX)), None),
Some(2)
);
assert_eq!(
uint_byte_width(&IntLit::from_u128(u128::from(u32::MAX)), None),
Some(4)
);
assert_eq!(
uint_byte_width(&IntLit::from_u128(u128::from(u64::MAX)), None),
Some(8)
);
assert_eq!(
uint_byte_width(&IntLit::from_u128(u128::MAX), None),
Some(16)
);
assert_eq!(
uint_byte_width(&IntLit::from_u128(16_777_215), Some(3)),
Some(3)
);
assert_eq!(uint_byte_width(&IntLit::from_i128(-1), None), None);
}
#[test]
fn foreign_field_rotation_and_limb_splits() {
for ft in [
FieldType::Secp256k1Base,
FieldType::Secp256k1Scalar,
FieldType::Secp256r1Base,
FieldType::Secp256r1Scalar,
FieldType::Curve25519Base,
FieldType::Curve25519Scalar,
] {
let modulus = foreign_field_modulus(ft).unwrap();
let split = foreign_field_split(ft).unwrap();
if ft == FieldType::Curve25519Scalar {
assert_eq!((split.low_bytes, split.high_bytes), (26, 7));
} else {
assert_eq!((split.low_bytes, split.high_bytes), (24, 8));
}
assert_eq!(rotate_foreign_to_wire(ft, U256::ZERO), Some(modulus - 1));
assert_eq!(rotate_foreign_from_wire(ft, modulus - 1), Some(U256::ZERO));
for val in [U256::ZERO, U256::ONE, U256::from(42u64), modulus - 1] {
let (lo, hi) = split_foreign_limbs(ft, val).unwrap();
assert_eq!(lo.len(), split.low_bytes as usize);
assert_eq!(hi.len(), split.high_bytes as usize);
assert_eq!(join_foreign_limbs(ft, &lo, &hi), Some(val));
}
assert_eq!(rotate_foreign_to_wire(ft, modulus), None);
}
assert_eq!(foreign_field_split(FieldType::Field), None);
assert_eq!(foreign_field_split(FieldType::JubjubScalar), None);
}
#[test]
fn curve_point_and_compound_field_layouts() {
let jj = FieldLayout::from_descriptor(&TypeDescriptor::JubjubPoint).unwrap();
assert_eq!(jj.atom_count(), 2);
assert_eq!(jj.field_slots(), 2);
assert!(!jj.needs_chunk_reordering());
let secp = FieldLayout::from_descriptor(&TypeDescriptor::Secp256k1Point).unwrap();
assert_eq!(secp.atom_count(), 5);
assert_eq!(secp.field_slots(), 5);
assert_eq!(
secp.atoms,
vec![
AtomLayout::Bytes { length: 24 },
AtomLayout::Bytes { length: 8 },
AtomLayout::Bytes { length: 24 },
AtomLayout::Bytes { length: 8 },
AtomLayout::Field,
]
);
assert!(!secp.needs_chunk_reordering());
let p256 = FieldLayout::from_descriptor(&TypeDescriptor::Secp256r1Point).unwrap();
assert_eq!(p256, secp);
let c25519 = FieldLayout::from_descriptor(&TypeDescriptor::Curve25519Point).unwrap();
assert_eq!(c25519.atom_count(), 4);
assert_eq!(c25519.field_slots(), 4);
let note = TypeDescriptor::Struct {
name: "Note".to_owned(),
elements: vec![
StructField {
name: "owner".to_owned(),
field_type: TypeDescriptor::Bytes { length: 32 },
},
StructField {
name: "amount".to_owned(),
field_type: TypeDescriptor::Uint {
maxval: IntLit::from_u128(u128::from(u64::MAX)),
alignment_bytes: None,
},
},
StructField {
name: "pk".to_owned(),
field_type: TypeDescriptor::Secp256k1Base,
},
],
};
let layout = FieldLayout::from_descriptor(¬e).unwrap();
assert_eq!(layout.atom_count(), 4);
assert_eq!(layout.field_slots(), 5);
assert!(layout.needs_chunk_reordering());
let fab_slots = [10u32, 20, 30, 40, 50];
let zkir_slots = layout
.reorder_field_slots(&fab_slots, ChunkOrder::MsbFirst, ChunkOrder::LsbFirst)
.unwrap();
assert_eq!(zkir_slots, vec![20, 10, 30, 40, 50]);
assert_eq!(
layout
.reorder_field_slots(&zkir_slots, ChunkOrder::LsbFirst, ChunkOrder::MsbFirst)
.unwrap(),
fab_slots
);
assert_eq!(
FieldLayout::from_descriptor(&TypeDescriptor::Map {
key: Box::new(TypeDescriptor::Field),
value: Box::new(TypeDescriptor::Counter),
}),
None
);
}
}