SPB Git

Repository Public

Field25519.swift 11.9 KB 263 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraEd25519/Field25519.swift8// Module           : Qyvora Ed255199// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import QyvoraMath4243/// 128-bit accumulator (two 64-bit words) for sums of 64×64-bit products.44///45/// The carry between the two words is computed with bit arithmetic only, as in `U256.adc` of the secp256k1 module:46/// no Boolean ever holds a carry, so the optimiser has nothing to turn into a conditional branch on secret limbs47/// (finding QYV-AUD-002).48struct Acc128 {49    var lo: UInt64 = 050    var hi: UInt64 = 05152    /// self += x · y. The caller guarantees that the running sum stays below 2^128.53    @inline(__always) mutating func addProduct(_ x: UInt64, _ y: UInt64) {54        let p = x.multipliedFullWidth(by: y)55        let s = lo &+ p.low56        let carry = ((lo & p.low) | ((lo | p.low) & ~s)) >> 6357        lo = s58        hi = hi &+ p.high &+ carry59    }6061    /// self += x.62    @inline(__always) mutating func add(_ x: UInt64) {63        let s = lo &+ x64        let carry = ((lo & x) | ((lo | x) & ~s)) >> 6365        lo = s66        hi = hi &+ carry67    }6869    /// self >> 51, which the caller guarantees to fit in 64 bits (self < 2^115).70    @inline(__always) var shiftedRight51: UInt64 { (hi << 13) | (lo >> 51) }71}7273/// Element of the field GF(2^255 − 19): five limbs of 51 bits, least significant first74/// (value = l0 + l1·2^51 + l2·2^102 + l3·2^153 + l4·2^204).75///76/// Invariant: every limb is below 2^52 ("loose" form; the value is any representative of its class below 2^256).77/// `add`, `sub`, `mul` and `fromBytes` return loose elements from loose inputs; only `toBytes` produces the canonical78/// representative. Every operation is a fixed sequence of additions, multiplications, shifts and masks: there is no79/// comparison, no Boolean and no branch on a limb.80struct Fe: Sendable {81    var l0: UInt6482    var l1: UInt6483    var l2: UInt6484    var l3: UInt6485    var l4: UInt648687    static let mask51: UInt64 = (1 << 51) - 188    static let zero = Fe(0, 0, 0, 0, 0)89    static let one = Fe(1, 0, 0, 0, 0)9091    @inline(__always) init(_ l0: UInt64, _ l1: UInt64, _ l2: UInt64, _ l3: UInt64, _ l4: UInt64) {92        self.l0 = l0; self.l1 = l1; self.l2 = l2; self.l3 = l3; self.l4 = l493    }9495    /// A small public constant.96    init(small v: UInt32) { self.init(UInt64(v), 0, 0, 0, 0) }9798    /// One parallel carry pass: limbs below 2^63 in, limbs below 2^51 + 2^17 out, same class modulo p.99    @inline(__always) static func carry(_ a: Fe) -> Fe {100        let c0 = a.l0 >> 51, c1 = a.l1 >> 51, c2 = a.l2 >> 51, c3 = a.l3 >> 51, c4 = a.l4 >> 51101        return Fe((a.l0 & mask51) &+ c4 &* 19, (a.l1 & mask51) &+ c0, (a.l2 & mask51) &+ c1,102                  (a.l3 & mask51) &+ c2, (a.l4 & mask51) &+ c3)103    }104105    @inline(__always) static func add(_ a: Fe, _ b: Fe) -> Fe {106        carry(Fe(a.l0 &+ b.l0, a.l1 &+ b.l1, a.l2 &+ b.l2, a.l3 &+ b.l3, a.l4 &+ b.l4))107    }108109    /// a − b, computed as a + 4p − b so that no limb goes negative (limbs of 4p: 2^53 − 76 and 2^53 − 4, above any loose limb).110    @inline(__always) static func sub(_ a: Fe, _ b: Fe) -> Fe {111        carry(Fe(a.l0 &+ 0x1f_ffff_ffff_ffb4 &- b.l0, a.l1 &+ 0x1f_ffff_ffff_fffc &- b.l1, a.l2 &+ 0x1f_ffff_ffff_fffc &- b.l2,112                 a.l3 &+ 0x1f_ffff_ffff_fffc &- b.l3, a.l4 &+ 0x1f_ffff_ffff_fffc &- b.l4))113    }114115    @inline(__always) static func neg(_ a: Fe) -> Fe { sub(.zero, a) }116117    /// a · b. With limbs below 2^52, each of the five column sums is below 5 · 19 · 2^104 < 2^111, so the carries118    /// (column >> 51) fit in 64 bits and 19 · (last carry) < 2^64.119    static func mul(_ a: Fe, _ b: Fe) -> Fe {120        let b1 = b.l1 &* 19, b2 = b.l2 &* 19, b3 = b.l3 &* 19, b4 = b.l4 &* 19121        var r0 = Acc128(), r1 = Acc128(), r2 = Acc128(), r3 = Acc128(), r4 = Acc128()122        r0.addProduct(a.l0, b.l0); r0.addProduct(a.l1, b4); r0.addProduct(a.l2, b3); r0.addProduct(a.l3, b2); r0.addProduct(a.l4, b1)123        r1.addProduct(a.l0, b.l1); r1.addProduct(a.l1, b.l0); r1.addProduct(a.l2, b4); r1.addProduct(a.l3, b3); r1.addProduct(a.l4, b2)124        r2.addProduct(a.l0, b.l2); r2.addProduct(a.l1, b.l1); r2.addProduct(a.l2, b.l0); r2.addProduct(a.l3, b4); r2.addProduct(a.l4, b3)125        r3.addProduct(a.l0, b.l3); r3.addProduct(a.l1, b.l2); r3.addProduct(a.l2, b.l1); r3.addProduct(a.l3, b.l0); r3.addProduct(a.l4, b4)126        r4.addProduct(a.l0, b.l4); r4.addProduct(a.l1, b.l3); r4.addProduct(a.l2, b.l2); r4.addProduct(a.l3, b.l1); r4.addProduct(a.l4, b.l0)127        r1.add(r0.shiftedRight51)128        r2.add(r1.shiftedRight51)129        r3.add(r2.shiftedRight51)130        r4.add(r3.shiftedRight51)131        let o0 = (r0.lo & mask51) &+ r4.shiftedRight51 &* 19132        let o1 = (r1.lo & mask51) &+ (o0 >> 51)133        return Fe(o0 & mask51, o1, r2.lo & mask51, r3.lo & mask51, r4.lo & mask51)134    }135136    @inline(__always) static func square(_ a: Fe) -> Fe { mul(a, a) }137138    /// a^(2^k) (k is a public constant).139    static func squareTimes(_ a: Fe, _ k: Int) -> Fe {140        var r = a141        for _ in 0..<k { r = mul(r, r) }142        return r143    }144145    /// (a^(2^250 − 1), a^11): the common part of the inversion and square-root exponentiations.146    private static func pow250(_ a: Fe) -> (Fe, Fe) {147        let z2 = square(a)148        let z9 = mul(a, squareTimes(z2, 2))149        let z11 = mul(z2, z9)150        let z5 = mul(z9, square(z11))               // a^(2^5 − 1)151        let z10 = mul(squareTimes(z5, 5), z5)       // a^(2^10 − 1)152        let z20 = mul(squareTimes(z10, 10), z10)153        let z40 = mul(squareTimes(z20, 20), z20)154        let z50 = mul(squareTimes(z40, 10), z10)155        let z100 = mul(squareTimes(z50, 50), z50)156        let z200 = mul(squareTimes(z100, 100), z100)157        let z250 = mul(squareTimes(z200, 50), z50)158        return (z250, z11)159    }160161    /// a^(p − 2): the inverse of a, and 0 for a = 0 (Fermat; fixed exponent, fixed sequence of operations).162    static func invert(_ a: Fe) -> Fe {163        let (z250, z11) = pow250(a)164        return mul(squareTimes(z250, 5), z11)165    }166167    /// a^((p − 5) / 8) = a^(2^252 − 3).168    static func pow22523(_ a: Fe) -> Fe {169        let (z250, _) = pow250(a)170        return mul(squareTimes(z250, 2), a)171    }172173    /// The 255 low bits of 32 little-endian bytes (bit 255 is ignored; values in [p, 2^255) are accepted here and174    /// denote their class modulo p — strict decoders compare with `toBytes` afterwards).175    static func fromBytes(_ b: UnsafePointer<UInt8>) -> Fe {176        Fe(Endian.loadLE64(b) & mask51, (Endian.loadLE64(b + 6) >> 3) & mask51, (Endian.loadLE64(b + 12) >> 6) & mask51,177           (Endian.loadLE64(b + 19) >> 1) & mask51, (Endian.loadLE64(b + 24) >> 12) & mask51)178    }179180    static func fromBytes(_ b: Bytes) -> Fe {181        precondition(b.count == 32)182        return b.withUnsafeBufferPointer { fromBytes($0.baseAddress!) }183    }184185    /// The four 64-bit words (least significant first) of the canonical representative in [0, p).186    @inline(__always) var canonicalWords: (UInt64, UInt64, UInt64, UInt64) {187        // sequential carries: afterwards the value is below 2^255 + 2^52, hence below 2p188        var t = Fe.carry(self)189        t.l1 &+= t.l0 >> 51; t.l0 &= Fe.mask51190        t.l2 &+= t.l1 >> 51; t.l1 &= Fe.mask51191        t.l3 &+= t.l2 >> 51; t.l2 &= Fe.mask51192        t.l4 &+= t.l3 >> 51; t.l3 &= Fe.mask51193        t.l0 &+= (t.l4 >> 51) &* 19; t.l4 &= Fe.mask51194        // q = ⌊(t + 19) / 2^255⌋ is 1 exactly when t ≥ p195        var q = (t.l0 &+ 19) >> 51196        q = (t.l1 &+ q) >> 51197        q = (t.l2 &+ q) >> 51198        q = (t.l3 &+ q) >> 51199        q = (t.l4 &+ q) >> 51200        // t − q·p = t + 19q − q·2^255: add 19q, propagate, drop bit 255201        t.l0 &+= q &* 19202        t.l1 &+= t.l0 >> 51; t.l0 &= Fe.mask51203        t.l2 &+= t.l1 >> 51; t.l1 &= Fe.mask51204        t.l3 &+= t.l2 >> 51; t.l2 &= Fe.mask51205        t.l4 &+= t.l3 >> 51; t.l3 &= Fe.mask51206        t.l4 &= Fe.mask51207        return (t.l0 | t.l1 << 51, t.l1 >> 13 | t.l2 << 38, t.l2 >> 26 | t.l3 << 25, t.l3 >> 39 | t.l4 << 12)208    }209210    /// Canonical 32-byte little-endian encoding (the representative in [0, p)).211    func toBytes() -> Bytes {212        let w = canonicalWords213        return Endian.le64(w.0) + Endian.le64(w.1) + Endian.le64(w.2) + Endian.le64(w.3)214    }215216    /// All ones when the element is 0 modulo p, zero otherwise.217    var isZeroMask: UInt64 {218        let w = canonicalWords219        let v = w.0 | w.1 | w.2 | w.3220        return ((v | (0 &- v)) >> 63) &- 1221    }222223    /// 1 when the canonical representative is odd ("negative" in RFC 8032), 0 otherwise.224    var isNegative: UInt64 { canonicalWords.0 & 1 }225226    /// All ones when a = b modulo p, zero otherwise.227    static func equalMask(_ a: Fe, _ b: Fe) -> UInt64 { sub(a, b).isZeroMask }228229    /// `a` when `mask` is all ones, `b` when it is zero.230    @inline(__always) static func select(_ mask: UInt64, _ a: Fe, _ b: Fe) -> Fe {231        Fe((a.l0 & mask) | (b.l0 & ~mask), (a.l1 & mask) | (b.l1 & ~mask), (a.l2 & mask) | (b.l2 & ~mask),232           (a.l3 & mask) | (b.l3 & ~mask), (a.l4 & mask) | (b.l4 & ~mask))233    }234235    /// Exchanges a and b when `mask` is all ones, leaves them when it is zero.236    @inline(__always) static func conditionalSwap(_ mask: UInt64, _ a: inout Fe, _ b: inout Fe) {237        let t0 = (a.l0 ^ b.l0) & mask, t1 = (a.l1 ^ b.l1) & mask, t2 = (a.l2 ^ b.l2) & mask238        let t3 = (a.l3 ^ b.l3) & mask, t4 = (a.l4 ^ b.l4) & mask239        a.l0 ^= t0; a.l1 ^= t1; a.l2 ^= t2; a.l3 ^= t3; a.l4 ^= t4240        b.l0 ^= t0; b.l1 ^= t1; b.l2 ^= t2; b.l3 ^= t3; b.l4 ^= t4241    }242243    /// The curve constant d = −121665 / 121666.244    static let d: Fe = mul(neg(Fe(small: 121_665)), invert(Fe(small: 121_666)))245    static let d2: Fe = add(d, d)246    /// A square root of −1: 2^((p − 1) / 4) = (2^(2^252 − 3))² · 2.247    static let sqrtMinusOne: Fe = { let two = Fe(small: 2); return mul(square(pow22523(two)), two) }()248249    /// Square root of u / v (RFC 8032 §5.1.3). Returns (all ones when u / v is a square, the non-negative root);250    /// when u / v is not a square the mask is zero and the value is meaningless. v = 0 gives (u = 0, 0).251    static func sqrtRatio(_ u: Fe, _ v: Fe) -> (UInt64, Fe) {252        let v3 = mul(square(v), v)253        let v7 = mul(square(v3), v)254        var r = mul(mul(u, v3), pow22523(mul(u, v7)))255        let check = mul(v, square(r))256        let correct = equalMask(check, u)257        let flipped = equalMask(check, neg(u))258        r = select(flipped, mul(r, sqrtMinusOne), r)259        r = select(0 &- r.isNegative, neg(r), r)260        return (correct | flipped, r)261    }262}263
Files main
Menu

Theme