ed25519-simd 0.1.0

Verification-only, AVX-512 IFMA batch Ed25519 signature verification, acceptance-compatible with solana-ed25519
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
use super::{LANES, Radix16, WIDE_WORDS};

/// Reduce eight 512-bit challenge hashes modulo the group order and recode
/// them as signed radix-16 digits. Each input row is one word across all lanes.
pub(super) fn wide_words_to_radix16(words: &[[u64; LANES]; WIDE_WORDS]) -> [Radix16; LANES] {
    WideScalar52::from_wide_words(words).to_radix16()
}

const LIMB52_MASK: u64 = (1u64 << 52) - 1;
// Number of 52-bit limbs needed to represent a value modulo L, the group order.
const LIMB_COUNT: usize = 5;
const SCALAR_L: [u64; LIMB_COUNT] = [
    0x0002631a5cf5d3ed,
    0x000dea2f79cd6581,
    0x000000000014def9,
    0x0000000000000000,
    0x0000100000000000,
];
const SCALAR_LFACTOR: u64 = 0x51da312547e1b;
const SCALAR_R: [u64; LIMB_COUNT] = [
    0x000f48bd6721e6ed,
    0x0003bab5ac67e45a,
    0x000fffffeb35e51b,
    0x000fffffffffffff,
    0x00000fffffffffff,
];
const SCALAR_RR: [u64; LIMB_COUNT] = [
    0x0009d265e952d13b,
    0x000d63c715bea69f,
    0x0005be65cb687604,
    0x0003dceec73d217f,
    0x000009411b7c309a,
];

/// Eight scalars packed limbwise for parallel AVX-512 modular arithmetic.
///
/// Each vector holds one 52-bit limb from eight SHA-512 hashes,
/// so one IFMA Montgomery multiplication advances all eight reductions.
#[derive(Clone, Copy)]
struct WideScalar52([std::arch::x86_64::__m512i; LIMB_COUNT]);

impl WideScalar52 {
    /// Reduces eight 512-bit little-endian integers modulo the group order.
    ///
    /// `words[word][lane]` is word `word` of the integer in `lane`. The result
    /// stores each reduced integer as five radix-2^52 limbs.
    fn from_wide_words(words: &[[u64; LANES]; WIDE_WORDS]) -> Self {
        use std::arch::x86_64::*;
        unsafe {
            let mask = _mm512_set1_epi64(LIMB52_MASK as i64);
            let words: [__m512i; WIDE_WORDS] = core::array::from_fn(|i| loadu(words[i]));
            let lo = Self([
                _mm512_and_si512(words[0], mask),
                _mm512_and_si512(
                    _mm512_or_si512(
                        _mm512_srli_epi64(words[0], 52),
                        _mm512_slli_epi64(words[1], 12),
                    ),
                    mask,
                ),
                _mm512_and_si512(
                    _mm512_or_si512(
                        _mm512_srli_epi64(words[1], 40),
                        _mm512_slli_epi64(words[2], 24),
                    ),
                    mask,
                ),
                _mm512_and_si512(
                    _mm512_or_si512(
                        _mm512_srli_epi64(words[2], 28),
                        _mm512_slli_epi64(words[3], 36),
                    ),
                    mask,
                ),
                _mm512_and_si512(
                    _mm512_or_si512(
                        _mm512_srli_epi64(words[3], 16),
                        _mm512_slli_epi64(words[4], 48),
                    ),
                    mask,
                ),
            ]);
            let hi = Self([
                _mm512_and_si512(_mm512_srli_epi64(words[4], 4), mask),
                _mm512_and_si512(
                    _mm512_or_si512(
                        _mm512_srli_epi64(words[4], 56),
                        _mm512_slli_epi64(words[5], 8),
                    ),
                    mask,
                ),
                _mm512_and_si512(
                    _mm512_or_si512(
                        _mm512_srli_epi64(words[5], 44),
                        _mm512_slli_epi64(words[6], 20),
                    ),
                    mask,
                ),
                _mm512_and_si512(
                    _mm512_or_si512(
                        _mm512_srli_epi64(words[6], 32),
                        _mm512_slli_epi64(words[7], 32),
                    ),
                    mask,
                ),
                _mm512_srli_epi64(words[7], 20),
            ]);

            Self::add(
                &hi.montgomery_mul(&Self::constant(&SCALAR_RR)),
                &lo.montgomery_mul(&Self::constant(&SCALAR_R)),
            )
        }
    }

    /// Broadcasts a radix-2^52 integer into every SIMD lane.
    fn constant(value: &[u64; LIMB_COUNT]) -> Self {
        use std::arch::x86_64::*;
        unsafe { Self(core::array::from_fn(|i| _mm512_set1_epi64(value[i] as i64))) }
    }

    /// Adds two reduced values lane-wise and returns their canonical sum modulo
    /// the group order.
    fn add(a: &Self, b: &Self) -> Self {
        use std::arch::x86_64::*;
        unsafe {
            let mask = _mm512_set1_epi64(LIMB52_MASK as i64);
            let mut out = [_mm512_setzero_si512(); LIMB_COUNT];
            let mut carry = _mm512_setzero_si512();
            let mut i = 0;
            while i < LIMB_COUNT {
                let sum = _mm512_add_epi64(_mm512_add_epi64(a.0[i], b.0[i]), carry);
                out[i] = _mm512_and_si512(sum, mask);
                carry = _mm512_srli_epi64(sum, 52);
                i += 1;
            }
            Self(out).sub(&Self::constant(&SCALAR_L))
        }
    }

    /// Subtracts `rhs` lane-wise and returns the canonical difference modulo the
    /// group order.
    fn sub(&self, rhs: &Self) -> Self {
        use std::arch::x86_64::*;
        unsafe {
            let limb_mask = _mm512_set1_epi64(LIMB52_MASK as i64);
            let one = _mm512_set1_epi64(1);
            let mut out = [_mm512_setzero_si512(); LIMB_COUNT];
            let mut borrow_mask = 0;
            let mut i = 0;
            while i < LIMB_COUNT {
                let borrow = _mm512_maskz_mov_epi64(borrow_mask, one);
                let subtrahend = _mm512_add_epi64(rhs.0[i], borrow);
                borrow_mask = _mm512_cmplt_epu64_mask(self.0[i], subtrahend);
                out[i] = _mm512_and_si512(_mm512_sub_epi64(self.0[i], subtrahend), limb_mask);
                i += 1;
            }

            let added_l = Self(out).add_l();
            Self(core::array::from_fn(|i| {
                _mm512_mask_blend_epi64(borrow_mask, out[i], added_l.0[i])
            }))
        }
    }

    /// Adds the group order to every lane without performing a final reduction.
    fn add_l(&self) -> Self {
        use std::arch::x86_64::*;
        unsafe {
            let l = Self::constant(&SCALAR_L);
            let mask = _mm512_set1_epi64(LIMB52_MASK as i64);
            let mut out = [_mm512_setzero_si512(); LIMB_COUNT];
            let mut carry = _mm512_setzero_si512();
            let mut i = 0;
            while i < LIMB_COUNT {
                let sum = _mm512_add_epi64(_mm512_add_epi64(self.0[i], l.0[i]), carry);
                out[i] = _mm512_and_si512(sum, mask);
                carry = _mm512_srli_epi64(sum, 52);
                i += 1;
            }
            Self(out)
        }
    }

    /// Multiplies two values lane-wise and performs Montgomery reduction.
    ///
    /// For Montgomery radix `R = 2^260`, the result is
    /// `self * rhs * R^-1 mod L` in each lane.
    fn montgomery_mul(&self, rhs: &Self) -> Self {
        let (lo, hi) = Self::mul_internal(self, rhs);
        Self::montgomery_reduce(&lo, &hi)
    }

    /// Computes the uncarried radix-2^52 product convolution in every lane.
    ///
    /// The returned arrays hold the low and high 52-bit halves accumulated for
    /// each output limb, ready for Montgomery reduction.
    fn mul_internal(
        a: &Self,
        b: &Self,
    ) -> (
        [std::arch::x86_64::__m512i; 2 * LIMB_COUNT - 1],
        [std::arch::x86_64::__m512i; 2 * LIMB_COUNT - 1],
    ) {
        use std::arch::x86_64::*;
        unsafe {
            let mut lo = [_mm512_setzero_si512(); 2 * LIMB_COUNT - 1];
            let mut hi = [_mm512_setzero_si512(); 2 * LIMB_COUNT - 1];
            let mut i = 0;
            while i < LIMB_COUNT {
                let mut j = 0;
                while j < LIMB_COUNT {
                    lo[i + j] = _mm512_madd52lo_epu64(lo[i + j], a.0[i], b.0[j]);
                    hi[i + j] = _mm512_madd52hi_epu64(hi[i + j], a.0[i], b.0[j]);
                    j += 1;
                }
                i += 1;
            }
            (lo, hi)
        }
    }

    /// Montgomery-reduces a split product and returns its canonical residue in
    /// each lane.
    fn montgomery_reduce(
        lo: &[std::arch::x86_64::__m512i; 2 * LIMB_COUNT - 1],
        hi: &[std::arch::x86_64::__m512i; 2 * LIMB_COUNT - 1],
    ) -> Self {
        use std::arch::x86_64::*;

        #[inline(always)]
        fn add_product(lo: &mut __m512i, hi: &mut __m512i, lhs: __m512i, rhs: __m512i) {
            unsafe {
                *lo = _mm512_madd52lo_epu64(*lo, lhs, rhs);
                *hi = _mm512_madd52hi_epu64(*hi, lhs, rhs);
            }
        }

        #[inline(always)]
        fn eliminate_low_limb(
            mut lo: __m512i,
            mut hi: __m512i,
            carry: __m512i,
            factor: __m512i,
            l0: __m512i,
        ) -> (__m512i, __m512i) {
            unsafe {
                lo = _mm512_add_epi64(lo, carry);
                let quotient = _mm512_madd52lo_epu64(_mm512_setzero_si512(), lo, factor);
                add_product(&mut lo, &mut hi, quotient, l0);
                let carry = _mm512_add_epi64(hi, _mm512_srli_epi64(lo, 52));
                (quotient, carry)
            }
        }

        #[inline(always)]
        fn split_output_limb(
            lo: __m512i,
            hi: __m512i,
            carry: __m512i,
            mask: __m512i,
        ) -> (__m512i, __m512i) {
            unsafe {
                let lo = _mm512_add_epi64(lo, carry);
                (
                    _mm512_add_epi64(hi, _mm512_srli_epi64(lo, 52)),
                    _mm512_and_si512(lo, mask),
                )
            }
        }

        unsafe {
            let zero = _mm512_setzero_si512();
            let mask = _mm512_set1_epi64(LIMB52_MASK as i64);
            let factor = _mm512_set1_epi64(SCALAR_LFACTOR as i64);
            let l = Self::constant(&SCALAR_L).0;

            let (n0, carry) = eliminate_low_limb(lo[0], hi[0], zero, factor, l[0]);

            let (mut s_lo, mut s_hi) = (lo[1], hi[1]);
            add_product(&mut s_lo, &mut s_hi, n0, l[1]);
            let (n1, carry) = eliminate_low_limb(s_lo, s_hi, carry, factor, l[0]);

            let (mut s_lo, mut s_hi) = (lo[2], hi[2]);
            add_product(&mut s_lo, &mut s_hi, n0, l[2]);
            add_product(&mut s_lo, &mut s_hi, n1, l[1]);
            let (n2, carry) = eliminate_low_limb(s_lo, s_hi, carry, factor, l[0]);

            let (mut s_lo, mut s_hi) = (lo[3], hi[3]);
            add_product(&mut s_lo, &mut s_hi, n1, l[2]);
            add_product(&mut s_lo, &mut s_hi, n2, l[1]);
            let (n3, carry) = eliminate_low_limb(s_lo, s_hi, carry, factor, l[0]);

            let (mut s_lo, mut s_hi) = (lo[4], hi[4]);
            add_product(&mut s_lo, &mut s_hi, n0, l[4]);
            add_product(&mut s_lo, &mut s_hi, n2, l[2]);
            add_product(&mut s_lo, &mut s_hi, n3, l[1]);
            let (n4, carry) = eliminate_low_limb(s_lo, s_hi, carry, factor, l[0]);

            let (mut s_lo, mut s_hi) = (lo[5], hi[5]);
            add_product(&mut s_lo, &mut s_hi, n1, l[4]);
            add_product(&mut s_lo, &mut s_hi, n3, l[2]);
            add_product(&mut s_lo, &mut s_hi, n4, l[1]);
            let (carry, r0) = split_output_limb(s_lo, s_hi, carry, mask);

            let (mut s_lo, mut s_hi) = (lo[6], hi[6]);
            add_product(&mut s_lo, &mut s_hi, n2, l[4]);
            add_product(&mut s_lo, &mut s_hi, n4, l[2]);
            let (carry, r1) = split_output_limb(s_lo, s_hi, carry, mask);

            let (mut s_lo, mut s_hi) = (lo[7], hi[7]);
            add_product(&mut s_lo, &mut s_hi, n3, l[4]);
            let (carry, r2) = split_output_limb(s_lo, s_hi, carry, mask);

            let (mut s_lo, mut s_hi) = (lo[8], hi[8]);
            add_product(&mut s_lo, &mut s_hi, n4, l[4]);
            let (r4, r3) = split_output_limb(s_lo, s_hi, carry, mask);

            Self([r0, r1, r2, r3, r4]).sub(&Self::constant(&SCALAR_L))
        }
    }

    /// Packs each lane's five radix-2^52 limbs into four little-endian 64-bit
    /// words.
    fn words(self) -> [std::arch::x86_64::__m512i; 4] {
        use std::arch::x86_64::*;
        unsafe {
            [
                _mm512_or_si512(self.0[0], _mm512_slli_epi64(self.0[1], 52)),
                _mm512_or_si512(
                    _mm512_srli_epi64(self.0[1], 12),
                    _mm512_slli_epi64(self.0[2], 40),
                ),
                _mm512_or_si512(
                    _mm512_srli_epi64(self.0[2], 24),
                    _mm512_slli_epi64(self.0[3], 28),
                ),
                _mm512_or_si512(
                    _mm512_srli_epi64(self.0[3], 36),
                    _mm512_slli_epi64(self.0[4], 16),
                ),
            ]
        }
    }

    /// Serializes each lane as a 32-byte little-endian scalar.
    #[cfg(test)]
    fn to_bytes_lanes(self) -> [[u8; 32]; LANES] {
        let words = self.words();
        let mut rows = [[0u64; LANES]; 4];
        for (word, row) in rows.iter_mut().enumerate() {
            storeu(words[word], row);
        }
        core::array::from_fn(|lane| {
            let mut bytes = [0u8; 32];
            for word in 0..4 {
                bytes[word * 8..word * 8 + 8].copy_from_slice(&rows[word][lane].to_le_bytes());
            }
            bytes
        })
    }

    /// Recodes each lane as 64 little-endian signed radix-16 digits in
    /// `-8..=7`.
    fn to_radix16(self) -> [Radix16; LANES] {
        use std::arch::x86_64::*;
        unsafe {
            let words = self.words();
            let byte_mask = _mm512_set1_epi64(0xff);
            let nibble_mask = _mm512_set1_epi64(0x0f);
            let bias = _mm512_set1_epi64(0x88);
            let eight = _mm512_set1_epi64(8);
            let mut carry = _mm512_setzero_si512();
            let mut out = [[0i8; 64]; LANES];
            let mut lanes = [0u64; LANES];

            let mut byte = 0;
            while byte < 32 {
                let shifts = _mm512_set1_epi64(((byte & 7) * 8) as i64);
                let value = _mm512_and_si512(_mm512_srlv_epi64(words[byte / 8], shifts), byte_mask);
                let biased = _mm512_add_epi64(_mm512_add_epi64(value, bias), carry);
                carry = _mm512_srli_epi64(biased, 8);

                let low = _mm512_sub_epi64(_mm512_and_si512(biased, nibble_mask), eight);
                let high = _mm512_sub_epi64(
                    _mm512_and_si512(_mm512_srli_epi64(biased, 4), nibble_mask),
                    eight,
                );
                storeu(low, &mut lanes);
                for lane in 0..LANES {
                    out[lane][2 * byte] = lanes[lane] as i8;
                }
                storeu(high, &mut lanes);
                for lane in 0..LANES {
                    out[lane][2 * byte + 1] = lanes[lane] as i8;
                }
                byte += 1;
            }

            storeu(carry, &mut lanes);
            debug_assert_eq!(lanes, [0; LANES]);
            out
        }
    }
}

// Loads the eight `u64` lanes into a 512-bit SIMD vector without requiring alignment.
#[inline(always)]
fn loadu(values: [u64; LANES]) -> std::arch::x86_64::__m512i {
    unsafe { std::arch::x86_64::_mm512_loadu_si512(values.as_ptr() as *const _) }
}

// Stores a 512-bit SIMD vector into eight `u64` lanes without requiring alignment.
#[inline(always)]
fn storeu(value: std::arch::x86_64::__m512i, out: &mut [u64; LANES]) {
    unsafe { std::arch::x86_64::_mm512_storeu_si512(out.as_mut_ptr() as *mut _, value) }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scalar::is_canonical;

    #[test]
    fn eight_lane_reduction_and_radix16_match_vectors() {
        let fixture: serde_json::Value =
            serde_json::from_str(include_str!("../../tests/vectors/scalar_reduction.json"))
                .unwrap();
        let cases = fixture["cases"].as_array().unwrap();
        assert_eq!(cases.len(), LANES);

        let words: [[u64; LANES]; WIDE_WORDS] = core::array::from_fn(|word| {
            core::array::from_fn(|lane| cases[lane]["words"][word].as_u64().unwrap())
        });
        let wide = WideScalar52::from_wide_words(&words);
        let reduced = wide.to_bytes_lanes();
        let digits = wide_words_to_radix16(&words);

        for lane in 0..LANES {
            let mut expected_reduced = [0u8; 32];
            hex::decode_to_slice(
                cases[lane]["reduced"].as_str().unwrap(),
                &mut expected_reduced,
            )
            .unwrap();
            let expected_digits: Radix16 =
                core::array::from_fn(|digit| cases[lane]["radix16"][digit].as_i64().unwrap() as i8);

            assert_eq!(reduced[lane], expected_reduced, "lane {lane} reduction");
            assert_eq!(digits[lane], expected_digits, "lane {lane} recoding");
            assert!(is_canonical(&reduced[lane]), "lane {lane} canonicality");
        }
    }
}