SPB Git

Repository Public

Scalar25519.swift 7.3 KB 191 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraEd25519/Scalar25519.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/// Integer below 2^256 as four 64-bit limbs (least significant first), with arithmetic modulo the order of the44/// Ed25519 base point, ℓ = 2^252 + 27742317777372353535851937790883648493.45///46/// Reductions use Montgomery multiplication (R = 2^256): a fixed sequence of multiplications and additions whose47/// carries are computed with bit arithmetic (no Boolean, no branch on a limb — finding QYV-AUD-002).48struct Sc: Sendable {49    var a0: UInt6450    var a1: UInt6451    var a2: UInt6452    var a3: UInt645354    static let zero = Sc(0, 0, 0, 0)55    static let one = Sc(1, 0, 0, 0)56    /// ℓ57    static let order = Sc(0x5812_631a_5cf5_d3ed, 0x14de_f9de_a2f7_9cd6, 0, 0x1000_0000_0000_0000)5859    @inline(__always) init(_ a0: UInt64, _ a1: UInt64, _ a2: UInt64, _ a3: UInt64) {60        self.a0 = a0; self.a1 = a1; self.a2 = a2; self.a3 = a361    }6263    /// 32 little-endian bytes.64    init(littleEndian b: UnsafePointer<UInt8>) {65        self.init(Endian.loadLE64(b), Endian.loadLE64(b + 8), Endian.loadLE64(b + 16), Endian.loadLE64(b + 24))66    }6768    init(littleEndian b: Bytes) {69        precondition(b.count == 32)70        self = b.withUnsafeBufferPointer { Sc(littleEndian: $0.baseAddress!) }71    }7273    /// 32 bytes, little endian.74    var bytes: Bytes { Endian.le64(a0) + Endian.le64(a1) + Endian.le64(a2) + Endian.le64(a3) }7576    @inline(__always) static func adc(_ x: UInt64, _ y: UInt64, _ carryIn: UInt64) -> (UInt64, UInt64) {77        let s = x &+ y &+ carryIn78        return (s, ((x & y) | ((x | y) & ~s)) >> 63)79    }8081    @inline(__always) static func sbb(_ x: UInt64, _ y: UInt64, _ borrowIn: UInt64) -> (UInt64, UInt64) {82        let d = x &- y &- borrowIn83        return (d, ((~x & y) | ((~x | y) & d)) >> 63)84    }8586    @inline(__always) static func addWide(_ a: Sc, _ b: Sc) -> (Sc, UInt64) {87        let (s0, c0) = adc(a.a0, b.a0, 0)88        let (s1, c1) = adc(a.a1, b.a1, c0)89        let (s2, c2) = adc(a.a2, b.a2, c1)90        let (s3, c3) = adc(a.a3, b.a3, c2)91        return (Sc(s0, s1, s2, s3), c3)92    }9394    @inline(__always) static func subWide(_ a: Sc, _ b: Sc) -> (Sc, UInt64) {95        let (s0, b0) = sbb(a.a0, b.a0, 0)96        let (s1, b1) = sbb(a.a1, b.a1, b0)97        let (s2, b2) = sbb(a.a2, b.a2, b1)98        let (s3, b3) = sbb(a.a3, b.a3, b2)99        return (Sc(s0, s1, s2, s3), b3)100    }101102    @inline(__always) static func select(_ mask: UInt64, _ a: Sc, _ b: Sc) -> Sc {103        Sc((a.a0 & mask) | (b.a0 & ~mask), (a.a1 & mask) | (b.a1 & ~mask),104           (a.a2 & mask) | (b.a2 & ~mask), (a.a3 & mask) | (b.a3 & ~mask))105    }106107    /// a + b mod ℓ for a, b < ℓ (the sum is below 2^254: no carry out of the four limbs).108    @inline(__always) static func addMod(_ a: Sc, _ b: Sc) -> Sc {109        let (s, _) = addWide(a, b)110        let (d, borrow) = subWide(s, order)111        return select(0 &- borrow, s, d)112    }113114    /// True when the value is below ℓ (variable time: used on public signatures only).115    var isCanonical: Bool { Sc.subWide(self, Sc.order).1 == 1 }116117    /// −ℓ⁻¹ mod 2^64118    static let orderInverse: UInt64 = {119        var inv: UInt64 = 1120        for _ in 0..<6 { inv = inv &* (2 &- order.a0 &* inv) }121        return 0 &- inv122    }()123124    /// R² mod ℓ = 2^512 mod ℓ125    static let r2: Sc = {126        var x = Sc.one127        for _ in 0..<512 { x = addMod(x, x) }128        return x129    }()130131    /// t + b·c + carry as (low, high).132    @inline(__always) private static func mac(_ t: UInt64, _ b: UInt64, _ c: UInt64, _ carry: UInt64) -> (UInt64, UInt64) {133        let p = b.multipliedFullWidth(by: c)134        let (l1, c1) = adc(p.low, t, 0)135        let (l2, c2) = adc(l1, carry, 0)136        return (l2, p.high &+ c1 &+ c2)137    }138139    /// Montgomery product a·b·R⁻¹ mod ℓ. Requires a·b < ℓ·2^256, which holds as soon as one operand is below ℓ140    /// (the other may be any value below 2^256). The result is below ℓ.141    static func montMul(_ a: Sc, _ b: Sc) -> Sc {142        let m = order143        let mInv = orderInverse144        var t0: UInt64 = 0, t1: UInt64 = 0, t2: UInt64 = 0, t3: UInt64 = 0, t4: UInt64 = 0145        var bi = b.a0146        for i in 0..<4 {147            var c: UInt64 = 0148            (t0, c) = mac(t0, a.a0, bi, c)149            (t1, c) = mac(t1, a.a1, bi, c)150            (t2, c) = mac(t2, a.a2, bi, c)151            (t3, c) = mac(t3, a.a3, bi, c)152            let (s4, t5) = adc(t4, c, 0)153            let q = t0 &* mInv154            var d: UInt64155            (_, d) = mac(t0, q, m.a0, 0)156            (t0, d) = mac(t1, q, m.a1, d)157            (t1, d) = mac(t2, q, m.a2, d)158            (t2, d) = mac(t3, q, m.a3, d)159            let (s3, c3) = adc(s4, d, 0)160            t3 = s3161            t4 = t5 &+ c3162            // next limb of b: the loop counter is public163            bi = i == 0 ? b.a1 : (i == 1 ? b.a2 : b.a3)164        }165        let t = Sc(t0, t1, t2, t3)166        let (d, borrow) = subWide(t, m)167        // keep t only when the fifth limb is zero and t < ℓ168        let keepT = (0 &- borrow) & ((t4 & 1) &- 1)169        return select(keepT, t, d)170    }171172    /// a mod ℓ for any a below 2^256.173    static func reduce(_ a: Sc) -> Sc { montMul(montMul(a, r2), .one) }174175    /// The 512-bit little-endian integer (64 bytes) reduced modulo ℓ: low + high·2^256.176    static func reduceWide(_ b: Bytes) -> Sc {177        precondition(b.count == 64)178        return b.withUnsafeBufferPointer { p in179            let low = Sc(littleEndian: p.baseAddress!)180            let high = Sc(littleEndian: p.baseAddress! + 32)181            // montMul(high, R²) = high·R mod ℓ182            return addMod(reduce(low), montMul(high, r2))183        }184    }185186    /// a·b + c mod ℓ, for a < ℓ, c < ℓ and any b below 2^256.187    static func mulAdd(_ a: Sc, _ b: Sc, _ c: Sc) -> Sc {188        addMod(montMul(montMul(a, b), r2), c)189    }190}191
Files main
Menu

Theme