use alloc::{vec, vec::Vec};
use core::ops::{Add, Neg};
use openvm_algebra_guest::IntMod;
use super::Group;
pub fn msm<EcPoint: Group, Scalar: IntMod>(coeffs: &[Scalar], bases: &[EcPoint]) -> EcPoint
where
for<'a> &'a EcPoint: Add<&'a EcPoint, Output = EcPoint>,
{
assert_eq!(
coeffs.len(),
bases.len(),
"msm requires matching scalar/base lengths"
);
let coeffs: Vec<_> = coeffs.iter().map(|c| c.as_le_bytes_unchecked()).collect();
let mut acc = EcPoint::IDENTITY;
let c = if bases.len() < 4 {
1
} else if bases.len() < 32 {
3
} else {
bases.len().ilog2() as usize
};
let field_byte_size = Scalar::NUM_LIMBS;
let mut acc_or = vec![0; field_byte_size];
for coeff in &coeffs {
for (acc_limb, limb) in acc_or.iter_mut().zip(coeff.as_ref().iter()) {
*acc_limb |= *limb;
}
}
let max_byte_size = field_byte_size
- acc_or
.iter()
.rev()
.position(|v| *v != 0)
.unwrap_or(field_byte_size);
if max_byte_size == 0 {
return EcPoint::IDENTITY;
}
let number_of_windows = max_byte_size * 8_usize / c + 1;
for current_window in (0..number_of_windows).rev() {
for _ in 0..c {
acc.double_assign();
}
#[derive(Clone)]
enum Bucket<EcPoint: Group> {
None,
Affine(EcPoint),
}
impl<EcPoint: Group> Bucket<EcPoint>
where
for<'a> &'a EcPoint: Add<&'a EcPoint, Output = EcPoint>,
{
fn add_assign(&mut self, other: &EcPoint) {
match self {
Bucket::None => {
*self = Bucket::Affine(other.clone());
}
Bucket::Affine(a) => {
a.add_assign(other);
}
}
}
fn sub_assign(&mut self, other: &EcPoint) {
match self {
Bucket::None => {
*self = Bucket::Affine(other.clone().neg());
}
Bucket::Affine(a) => {
a.sub_assign(other);
}
}
}
fn add(self, mut other: EcPoint) -> EcPoint {
match self {
Bucket::None => other.clone(),
Bucket::Affine(a) => {
other += a;
other
}
}
}
}
let mut buckets: Vec<Bucket<EcPoint>> = vec![Bucket::None; 1 << (c - 1)];
for (coeff, base) in coeffs.iter().zip(bases.iter()) {
let coeff = get_booth_index(current_window, c, coeff);
if coeff.is_positive() {
buckets[coeff as usize - 1].add_assign(base);
}
if coeff.is_negative() {
buckets[coeff.unsigned_abs() as usize - 1].sub_assign(base);
}
}
let mut running_sum = EcPoint::IDENTITY;
for exp in buckets.into_iter().rev() {
running_sum = exp.add(running_sum);
acc = acc.add(&running_sum);
}
}
acc
}
fn get_booth_index(window_index: usize, window_size: usize, el: &[u8]) -> i32 {
let skip_bits = (window_index * window_size).saturating_sub(1);
let skip_bytes = skip_bits / 8;
let mut v: [u8; 4] = [0; 4];
for (dst, src) in v.iter_mut().zip(el.iter().skip(skip_bytes)) {
*dst = *src
}
let mut tmp = u32::from_le_bytes(v);
if window_index == 0 {
tmp <<= 1;
}
tmp >>= skip_bits - (skip_bytes * 8);
tmp &= (1 << (window_size + 1)) - 1;
let sign = tmp & (1 << window_size) == 0;
tmp = (tmp + 1) >> 1;
if sign {
tmp as i32
} else {
((!(tmp - 1) & ((1 << window_size) - 1)) as i32).neg()
}
}