garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /crypto/src/scalar.rs

raw

//! Integers modulo the group order L = 2^252 + 27742317777372353535851937790883648493,
//! as 32 little-endian bytes.

const L: [u64; 4] = [
    0x5812_631a_5cf5_d3ed,
    0x14de_f9de_a2f7_9cd6,
    0,
    0x1000_0000_0000_0000,
];

/// r − L when that does not go below zero, else r; in the same time.
fn reduce_once(r: [u64; 4]) -> [u64; 4] {
    let mut d = [0u64; 4];
    let mut borrow = 0u64;
    for i in 0..4 {
        let (x, b1) = r[i].overflowing_sub(L[i]);
        let (x, b2) = x.overflowing_sub(borrow);
        d[i] = x;
        borrow = u64::from(b1 | b2);
    }
    // borrow is 1 when r < L: keep r.
    let keep = 0u64.wrapping_sub(borrow);
    core::array::from_fn(|i| (r[i] & keep) | (d[i] & !keep))
}

/// A number of any length (little-endian bytes) modulo L, by binary long
/// division from the top bit: the remainder stays below 2L < 2^254.
pub fn reduce(bytes: &[u8]) -> [u8; 32] {
    let mut r = [0u64; 4];
    for bit in (0..bytes.len() * 8).rev() {
        let b = u64::from((bytes[bit / 8] >> (bit % 8)) & 1);
        r = [
            r[0] << 1 | b,
            r[1] << 1 | r[0] >> 63,
            r[2] << 1 | r[1] >> 63,
            r[3] << 1 | r[2] >> 63,
        ];
        r = reduce_once(r);
    }
    to_bytes(r)
}

fn to_bytes(r: [u64; 4]) -> [u8; 32] {
    let mut out = [0u8; 32];
    for (i, limb) in r.iter().enumerate() {
        out[i * 8..i * 8 + 8].copy_from_slice(&limb.to_le_bytes());
    }
    out
}

fn limbs(b: &[u8; 32]) -> [u64; 4] {
    core::array::from_fn(|i| u64::from_le_bytes(b[i * 8..i * 8 + 8].try_into().unwrap()))
}

/// (a × b + c) mod L.
pub fn mul_add(a: &[u8; 32], b: &[u8; 32], c: &[u8; 32]) -> [u8; 32] {
    let (a, b, c) = (limbs(a), limbs(b), limbs(c));
    let mut wide = [0u64; 8];
    for i in 0..4 {
        let mut carry = 0u128;
        for j in 0..4 {
            let t = u128::from(a[i]) * u128::from(b[j]) + u128::from(wide[i + j]) + carry;
            wide[i + j] = t as u64;
            carry = t >> 64;
        }
        wide[i + 4] = carry as u64;
    }
    let mut carry = 0u128;
    for i in 0..8 {
        let t = u128::from(wide[i]) + u128::from(if i < 4 { c[i] } else { 0 }) + carry;
        wide[i] = t as u64;
        carry = t >> 64;
    }
    let mut bytes = [0u8; 64];
    for (i, limb) in wide.iter().enumerate() {
        bytes[i * 8..i * 8 + 8].copy_from_slice(&limb.to_le_bytes());
    }
    reduce(&bytes)
}

/// Whether `s` is below L, as a signature's S must be.
pub fn is_canonical(s: &[u8; 32]) -> bool {
    reduce_once(limbs(s)) == limbs(s) && s[31] & 0xf0 == 0
}