simd_msm.rs

cdk-rsx/crates/crypto/batch/src/simd_msm.rs

simd_msm.rs1,580 lines← SDK documentation
1//! Public-input four-lane SIMD128 Pippenger experiment. It uses the exact2//! standard BIP340 transcript and full-field weights. Four distinct occupied3//! bucket updates share point/field operations; a bounded descriptor queue4//! defers public collisions. Bucket sums retain four exact digit-weight streams.5//! Native execution is a checked four-lane model, not a Wasm performance result.67use crate::{AffinePoint, Coefficients, Error, Item, Scalar, msm, schnorr_hints};8pub use k256::{PublicField4, PublicSimdAffine};9#[cfg(not(feature = "wasm-msm-xyzz"))]10pub use k256::{PublicSimdPoint, PublicSimdPoint4};11#[cfg(feature = "wasm-msm-xyzz")]12pub use k256::{PublicXyzzPoint as PublicSimdPoint, PublicXyzzPoint4 as PublicSimdPoint4};13use msm::{EncodedScalar, Term, Window};1415/// Explicit experimental MSM configuration, separate from scalar defaults.16#[derive(Clone, Copy)]17pub struct Config {18    pub window: Window,19    pub glv: bool,20}21impl Config {22    pub const fn encodings(self, terms: usize) -> usize {23        if self.glv {24            terms.saturating_mul(2)25        } else {26            terms27        }28    }29    pub const fn buckets(self) -> usize {30        1 << (self.window.bits() - 1)31    }32}3334/// All temporary storage is supplied by the caller. Affine conversions and GLV35/// images are refreshed inside each call; no prior-call point table is used.36pub struct Workspace<'a> {37    pub encodings: &'a mut [EncodedScalar],38    pub affine: &'a mut [PublicSimdAffine],39    pub buckets: &'a mut [PublicSimdPoint],40}41impl Workspace<'_> {42    pub fn supports(&self, terms: usize, config: Config) -> bool {43        terms <= msm::MAX_TERMS44            && self.encodings.len() >= config.encodings(terms)45            && self.affine.len() >= config.encodings(terms)46            && self.buckets.len() >= config.buckets()47    }48}4950/// Complete standard signature preparation plus SIMD scratch.51pub struct BatchWorkspace<'a> {52    pub terms: &'a mut [Term],53    pub msm: Workspace<'a>,54}5556/// Diagnostic scheduling counts. Every group still performs exact arithmetic;57/// these are not timing, IC gas, logical-signature or page measurements.58#[derive(Clone, Copy, Default, Debug)]59pub struct Stats {60    pub prepared_affines: usize,61    pub groups: usize,62    pub first_assignments: usize,63    pub vector_mixed_calls: usize,64    pub mixed_lanes: usize,65    pub collision_flushes: usize,66    pub bucket_blocks: usize,67    pub sharded_top_groups: usize,68    pub affine_z1_calls: usize,69    pub affine_z1_lanes: usize,70}7172fn prepare_terms(terms: &[Term], scratch: &mut Workspace<'_>, config: Config, bits: usize) {73    for first in (0..terms.len()).step_by(4) {74        let points = core::array::from_fn(|lane| {75            terms76                .get(first + lane)77                .map(|term| PublicSimdAffine::from_affine(&term.point))78                .unwrap_or(PublicSimdAffine::IDENTITY)79        });80        let images = if config.glv {81            PublicSimdAffine::endomorphism4(&points)82        } else {83            [PublicSimdAffine::IDENTITY; 4]84        };85        for lane in 0..4 {86            let i = first + lane;87            let Some(term) = terms.get(i) else {88                break;89            };90            if config.glv {91                scratch.affine[2 * i] = points[lane];92                scratch.affine[2 * i + 1] = images[lane];93                for (j, (magnitude, negative)) in crate::public_scalar::split(&term.scalar)94                    .into_iter()95                    .enumerate()96                {97                    let bytes = &mut scratch.encodings[2 * i + j];98                    bytes[0] = 0;99                    bytes[1..17].fill(0);100                    bytes[17..].copy_from_slice(&magnitude);101                    msm::recenter(bytes, usize::from(config.window.bits()), 129);102                    bytes[0] = u8::from(negative);103                }104            } else {105                scratch.affine[i] = points[lane];106                let bytes = &mut scratch.encodings[i];107                bytes[0] = 0;108                bytes[1..].copy_from_slice(&term.scalar.to_bytes());109                msm::recenter(bytes, usize::from(config.window.bits()), bits);110            }111        }112    }113}114115/// Store one centered digit per byte when a bounded schedule fits the existing116/// encoding slot. The two leading zero bits supplied by the bounded API consume117/// every carry. Each signed digit is in [-128,127], including W8's -128 edge.118fn recode_byte_digits(bytes: &[u8; 32], output: &mut EncodedScalar, width: usize, groups: usize) {119    let mask = (1usize << width) - 1;120    let mut carry = 0;121    for (group, digit) in output[..groups].iter_mut().enumerate() {122        let offset = group * width;123        let source = offset / 8;124        let mut raw = if source < 32 {125            usize::from(bytes[31 - source])126        } else {127            0128        };129        if source + 1 < 32 {130            raw |= usize::from(bytes[30 - source]) << 8;131        }132        let value = ((raw >> (offset % 8)) & mask) + carry;133        carry = usize::from(value >= 1 << (width - 1));134        *digit = (value as i16 - (carry << width) as i16) as u8;135    }136    debug_assert_eq!(carry, 0);137}138139fn prepare_byte_digits(terms: &[Term], scratch: &mut Workspace<'_>, width: usize, groups: usize) {140    for (i, term) in terms.iter().enumerate() {141        scratch.affine[i] = PublicSimdAffine::from_affine(&term.point);142        recode_byte_digits(143            &term.scalar.to_bytes().into(),144            &mut scratch.encodings[i],145            width,146            groups,147        );148    }149}150151#[inline(always)]152fn signed_digit<const BYTE_DIGITS: bool>(153    bytes: &EncodedScalar,154    group: usize,155    width: usize,156) -> (usize, bool) {157    if BYTE_DIGITS {158        let digit = bytes[group] as i8;159        (usize::from(digit.unsigned_abs()), digit < 0)160    } else {161        let digit = msm::digit(bytes, group * width, width);162        let negative = digit & (1 << (width - 1)) != 0;163        (164            if negative {165                (1 << width) - digit166            } else {167                digit168            },169            negative,170        )171    }172}173174fn flush(175    scratch: &mut Workspace<'_>,176    indices: &[usize; 4],177    inputs: &[usize; 4],178    negative: u8,179    count: usize,180    affine_z1: bool,181    stats: &mut Stats,182) {183    if count == 0 {184        return;185    }186    let before = PublicSimdPoint4::gather_indexed(scratch.buckets, indices, count);187    let after = if affine_z1 {188        stats.affine_z1_calls += 1;189        stats.affine_z1_lanes += count;190        before.add_affine_z1_indexed(scratch.affine, inputs, count, negative)191    } else {192        before.add_affine_indexed(scratch.affine, inputs, count, negative)193    };194    after.scatter_indexed(scratch.buckets, indices, count);195    stats.vector_mixed_calls += 1;196    stats.mixed_lanes += count;197}198199/// Select at most four distinct bucket targets from sixteen public updates.200/// A descriptor packs the affine-slot index above bit7, the bucket index in201/// bits1..7 and its sign in bit0. MAX_TERMS*2 fits the remaining u32 bits.202/// Only descriptors are buffered; checked affine coordinates stay in scratch.203#[cfg(test)]204fn flush_deferred<const AFFINITY: bool>(205    scratch: &mut Workspace<'_>,206    queue: &mut [u32; 16],207    queued: &mut usize,208    affine: &mut [u64; 2],209    stats: &mut Stats,210) {211    let before = *queued;212    if before == 0 {213        return;214    }215    let eligible = |index: usize| {216        let known = affine[index / 64] & (1u64 << (index % 64)) != 0;217        #[cfg(test)]218        if known {219            let point = &scratch.buckets[index];220            assert!(point.is_identity() || point.is_affine_z1());221        }222        known223    };224    let preferred = AFFINITY && eligible((queue[0] as usize >> 1) & 127);225    let mut affine_z1 = preferred;226    let mut indices = [0; 4];227    let mut inputs = [0; 4];228    let mut negative = 0;229    let mut count = 0;230    // Prefer a uniform group of the queue-front target's eligibility hints.231    // Fill any short group in a second pass, preserving SIMD lane occupancy.232    // A hint is set only by first affine assignment and cleared by any update.233    // It never bypasses the checked unit-Z leaf, and later queued updates cannot234    // reuse a preceding update's hint. Rare later unit/identity values use the235    // generic formula instead of paying to inspect every bucket's field limbs.236    for pass in 0..if AFFINITY { 2 } else { 1 } {237        let mut cursor = 0;238        while cursor < *queued && count < 4 {239            let entry = queue[cursor];240            let index = (entry as usize >> 1) & 127;241            if indices[..count].contains(&index)242                || AFFINITY && pass == 0 && eligible(index) != preferred243            {244                cursor += 1;245                continue;246            }247            *queued -= 1;248            queue[cursor] = queue[*queued];249            indices[count] = index;250            inputs[count] = entry as usize >> 8;251            negative |= ((entry & 1) as u8) << count;252            count += 1;253            if pass != 0 {254                affine_z1 = false;255            }256        }257    }258    flush(259        scratch, &indices, &inputs, negative, count, affine_z1, stats,260    );261    if AFFINITY {262        for index in &indices[..count] {263            affine[*index / 64] &= !(1u64 << (*index % 64));264        }265    }266    stats.collision_flushes += usize::from(count < 4 && before > count);267}268269/// Preserve the four digit-residue streams through the window recurrence.270/// Lane r contains 4*S_r-(4-r)*R_r, r=1..4. Their sum is the exact window271/// contribution, and a common Horner doubling commutes with the final sum.272/// Keeping the streams independent avoids a horizontal point reduction in273/// every window; no scalar, point, digit or transcript term is omitted.274fn weighted_bucket_streams(275    sums: &PublicSimdPoint4,276    running: &PublicSimdPoint4,277) -> PublicSimdPoint4 {278    let (doubled, tripled) = running.double_and_triple();279    let mut correction = PublicSimdPoint4::select(running, &doubled, 2);280    correction = PublicSimdPoint4::select(&correction, &tripled, 1);281    correction = PublicSimdPoint4::select(&correction, &PublicSimdPoint4::identity(), 8);282    sums.double().double().add(&correction.negate())283}284285/// Compute an exact public MSM. No coefficients, hashes, decoding, sampling or286/// signature semantics are introduced here; callers supply all typed terms.287pub fn weighted_msm_vartime(288    terms: &[Term],289    scratch: &mut Workspace<'_>,290    config: Config,291) -> Result<PublicSimdPoint, msm::Error> {292    weighted_msm_with_stats_vartime(terms, scratch, config).map(|(point, _)| point)293}294295pub fn weighted_msm_with_stats_vartime(296    terms: &[Term],297    scratch: &mut Workspace<'_>,298    config: Config,299) -> Result<(PublicSimdPoint, Stats), msm::Error> {300    // Compare public encoded-term density, including the GLV expansion and301    // generator term. Above eight inputs per bucket, first affine updates are302    // a small fraction of work. Select once so the dense kernel has no303    // coordinate classification or policy branch inside its loops.304    let bits = if config.glv { 129 } else { 257 };305    if config.encodings(terms.len()) <= 8 * config.buckets() {306        weighted_msm_bucket_chains::<true, false, false>(terms, scratch, config, bits)307    } else {308        weighted_msm_bucket_chains::<false, false, false>(terms, scratch, config, bits)309    }310}311312/// Compute an exact public MSM with nonnegative integer scalars below313/// `2^scalar_bits`. The width is checked against every canonical scalar before314/// any recoding; high bits are never truncated. Width zero admits only zero.315/// Negative contributions must use a negated point with a positive scalar,316/// rather than the full-width residue `n-r`. This path performs no GLV split.317pub fn weighted_msm_bounded_vartime(318    terms: &[Term],319    scratch: &mut Workspace<'_>,320    window: Window,321    scalar_bits: usize,322) -> Result<PublicSimdPoint, msm::Error> {323    weighted_msm_bounded_with_stats_vartime(terms, scratch, window, scalar_bits)324        .map(|(point, _)| point)325}326327pub fn weighted_msm_bounded_with_stats_vartime(328    terms: &[Term],329    scratch: &mut Workspace<'_>,330    window: Window,331    scalar_bits: usize,332) -> Result<(PublicSimdPoint, Stats), msm::Error> {333    if scalar_bits > 256 {334        return Err(msm::Error::ScalarBits);335    }336    let config = Config { window, glv: false };337    if !scratch.supports(terms.len(), config) {338        return Err(msm::Error::Capacity);339    }340    // Scalar is a canonical field element, but a narrower schedule still needs341    // an explicit integer bound. Include partial bytes as well as whole bytes.342    let unused = 256 - scalar_bits;343    let whole = unused / 8;344    let partial = unused % 8;345    for term in terms {346        let bytes = term.scalar.to_bytes();347        if bytes[..whole].iter().any(|byte| *byte != 0)348            || partial != 0 && bytes[whole] >> (8 - partial) != 0349        {350            return Err(msm::Error::ScalarRange);351        }352    }353    // At least two leading zero bits keep the final signed digit nonnegative354    // even when the preceding digit carries. One leading zero is insufficient355    // if a window ends there: e.g. 127 at W4 otherwise becomes [-1,-8] with an356    // unconsumed carry. Rounding this width to windows adds a group only when357    // (scalar_bits+1) is exactly divisible by the window width.358    let bits = scalar_bits + 2;359    // The certificate's bounded W6/W7 schedules fit one signed digit per byte.360    // Select the encoding once; neither bucket scan carries a format branch.361    // Narrow windows retain the packed representation when more digits need to362    // fit, and standard/full-width GLV calls always retain their original path.363    let byte_digits = bits.div_ceil(usize::from(window.bits())) <= msm::ENCODING_BYTES;364    match (terms.len() <= 8 * config.buckets(), byte_digits) {365        (true, true) => {366            weighted_msm_bucket_chains::<true, true, true>(terms, scratch, config, bits)367        }368        (false, true) => {369            weighted_msm_bucket_chains::<false, true, true>(terms, scratch, config, bits)370        }371        (true, false) => {372            weighted_msm_bucket_chains::<true, true, false>(terms, scratch, config, bits)373        }374        (false, false) => {375            weighted_msm_bucket_chains::<false, true, false>(terms, scratch, config, bits)376        }377    }378}379380// Each descriptor is (affine index << 1) | sign. 2002 GLV slots fit in381// u16 without using the sentinel; links always point to an earlier input.382const NO_LINK: u16 = u16::MAX;383const _: () = assert!(8 * msm::MAX_TERMS < u16::MAX as usize);384385fn longest_chain_order<const HEADS: usize, const LINKS: usize>(386    heads: &[u16; HEADS],387    links: &[u16; LINKS],388    highest: usize,389    order: &mut [u32; HEADS],390) -> usize {391    const {392        assert!(HEADS <= u16::MAX as usize && LINKS <= u16::MAX as usize);393    }394    let mut used = 0;395    for (bucket, head) in heads[..highest].iter().enumerate() {396        let mut entry = *head;397        let mut length = 0u32;398        while entry != NO_LINK {399            length += 1;400            entry = links[usize::from(entry >> 1)];401        }402        if length != 0 {403            // Private head/link capacities fit u16. Sorting packed keys avoids404            // point reads or comparator lookups into the chain graph.405            order[used] = (length << 16) | bucket as u32;406            used += 1;407        }408    }409    order[..used].sort_unstable();410    used411}412413fn accumulate_chains<414    const AFFINITY: bool,415    const LONGEST: bool,416    const HEADS: usize,417    const LINKS: usize,418>(419    scratch: &mut Workspace<'_>,420    heads: &mut [u16; HEADS],421    links: &[u16; LINKS],422    highest: usize,423    stats: &mut Stats,424) {425    if AFFINITY {426        // Before any update every occupied bucket is an affine first assignment.427        // Pop one update per distinct bucket, using the checked unit-Z leaf.428        let mut indices = [0; 4];429        let mut inputs = [0; 4];430        let mut negative = 0;431        let mut count = 0;432        for bucket in 0..highest {433            let entry = heads[bucket];434            if entry == NO_LINK {435                continue;436            }437            let input = usize::from(entry >> 1);438            heads[bucket] = links[input];439            indices[count] = bucket;440            inputs[count] = input;441            negative |= ((entry & 1) as u8) << count;442            count += 1;443            if count == 4 {444                flush(scratch, &indices, &inputs, negative, count, true, stats);445                count = 0;446                negative = 0;447            }448        }449        flush(scratch, &indices, &inputs, negative, count, true, stats);450    }451452    // Only the bounded MSM selects this candidate. The affine-first pass has453    // already removed its cheap second assignments, so order the actual454    // remaining work. Descending lengths reduce the final underfilled rounds.455    // Default/full-width and four-column controls keep their original order.456    let mut order = [0u32; HEADS];457    let ordered = if LONGEST {458        longest_chain_order(heads, links, highest, &mut order)459    } else {460        0461    };462463    let mut point = PublicSimdPoint4::identity();464    let mut buckets = [0; 4];465    let mut inputs = [0; 4];466    let mut active = 0u8;467    let mut next = 0;468    loop {469        let mut refill = 0u8;470        for lane in 0..4 {471            if active & (1 << lane) != 0 {472                continue;473            }474            let bucket = if LONGEST {475                if next == ordered {476                    continue;477                }478                (order[ordered - next - 1] & 0xffff) as usize479            } else {480                while next < highest && heads[next] == NO_LINK {481                    next += 1;482                }483                if next == highest {484                    continue;485                }486                next487            };488            buckets[lane] = bucket;489            next += 1;490            active |= 1 << lane;491            refill |= 1 << lane;492        }493        if active == 0 {494            break;495        }496        if refill != 0 {497            let new = PublicSimdPoint4::gather_masked(scratch.buckets, &buckets, refill);498            point = if refill == 15 {499                new500            } else {501                PublicSimdPoint4::select(&point, &new, refill)502            };503        }504        let mut negative = 0u8;505        let mut finish = 0u8;506        for lane in 0..4 {507            if active & (1 << lane) == 0 {508                continue;509            }510            let bucket = buckets[lane];511            let entry = heads[bucket];512            let input = usize::from(entry >> 1);513            heads[bucket] = links[input];514            inputs[lane] = input;515            negative |= ((entry & 1) as u8) << lane;516            if heads[bucket] == NO_LINK {517                finish |= 1 << lane;518            }519        }520        #[cfg(feature = "wasm-msm-xyzz")]521        point.add_affine_masked_indexed_assign(scratch.affine, &inputs, active, negative);522        #[cfg(not(feature = "wasm-msm-xyzz"))]523        {524            point = point.add_affine_masked_indexed(scratch.affine, &inputs, active, negative);525        }526        stats.vector_mixed_calls += 1;527        stats.mixed_lanes += active.count_ones() as usize;528        if finish != 0 {529            point.scatter_masked(scratch.buckets, &buckets, finish);530            active &= !finish;531            // Finished lanes retain bounded coordinates. Masked additions532            // preserve them, no later scatter reads an inactive lane, and a533            // refill overwrites the lane before it becomes active again.534        }535    }536}537538fn weighted_msm_bucket_chains<539    const AFFINITY: bool,540    const LONGEST: bool,541    const BYTE_DIGITS: bool,542>(543    terms: &[Term],544    scratch: &mut Workspace<'_>,545    config: Config,546    bits: usize,547) -> Result<(PublicSimdPoint, Stats), msm::Error> {548    if !scratch.supports(terms.len(), config) {549        return Err(msm::Error::Capacity);550    }551    let used = config.encodings(terms.len());552    let width = usize::from(config.window.bits());553    let groups = bits.div_ceil(width);554    if BYTE_DIGITS {555        debug_assert!(!config.glv);556        prepare_byte_digits(terms, scratch, width, groups);557    } else {558        prepare_terms(terms, scratch, config, bits);559    }560    // The declared bound can widen after equal bases are folded even when561    // almost all actual top digits remain tiny. Size the four-way sharding562    // from the exact recoded magnitudes, including signs and final carry,563    // rather than from the unused capacity of the top window.564    let top_maximum = scratch.encodings[..used]565        .iter()566        .map(|bytes| signed_digit::<BYTE_DIGITS>(bytes, groups - 1, width).0)567        .max()568        .unwrap_or(0);569    let top_fits_shards = 4 * top_maximum <= config.buckets();570    // 4004 public stack bytes, initialized once. Each window's fresh heads can571    // reach only links written for that window; no prior-call data is reused.572    let mut links = [NO_LINK; 2 * msm::MAX_TERMS];573    let mut result = PublicSimdPoint4::identity();574    let mut stats = Stats {575        prepared_affines: used,576        ..Stats::default()577    };578    for group in (0..groups).rev() {579        stats.groups += 1;580        for _ in 0..width {581            result = result.double();582        }583        let shard_top = group + 1 == groups && top_fits_shards;584        stats.sharded_top_groups += usize::from(shard_top);585        let mut next_shard = 0;586        let mut occupied = [0u64; 2];587        let mut heads = [NO_LINK; 128];588        let mut highest = 0;589        for i in 0..used {590            let bytes = &scratch.encodings[i];591            let (magnitude, digit_negative) = signed_digit::<BYTE_DIGITS>(bytes, group, width);592            if magnitude == 0 {593                continue;594            }595            let index = if shard_top {596                let index = 4 * (magnitude - 1) + next_shard;597                next_shard = (next_shard + 1) & 3;598                index599            } else {600                magnitude - 1601            };602            let negative = digit_negative ^ (config.glv && bytes[0] != 0);603            let bit = 1u64 << (index % 64);604            if occupied[index / 64] & bit == 0 {605                scratch.buckets[index] = PublicSimdPoint::from_affine(&scratch.affine[i], negative);606                occupied[index / 64] |= bit;607                highest = highest.max(index + 1);608                stats.first_assignments += 1;609            } else {610                links[i] = heads[index];611                heads[index] = ((i as u16) << 1) | u16::from(negative);612            }613        }614        accumulate_chains::<AFFINITY, LONGEST, 128, { 2 * msm::MAX_TERMS }>(615            scratch, &mut heads, &links, highest, &mut stats,616        );617        let mut running = PublicSimdPoint4::identity();618        let mut sums = PublicSimdPoint4::identity();619        for block in (0..highest.div_ceil(4)).rev() {620            let first = block * 4;621            let indices = [first, first + 1, first + 2, first + 3];622            let mask = ((occupied[block / 16] >> (4 * (block % 16))) & 15) as u8;623            let points = PublicSimdPoint4::gather_masked(scratch.buckets, &indices, mask);624            running = running.add(&points);625            sums = sums.add(&running);626            stats.bucket_blocks += 1;627        }628        result = result.add(&if shard_top {629            sums630        } else {631            weighted_bucket_streams(&sums, &running)632        });633    }634    Ok((result.sum_lanes(), stats))635}636637/// Four radix-column MSMs over the same public bases, with an independent638/// bucket bank and result in each lane. Output lane `l < column_count` is639/// `sum_i digit(scalar_i, first_column+l, digit_bits) * point_i`; unused lanes640/// are identities. Unlike the ordinary MSM, these lanes are never summed.641///642/// Requires four encodings and four affine slots per input term, plus four643/// times the ordinary signed-window bucket capacity. Scalar digit extraction644/// is exact integer decomposition, without field reduction. Digit widths are645/// 1..=256 and the selected columns must lie inside the scalar's radix layout.646pub fn weighted_msm_radix4_vartime(647    terms: &[Term],648    scratch: &mut Workspace<'_>,649    window: Window,650    digit_bits: usize,651    first_column: usize,652    column_count: usize,653) -> Result<[PublicSimdPoint; 4], msm::Error> {654    weighted_msm_radix4_with_stats_vartime(655        terms,656        scratch,657        window,658        digit_bits,659        first_column,660        column_count,661    )662    .map(|(points, _)| points)663}664665pub fn weighted_msm_radix4_with_stats_vartime(666    terms: &[Term],667    scratch: &mut Workspace<'_>,668    window: Window,669    digit_bits: usize,670    first_column: usize,671    column_count: usize,672) -> Result<([PublicSimdPoint; 4], Stats), msm::Error> {673    if digit_bits == 0 || digit_bits > 256 {674        return Err(msm::Error::ScalarBits);675    }676    let columns = 256usize.div_ceil(digit_bits);677    if column_count > 4 || first_column > columns || column_count > columns - first_column {678        return Err(msm::Error::ScalarBits);679    }680    let width = usize::from(window.bits());681    let buckets = 1usize << (width - 1);682    if terms.len() > msm::MAX_TERMS683        || scratch.encodings.len() < 4 * terms.len()684        || scratch.affine.len() < 4 * terms.len()685        || scratch.buckets.len() < 4 * buckets686    {687        return Err(msm::Error::Capacity);688    }689    if column_count == 0 {690        return Ok(([PublicSimdPoint::IDENTITY; 4], Stats::default()));691    }692    for (i, term) in terms.iter().enumerate() {693        let affine = PublicSimdAffine::from_affine(&term.point);694        let bytes: [u8; 32] = term.scalar.to_bytes().into();695        for lane in 0..column_count {696            let input = 4 * i + lane;697            scratch.affine[input] = affine;698            scratch.encodings[input] =699                radix_digit(&bytes, (first_column + lane) * digit_bits, digit_bits);700            msm::recenter(&mut scratch.encodings[input], width, digit_bits + 2);701        }702    }703    // The same two leading zero bits as the checked bounded MSM ensure that704    // no carry survives the last centered digit, at every window alignment.705    let bits = digit_bits + 2;706    let groups = bits.div_ceil(width);707    let mut links = [NO_LINK; 4 * msm::MAX_TERMS];708    let mut result = PublicSimdPoint4::identity();709    let mut stats = Stats {710        prepared_affines: terms.len() * column_count,711        ..Stats::default()712    };713    for group in (0..groups).rev() {714        stats.groups += 1;715        for _ in 0..width {716            result = result.double();717        }718        let mut occupied = [0u64; 8];719        let mut heads = [NO_LINK; 512];720        let mut highest = 0;721        for i in 0..terms.len() {722            for lane in 0..column_count {723                let input = 4 * i + lane;724                let digit = msm::digit(&scratch.encodings[input], group * width, width);725                let negative = digit & (1 << (width - 1)) != 0;726                let magnitude = if negative {727                    (1 << width) - digit728                } else {729                    digit730                };731                if magnitude == 0 {732                    continue;733                }734                // Bank l is bucket slots l,4+l,8+l,..., so descending SIMD735                // bucket reduction preserves one exact column in every lane.736                let index = 4 * (magnitude - 1) + lane;737                let bit = 1u64 << (index % 64);738                if occupied[index / 64] & bit == 0 {739                    scratch.buckets[index] =740                        PublicSimdPoint::from_affine(&scratch.affine[input], negative);741                    occupied[index / 64] |= bit;742                    highest = highest.max(index + 1);743                    stats.first_assignments += 1;744                } else {745                    links[input] = heads[index];746                    heads[index] = ((input as u16) << 1) | u16::from(negative);747                }748            }749        }750        if terms.len() <= 8 * buckets {751            accumulate_chains::<true, false, 512, { 4 * msm::MAX_TERMS }>(752                scratch, &mut heads, &links, highest, &mut stats,753            );754        } else {755            accumulate_chains::<false, false, 512, { 4 * msm::MAX_TERMS }>(756                scratch, &mut heads, &links, highest, &mut stats,757            );758        }759        let mut running = PublicSimdPoint4::identity();760        let mut sums = PublicSimdPoint4::identity();761        for block in (0..highest.div_ceil(4)).rev() {762            let first = 4 * block;763            let indices = [first, first + 1, first + 2, first + 3];764            let mask = ((occupied[block / 16] >> (4 * (block % 16))) & 15) as u8;765            let points = PublicSimdPoint4::gather_masked(scratch.buckets, &indices, mask);766            running = running.add(&points);767            sums = sums.add(&running);768            stats.bucket_blocks += 1;769        }770        result = result.add(&sums);771    }772    Ok((result.to_points(), stats))773}774775fn radix_digit(bytes: &[u8; 32], offset: usize, bits: usize) -> EncodedScalar {776    let mut digit = [0; msm::ENCODING_BYTES];777    let available = bits.min(256 - offset);778    for output in 0..available.div_ceil(8) {779        let source = offset / 8 + output;780        let shift = offset % 8;781        let mut value = bytes[31 - source] >> shift;782        if shift != 0 && source < 31 {783            value |= bytes[30 - source] << (8 - shift);784        }785        let live = (available - 8 * output).min(8);786        digit[32 - output] = value & (0xff >> (8 - live));787    }788    digit789}790791#[cfg(test)]792fn weighted_msm_scheduled_vartime<793    const DEFER: bool,794    const SHARD_TOP: bool,795    const AFFINITY: bool,796>(797    terms: &[Term],798    scratch: &mut Workspace<'_>,799    config: Config,800) -> Result<(PublicSimdPoint, Stats), msm::Error> {801    if !scratch.supports(terms.len(), config) {802        return Err(msm::Error::Capacity);803    }804    prepare_terms(terms, scratch, config, if config.glv { 129 } else { 257 });805    let used = config.encodings(terms.len());806    let width = usize::from(config.window.bits());807    let bits = if config.glv { 129usize } else { 257usize };808    let mut result = PublicSimdPoint4::identity();809    let mut stats = Stats {810        prepared_affines: used,811        ..Stats::default()812    };813    let groups = bits.div_ceil(width);814    for group in (0..groups).rev() {815        stats.groups += 1;816        for _ in 0..width {817            result = result.double();818        }819        // The short top digit often occupies only one or two buckets. Give820        // each original bucket four shards when all possible shards fit in821        // the existing backing. Shard r of digit d occupies index4*(d-1)+r;822        // consecutive nonzero inputs cycle through r=0..3. Using the original823        // input index instead would correlate shards with GLV component slots.824        // The interleaved scan then computes sum_d d*B_(d,r) in each lane,825        // requiring no 4*S-(4-r)*R correction for this window. The final sum826        // remains exact, with no extra allocation or input-point operation.827        let remaining = bits - group * width;828        let shard_top =829            SHARD_TOP && group + 1 == groups && 4 * (1usize << remaining) <= config.buckets();830        stats.sharded_top_groups += usize::from(shard_top);831        let mut next_shard = 0;832        let mut occupied = [0u64; 2];833        let mut affine = [0u64; 2];834        let mut highest = 0;835        let mut indices = [0; 4];836        let mut inputs = [0; 4];837        let mut negatives = 0u8;838        let mut pending = 0;839        let mut queue = [0u32; 16];840        let mut queued = 0;841        for i in 0..used {842            let bytes = &scratch.encodings[i];843            let encoded = msm::digit(bytes, group * width, width);844            let digit_negative = encoded & (1 << (width - 1)) != 0;845            let magnitude = if digit_negative {846                (1 << width) - encoded847            } else {848                encoded849            };850            if magnitude == 0 {851                continue;852            }853            let index = if shard_top {854                let index = 4 * (magnitude - 1) + next_shard;855                next_shard = (next_shard + 1) & 3;856                index857            } else {858                magnitude - 1859            };860            let negative = digit_negative ^ (config.glv && bytes[0] != 0);861            let bit = 1u64 << (index % 64);862            if occupied[index / 64] & bit == 0 {863                scratch.buckets[index] = PublicSimdPoint::from_affine(&scratch.affine[i], negative);864                occupied[index / 64] |= bit;865                if AFFINITY {866                    affine[index / 64] |= bit;867                }868                highest = highest.max(index + 1);869                stats.first_assignments += 1;870                continue;871            }872            if DEFER {873                queue[queued] = ((i as u32) << 8) | ((index as u32) << 1) | u32::from(negative);874                queued += 1;875                if queued == queue.len() {876                    flush_deferred::<AFFINITY>(877                        scratch,878                        &mut queue,879                        &mut queued,880                        &mut affine,881                        &mut stats,882                    );883                }884                continue;885            }886            if indices[..pending].contains(&index) {887                flush(888                    scratch, &indices, &inputs, negatives, pending, false, &mut stats,889                );890                pending = 0;891                inputs = [0; 4];892                negatives = 0;893                stats.collision_flushes += 1;894            }895            indices[pending] = index;896            inputs[pending] = i;897            negatives |= u8::from(negative) << pending;898            pending += 1;899            if pending == 4 {900                flush(901                    scratch, &indices, &inputs, negatives, pending, false, &mut stats,902                );903                pending = 0;904                inputs = [0; 4];905                negatives = 0;906            }907        }908        if DEFER {909            while queued != 0 {910                flush_deferred::<AFFINITY>(911                    scratch,912                    &mut queue,913                    &mut queued,914                    &mut affine,915                    &mut stats,916                );917            }918        } else {919            flush(920                scratch, &indices, &inputs, negatives, pending, false, &mut stats,921            );922        }923        let mut running = PublicSimdPoint4::identity();924        let mut sums = PublicSimdPoint4::identity();925        for block in (0..highest.div_ceil(4)).rev() {926            let first = block * 4;927            let indices = [first, first + 1, first + 2, first + 3];928            // Four consecutive buckets fit one occupancy word. Keep holes in929            // their original residue lanes; inactive indices are not read.930            let mask = ((occupied[block / 16] >> (4 * (block % 16))) & 15) as u8;931            let points = PublicSimdPoint4::gather_masked(scratch.buckets, &indices, mask);932            running = running.add(&points);933            sums = sums.add(&running);934            stats.bucket_blocks += 1;935        }936        result = result.add(&if shard_top {937            sums938        } else {939            weighted_bucket_streams(&sums, &running)940        });941    }942    Ok((result.sum_lanes(), stats))943}944945fn aggregate(946    workspace: &mut BatchWorkspace<'_>,947    count: usize,948    seed: &[u8; 32],949    config: Config,950) -> Result<bool, Error> {951    // Same complete-transcript, a1=1, full-field rejection sampling as the952    // qualified scalar batch. Only its typed MSM backend changes.953    let mut coefficients = Coefficients::new(seed);954    let mut generator = Scalar::ZERO;955    for i in 0..count {956        let a = if i == 0 {957            Scalar::ONE958        } else {959            coefficients.next()?960        };961        generator += a * workspace.terms[2 * i].scalar;962        workspace.terms[2 * i].scalar = -a;963        workspace.terms[2 * i + 1].scalar *= -a;964    }965    workspace.terms[2 * count] = Term {966        point: AffinePoint::GENERATOR,967        scalar: generator,968    };969    weighted_msm_vartime(970        &workspace.terms[..2 * count + 1],971        &mut workspace.msm,972        config,973    )974    .map(|point| point.is_identity())975    .map_err(|_| Error::Workspace)976}977978pub fn verify_bip340_batch(979    items: &[Item<'_>],980    workspace: &mut BatchWorkspace<'_>,981    config: Config,982) -> Result<bool, Error> {983    crate::validate_items(items.len(), items.iter().copied())?;984    let count = 2 * items.len() + 1;985    if workspace.terms.len() < count || !workspace.msm.supports(count, config) {986        return Err(Error::Workspace);987    }988    let transcript = crate::hash_transcript_items(items.len(), items.iter().copied());989    let challenge = crate::challenge_prefix();990    for (i, item) in items.iter().enumerate() {991        let p = crate::lift_x(item.public_key.try_into().unwrap()).ok_or(Error::PublicKey(i))?;992        let r =993            crate::lift_x(item.signature[..32].try_into().unwrap()).ok_or(Error::Signature(i))?;994        crate::store_prepared_item(*item, i, p, r, workspace.terms, &challenge)?;995    }996    aggregate(workspace, items.len(), &transcript, config)997}998999pub fn verify_hinted_batch(1000    items: &[schnorr_hints::HintedItem<'_>],1001    workspace: &mut BatchWorkspace<'_>,1002    config: Config,1003) -> Result<bool, schnorr_hints::Error> {1004    crate::validate_items(items.len(), items.iter().map(|i| i.item))1005        .map_err(schnorr_hints::Error::Input)?;1006    let count = 2 * items.len() + 1;1007    if workspace.terms.len() < count || !workspace.msm.supports(count, config) {1008        return Err(schnorr_hints::Error::Input(Error::Workspace));1009    }1010    let transcript = crate::hash_transcript_items(items.len(), items.iter().map(|i| i.item));1011    let challenge = crate::challenge_prefix();1012    for (i, item) in items.iter().enumerate() {1013        let (p, r) =1014            schnorr_hints::points(*item, i, schnorr_hints::HintValidation::DirectField, true)?;1015        crate::store_prepared_item(item.item, i, p, r.unwrap(), workspace.terms, &challenge)1016            .map_err(schnorr_hints::Error::Input)?;1017    }1018    aggregate(workspace, items.len(), &transcript, config).map_err(schnorr_hints::Error::Input)1019}10201021#[cfg(test)]1022mod tests;10231024#[cfg(test)]1025#[path = "simd_msm/byte_digits_tests.rs"]1026mod byte_digits_tests;10271028#[cfg(test)]1029#[path = "simd_msm/adversarial_tests.rs"]1030mod adversarial_tests;10311032#[cfg(test)]1033mod bounded_tests {1034    use super::*;1035    use k256::elliptic_curve::{1036        PrimeField,1037        group::{Group, prime::PrimeCurveAffine},1038    };1039    use k256::{ProjectivePoint, Scalar};1040    use std::{vec, vec::Vec};10411042    fn with_scratch<T>(1043        count: usize,1044        window: Window,1045        columns: bool,1046        run: impl FnOnce(&mut Workspace<'_>) -> T,1047    ) -> T {1048        let factor = if columns { 4 } else { 1 };1049        let mut encodings = vec![[0xff; msm::ENCODING_BYTES]; factor * count];1050        let mut affine = vec![PublicSimdAffine::IDENTITY; factor * count];1051        let mut buckets = vec![PublicSimdPoint::IDENTITY; factor * (1usize << (window.bits() - 1))];1052        run(&mut Workspace {1053            encodings: &mut encodings,1054            affine: &mut affine,1055            buckets: &mut buckets,1056        })1057    }10581059    fn maximal(bits: usize) -> Scalar {1060        if bits == 256 {1061            return -Scalar::ONE;1062        }1063        let mut bytes = [0u8; 32];1064        for bit in 0..bits {1065            bytes[31 - bit / 8] |= 1 << (bit % 8);1066        }1067        Scalar::from_repr(bytes.into()).unwrap()1068    }10691070    fn original_terms(count: usize) -> Vec<Term> {1071        (0..count)1072            .map(|i| {1073                let mut bytes = [0u8; 32];1074                for (j, byte) in bytes.iter_mut().enumerate() {1075                    *byte = (i.wrapping_mul(73) + j * 109 + 17) as u8;1076                }1077                bytes[0] &= 0x7f;1078                let scalar = match i % 7 {1079                    0 => Scalar::ZERO,1080                    1 => -Scalar::ONE,1081                    _ => Scalar::from_repr(bytes.into()).unwrap(),1082                };1083                let point = match i % 5 {1084                    0 => ProjectivePoint::IDENTITY,1085                    1 => ProjectivePoint::GENERATOR,1086                    2 => -ProjectivePoint::GENERATOR,1087                    _ => ProjectivePoint::GENERATOR * Scalar::from((i % 13 + 1) as u64),1088                };1089                Term {1090                    point: point.to_affine(),1091                    scalar,1092                }1093            })1094            .collect()1095    }10961097    fn chain_lifecycle<const AFFINITY: bool, const LONGEST: bool>(form: usize) {1098        let lengths = [0usize, 1, 3, 8, 2, 7, 1, 11];1099        let mut links = [NO_LINK; 64];1100        let mut heads = [NO_LINK; 8];1101        let mut encodings = [];1102        let mut affine = [PublicSimdAffine::IDENTITY; 64];1103        let mut buckets = [PublicSimdPoint::IDENTITY; 8];1104        let mut expected = [ProjectivePoint::IDENTITY; 8];1105        let mut next = 0;1106        for (bucket, length) in lengths.into_iter().enumerate() {1107            let base = ProjectivePoint::GENERATOR * Scalar::from((bucket + 1) as u64);1108            expected[bucket] = if form == 2 || form == 0 && bucket % 3 == 0 {1109                ProjectivePoint::IDENTITY1110            } else {1111                base1112            };1113            buckets[bucket] = PublicSimdPoint::from_affine(1114                &PublicSimdAffine::from_affine(&expected[bucket].to_affine()),1115                false,1116            );1117            for turn in 0..length {1118                let input = if form == 2 {1119                    ProjectivePoint::IDENTITY1120                } else if form == 1 {1121                    match turn % 3 {1122                        0 => -base,1123                        1 => base,1124                        _ => ProjectivePoint::IDENTITY,1125                    }1126                } else {1127                    match (turn + bucket) % 4 {1128                        0 => base,1129                        1 => -base,1130                        2 => ProjectivePoint::IDENTITY,1131                        _ => base.double(),1132                    }1133                };1134                let negative = form == 0 && (turn + bucket) % 3 == 0;1135                affine[next] = PublicSimdAffine::from_affine(&input.to_affine());1136                links[next] = heads[bucket];1137                heads[bucket] = ((next as u16) << 1) | u16::from(negative);1138                expected[bucket] += if negative { -input } else { input };1139                next += 1;1140            }1141        }1142        let mut scratch = Workspace {1143            encodings: &mut encodings,1144            affine: &mut affine,1145            buckets: &mut buckets,1146        };1147        let mut stats = Stats::default();1148        accumulate_chains::<AFFINITY, LONGEST, 8, 64>(1149            &mut scratch,1150            &mut heads,1151            &links,1152            8,1153            &mut stats,1154        );1155        assert!(heads.iter().all(|head| *head == NO_LINK));1156        assert_eq!(stats.mixed_lanes, lengths.iter().sum::<usize>());1157        for (bucket, expected) in expected.iter().enumerate() {1158            assert_eq!(1159                scratch.buckets[bucket].to_projective(),1160                *expected,1161                "affinity{AFFINITY}/longest{LONGEST}/form{form}/bucket{bucket}"1162            );1163        }1164    }11651166    #[test]1167    fn finished_chain_lanes_remain_masked_through_reactivation_and_cancellation() {1168        for form in 0..3 {1169            chain_lifecycle::<false, false>(form);1170            chain_lifecycle::<true, false>(form);1171            chain_lifecycle::<false, true>(form);1172            chain_lifecycle::<true, true>(form);1173        }1174    }11751176    fn unequal_chain_schedule<const AFFINITY: bool, const LONGEST: bool>() -> Stats {1177        let lengths = [10usize, 10, 1, 1, 1, 1, 10, 10];1178        let mut links = [NO_LINK; 64];1179        let mut heads = [NO_LINK; 8];1180        let mut encodings = [];1181        let generator = ProjectivePoint::GENERATOR;1182        let affine_g = PublicSimdAffine::from_affine(&AffinePoint::GENERATOR);1183        let mut affine = [affine_g; 64];1184        let mut buckets = [PublicSimdPoint::IDENTITY; 8];1185        let mut expected = [ProjectivePoint::IDENTITY; 8];1186        let mut input = 0;1187        for (bucket, length) in lengths.into_iter().enumerate() {1188            expected[bucket] = generator * Scalar::from((bucket + 1) as u64);1189            buckets[bucket] = PublicSimdPoint::from_affine(1190                &PublicSimdAffine::from_affine(&expected[bucket].to_affine()),1191                false,1192            );1193            for turn in 0..length + usize::from(AFFINITY) {1194                let negative = (bucket + turn) % 2 == 0;1195                links[input] = heads[bucket];1196                heads[bucket] = ((input as u16) << 1) | u16::from(negative);1197                expected[bucket] += if negative { -generator } else { generator };1198                input += 1;1199            }1200        }1201        let mut scratch = Workspace {1202            encodings: &mut encodings,1203            affine: &mut affine,1204            buckets: &mut buckets,1205        };1206        let mut stats = Stats::default();1207        accumulate_chains::<AFFINITY, LONGEST, 8, 64>(1208            &mut scratch,1209            &mut heads,1210            &links,1211            8,1212            &mut stats,1213        );1214        assert!(heads.iter().all(|head| *head == NO_LINK));1215        assert_eq!(stats.mixed_lanes, input);1216        for (bucket, expected) in expected.iter().enumerate() {1217            assert_eq!(1218                scratch.buckets[bucket].to_projective(),1219                *expected,1220                "affinity{AFFINITY}/longest{LONGEST}/bucket{bucket}"1221            );1222        }1223        stats1224    }12251226    #[test]1227    fn longest_first_chains_preserve_results_and_reduce_underfilled_tail_rounds() {1228        let original = unequal_chain_schedule::<false, false>();1229        let ordered = unequal_chain_schedule::<false, true>();1230        assert_eq!(ordered.vector_mixed_calls + 1, original.vector_mixed_calls);1231        assert_eq!(ordered.mixed_lanes, original.mixed_lanes);1232        let original = unequal_chain_schedule::<true, false>();1233        let ordered = unequal_chain_schedule::<true, true>();1234        assert_eq!(ordered.vector_mixed_calls + 1, original.vector_mixed_calls);1235        assert_eq!(ordered.mixed_lanes, original.mixed_lanes);1236    }12371238    #[test]1239    fn bounded_widths_keep_signed_carry_and_match_exact_group_arithmetic() {1240        for bits in [1241            0, 1, 4, 5, 6, 7, 8, 9, 13, 16, 31, 32, 127, 128, 129, 141, 148, 163, 173, 180, 195,1242            255, 256,1243        ] {1244            let terms: Vec<_> = original_terms(17)1245                .into_iter()1246                .enumerate()1247                .map(|(i, term)| Term {1248                    scalar: if i % 3 == 0 {1249                        Scalar::ZERO1250                    } else {1251                        maximal(bits)1252                    },1253                    ..term1254                })1255                .collect();1256            let expected = terms.iter().fold(ProjectivePoint::IDENTITY, |sum, term| {1257                sum + term.point * term.scalar1258            });1259            for w in [5, 6, 7] {1260                let window = Window::new(w).unwrap();1261                with_scratch(terms.len(), window, false, |scratch| {1262                    for population in [&terms[..0], &terms[..1], &terms[..3], &terms[..]] {1263                        let (actual, stats) = weighted_msm_bounded_with_stats_vartime(1264                            population, scratch, window, bits,1265                        )1266                        .unwrap();1267                        let oracle = if population.len() == terms.len() {1268                            expected1269                        } else {1270                            population1271                                .iter()1272                                .fold(ProjectivePoint::IDENTITY, |sum, term| {1273                                    sum + term.point * term.scalar1274                                })1275                        };1276                        assert_eq!(actual.to_projective(), oracle, "bits{bits}/w{w}");1277                        assert_eq!(stats.groups, (bits + 2).div_ceil(usize::from(w)));1278                        assert_eq!(stats.prepared_affines, population.len());1279                    }1280                });1281            }1282        }1283    }12841285    #[test]1286    fn all_bounded_width_window_alignments_preserve_maximal_integer_carry() {1287        // Exercise every possible top-window alignment, including the real1288        // certificate bounds 173/W6 and 195/W7. A single nonidentity base makes1289        // a dropped final carry observable rather than allowing cancellation.1290        for scalar_bits in 0..=256 {1291            let scalar = maximal(scalar_bits);1292            let term = Term {1293                point: AffinePoint::GENERATOR,1294                scalar,1295            };1296            let expected = ProjectivePoint::GENERATOR * scalar;1297            for width in 2..=8 {1298                let window = Window::new(width).unwrap();1299                with_scratch(1, window, true, |scratch| {1300                    let (actual, stats) = weighted_msm_bounded_with_stats_vartime(1301                        &[term],1302                        scratch,1303                        window,1304                        scalar_bits,1305                    )1306                    .unwrap();1307                    assert_eq!(1308                        actual.to_projective(),1309                        expected,1310                        "bounded bits{scalar_bits}/w{width}"1311                    );1312                    assert_eq!(stats.groups, (scalar_bits + 2).div_ceil(usize::from(width)));1313                    if scalar_bits != 0 {1314                        let count = 256usize.div_ceil(scalar_bits).min(4);1315                        let (columns, stats) = weighted_msm_radix4_with_stats_vartime(1316                            &[term],1317                            scratch,1318                            window,1319                            scalar_bits,1320                            0,1321                            count,1322                        )1323                        .unwrap();1324                        assert_eq!(1325                            columns[0].to_projective(),1326                            expected,1327                            "radix4 bits{scalar_bits}/w{width}"1328                        );1329                        assert!(columns[1..].iter().all(PublicSimdPoint::is_identity));1330                        assert_eq!(stats.groups, (scalar_bits + 2).div_ceil(usize::from(width)));1331                    }1332                });1333            }1334        }1335    }13361337    #[test]1338    fn top_shards_follow_actual_digits_after_wider_bounds_and_at_capacity_edges() {1339        for scalar_bits in [150, 151, 152] {1340            let terms: Vec<_> = original_terms(217)1341                .into_iter()1342                .enumerate()1343                .map(|(i, term)| Term {1344                    point: if i == 0 {1345                        AffinePoint::GENERATOR1346                    } else {1347                        term.point1348                    },1349                    scalar: if i == 0 {1350                        maximal(scalar_bits)1351                    } else {1352                        maximal(147)1353                    },1354                })1355                .collect();1356            let expected = terms.iter().fold(ProjectivePoint::IDENTITY, |sum, term| {1357                sum + term.point * term.scalar1358            });1359            for width in 2..=8 {1360                let window = Window::new(width).unwrap();1361                with_scratch(terms.len(), window, false, |scratch| {1362                    let (actual, stats) = weighted_msm_bounded_with_stats_vartime(1363                        &terms,1364                        scratch,1365                        window,1366                        scalar_bits,1367                    )1368                    .unwrap();1369                    assert_eq!(1370                        actual.to_projective(),1371                        expected,1372                        "bits{scalar_bits}/w{width}"1373                    );1374                    if width == 7 {1375                        // Top magnitudes are respectively 8,16,32. Four1376                        // shards fit exactly at 16, and must not fit at 32.1377                        assert_eq!(stats.sharded_top_groups, usize::from(scalar_bits <= 151));1378                        let groups = (scalar_bits + 2).div_ceil(7);1379                        let remaining = scalar_bits + 2 - (groups - 1) * 7;1380                        assert!(4 * (1usize << remaining) > 64);1381                    }1382                    let (one, _) = weighted_msm_bounded_with_stats_vartime(1383                        &terms[..1],1384                        scratch,1385                        window,1386                        scalar_bits,1387                    )1388                    .unwrap();1389                    assert_eq!(1390                        one.to_projective(),1391                        ProjectivePoint::GENERATOR * maximal(scalar_bits)1392                    );1393                    let (zero, stats) = weighted_msm_bounded_with_stats_vartime(1394                        &[Term::ZERO; 5],1395                        scratch,1396                        window,1397                        scalar_bits,1398                    )1399                    .unwrap();1400                    assert!(zero.is_identity());1401                    assert_eq!(stats.sharded_top_groups, 1);1402                    let (empty, stats) =1403                        weighted_msm_bounded_with_stats_vartime(&[], scratch, window, scalar_bits)1404                            .unwrap();1405                    assert!(empty.is_identity());1406                    assert_eq!(stats.sharded_top_groups, 1);1407                });1408            }1409        }1410    }14111412    #[test]1413    fn bounded_rejects_high_bits_and_full_width_negative_residues() {1414        let window = Window::new(6).unwrap();1415        with_scratch(2, window, false, |scratch| {1416            for bits in [0, 1, 7, 8, 31, 32, 127, 128, 141, 148, 163, 255] {1417                let mut bytes = [0u8; 32];1418                bytes[31 - bits / 8] = 1 << (bits % 8);1419                let term = Term {1420                    point: AffinePoint::GENERATOR,1421                    scalar: Scalar::from_repr(bytes.into()).unwrap(),1422                };1423                assert!(matches!(1424                    weighted_msm_bounded_vartime(&[term], scratch, window, bits),1425                    Err(msm::Error::ScalarRange)1426                ));1427            }1428            assert!(matches!(1429                weighted_msm_bounded_vartime(&[], scratch, window, 257),1430                Err(msm::Error::ScalarBits)1431            ));1432            let residue = Term {1433                point: AffinePoint::GENERATOR,1434                scalar: -Scalar::ONE,1435            };1436            assert!(matches!(1437                weighted_msm_bounded_vartime(&[residue], scratch, window, 128),1438                Err(msm::Error::ScalarRange)1439            ));1440            let negative = Term {1441                point: -AffinePoint::GENERATOR,1442                scalar: Scalar::ONE,1443            };1444            let actual = weighted_msm_bounded_vartime(&[negative], scratch, window, 1).unwrap();1445            assert_eq!(actual.to_projective(), -ProjectivePoint::GENERATOR);1446            let cancel = Term {1447                point: AffinePoint::GENERATOR,1448                scalar: Scalar::ONE,1449            };1450            assert!(1451                weighted_msm_bounded_vartime(&[negative, cancel], scratch, window, 1)1452                    .unwrap()1453                    .is_identity()1454            );1455            assert!(matches!(1456                weighted_msm_bounded_vartime(&[Term::ZERO; 3], scratch, window, 1),1457                Err(msm::Error::Capacity)1458            ));1459        });1460    }14611462    fn oracle_digit(scalar: Scalar, offset: usize, width: usize) -> Scalar {1463        let bytes = scalar.to_bytes();1464        let mut digit = Scalar::ZERO;1465        for bit in (offset..(offset + width).min(256)).rev() {1466            digit = digit + digit;1467            if bytes[31 - bit / 8] & (1 << (bit % 8)) != 0 {1468                digit += Scalar::ONE;1469            }1470        }1471        digit1472    }14731474    #[test]1475    fn radix4_retains_four_independent_outputs_and_clears_unused_lanes() {1476        let terms = original_terms(201);1477        for digit_bits in [1, 8, 13, 16, 32, 64, 255, 256] {1478            let columns = 256usize.div_ceil(digit_bits);1479            for w in [5, 6, 7] {1480                let window = Window::new(w).unwrap();1481                with_scratch(terms.len(), window, true, |scratch| {1482                    for (first, count) in [(0, columns.min(4)), (columns - 1, 1)] {1483                        let actual = weighted_msm_radix4_vartime(1484                            &terms, scratch, window, digit_bits, first, count,1485                        )1486                        .unwrap();1487                        for lane in 0..4 {1488                            let expected = if lane >= count {1489                                ProjectivePoint::IDENTITY1490                            } else {1491                                terms.iter().fold(ProjectivePoint::IDENTITY, |sum, term| {1492                                    sum + term.point1493                                        * oracle_digit(1494                                            term.scalar,1495                                            (first + lane) * digit_bits,1496                                            digit_bits,1497                                        )1498                                })1499                            };1500                            assert_eq!(1501                                actual[lane].to_projective(),1502                                expected,1503                                "b{digit_bits}/w{w}/first{first}/lane{lane}"1504                            );1505                        }1506                    }1507                    assert!(1508                        weighted_msm_radix4_vartime(1509                            &[],1510                            scratch,1511                            window,1512                            digit_bits,1513                            0,1514                            columns.min(4),1515                        )1516                        .unwrap()1517                        .iter()1518                        .all(PublicSimdPoint::is_identity)1519                    );1520                    assert!(1521                        weighted_msm_radix4_vartime(1522                            &terms, scratch, window, digit_bits, columns, 0,1523                        )1524                        .unwrap()1525                        .iter()1526                        .all(PublicSimdPoint::is_identity)1527                    );1528                });1529            }1530        }1531        let window = Window::new(5).unwrap();1532        with_scratch(1, window, true, |scratch| {1533            for (bits, first, count) in [(0, 0, 1), (257, 0, 1), (8, 32, 1), (8, 0, 5)] {1534                assert!(matches!(1535                    weighted_msm_radix4_vartime(&terms[..1], scratch, window, bits, first, count),1536                    Err(msm::Error::ScalarBits)1537                ));1538            }1539            assert!(matches!(1540                weighted_msm_radix4_vartime(&terms[..2], scratch, window, 8, 0, 4),1541                Err(msm::Error::Capacity)1542            ));1543        });1544    }15451546    #[test]1547    fn public_point_helpers_and_batch_normalization_match_exceptional_group_cases() {1548        let ordinary = [1549            ProjectivePoint::IDENTITY,1550            ProjectivePoint::GENERATOR,1551            -ProjectivePoint::GENERATOR,1552            ProjectivePoint::GENERATOR.double(),1553            ProjectivePoint::GENERATOR.endomorphism(),1554        ];1555        let points = ordinary.map(|point| {1556            PublicSimdPoint::from_affine(&PublicSimdAffine::from_affine(&point.to_affine()), false)1557                .double()1558        });1559        let normalized = PublicSimdPoint::batch_to_affine(&points);1560        for (i, point) in points.iter().enumerate() {1561            assert_eq!(normalized[i], ordinary[i].double().to_affine());1562            assert_eq!(point.negate().to_projective(), -ordinary[i].double());1563            for j in 0..points.len() {1564                let sum = point.add(&points[j]);1565                let expected = (ordinary[i] + ordinary[j]).double();1566                assert_eq!(sum.to_projective(), expected);1567                assert_eq!(sum.is_identity(), bool::from(expected.is_identity()));1568            }1569        }1570        assert!(1571            PublicSimdPoint::batch_to_affine(&[PublicSimdPoint::IDENTITY; 4])1572                .iter()1573                .all(|point| bool::from(point.is_identity()))1574        );1575        assert_eq!(1576            PublicSimdPoint::batch_to_affine::<0>(&[]),1577            [AffinePoint::IDENTITY; 0]1578        );1579    }1580}