Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraMLDSA/MLDSAArithmetic.swift8// Module : Qyvora MLDSA9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//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 Foundation42import QyvoraKeccak43import QyvoraMath4445// FIPS 204 arithmetic layer: the field Z_q with q = 8380417 = 2^23 - 2^13 + 1, the46// number-theoretic transform of section 7.5, the rounding functions of section 7.4, the47// samplers of section 7.3 and the bit packings of section 7.1.48//49// Polynomials are 256 signed 32-bit coefficients; vectors and matrices are flat buffers of50// 256-coefficient blocks. Products use signed Montgomery reduction (R = 2^32). The magnitude51// invariants are stated next to each routine.5253extension MLDSA {54 /// Arithmetic modulo q = 8380417.55 public enum Field {56 public static let q: Int32 = 8_380_41757 /// q^-1 mod 2^32.58 public static let qInverse: Int32 = 58_728_44959 /// Dropped bits of t (d in FIPS 204).60 public static let d: Int32 = 136162 /// Signed Montgomery reduction: for |a| <= 2^31 q returns a 2^-32 mod q in (-q, q).63 @inlinable @inline(__always)64 public static func montgomeryReduce(_ a: Int64) -> Int32 {65 let t = Int32(truncatingIfNeeded: a) &* qInverse66 return Int32(truncatingIfNeeded: (a &- Int64(t) &* 8_380_417) >> 32)67 }6869 /// a b 2^-32 mod q, in (-q, q).70 @inlinable @inline(__always)71 public static func multiply(_ a: Int32, _ b: Int32) -> Int32 {72 montgomeryReduce(Int64(a) &* Int64(b))73 }7475 /// For |a| <= 2^31 - 2^22 - 1 returns a congruent value in [-6283008, 6283008].76 @inlinable @inline(__always)77 public static func reduce32(_ a: Int32) -> Int32 {78 let t = (a &+ (1 << 22)) >> 2379 return a &- t &* 8_380_41780 }8182 /// Adds q to a negative value.83 @inlinable @inline(__always)84 public static func addQIfNegative(_ a: Int32) -> Int32 {85 a &+ ((a >> 31) & 8_380_417)86 }8788 /// Canonical representative in [0, q) of a value in the domain of `reduce32`.89 @inlinable @inline(__always)90 public static func canonical(_ a: Int32) -> Int32 {91 addQIfNegative(reduce32(a))92 }93 }9495 // MARK: - Rounding (FIPS 204, section 7.4)9697 public enum Rounding {98 /// Power2Round (Algorithm 35): r in [0, q) -> (r1, r0) with r = r1 2^13 + r0, r0 in (-2^12, 2^12].99 @inlinable @inline(__always)100 public static func power2Round(_ r: Int32) -> (r1: Int32, r0: Int32) {101 let r1 = (r &+ (1 << 12) &- 1) >> 13102 return (r1, r &- (r1 << 13))103 }104105 /// Decompose (Algorithm 36): r in [0, q) -> (r1, r0) with r = r1 (2 gamma2) + r0,106 /// r0 in (-gamma2, gamma2], and the wrap-around corner r1 = (q-1)/(2 gamma2) folded to107 /// r1 = 0, r0 = r0 - 1. Division-free and branch-free on r.108 @inlinable @inline(__always)109 public static func decompose(_ r: Int32, gamma2: Int32) -> (r1: Int32, r0: Int32) {110 var r1 = (r &+ 127) >> 7111 if gamma2 == 261_888 { // (q - 1) / 32: public parameter112 r1 = (r1 &* 1025 &+ (1 << 21)) >> 22113 r1 &= 15114 } else { // (q - 1) / 88115 r1 = (r1 &* 11275 &+ (1 << 23)) >> 24116 r1 ^= ((43 &- r1) >> 31) & r1117 }118 var r0 = r &- r1 &* 2 &* gamma2119 r0 = r0 &- ((((8_380_417 - 1) / 2 &- r0) >> 31) & 8_380_417)120 return (r1, r0)121 }122123 /// HighBits (Algorithm 37).124 @inlinable public static func highBits(_ r: Int32, gamma2: Int32) -> Int32 { decompose(r, gamma2: gamma2).r1 }125 /// LowBits (Algorithm 38).126 @inlinable public static func lowBits(_ r: Int32, gamma2: Int32) -> Int32 { decompose(r, gamma2: gamma2).r0 }127128 /// MakeHint (Algorithm 39), specification form: z, r in [0, q); true when adding z changes the high bits of r.129 public static func makeHint(_ z: Int32, _ r: Int32, gamma2: Int32) -> Bool {130 var s = r &+ z131 s = s &- (((8_380_417 - 1) &- s) >> 31 & 8_380_417)132 return highBits(r, gamma2: gamma2) != highBits(s, gamma2: gamma2)133 }134135 /// The hint as computed during signing: `low` = LowBits(w) - c s2 + c t0 (centered) and136 /// `high` = HighBits(w). Equivalent to MakeHint(-c t0, w - c s2 + c t0); only evaluated on137 /// a signature candidate that passed every rejection test, so the result is public.138 @inlinable @inline(__always)139 static func makeHint(low a0: Int32, high a1: Int32, gamma2: Int32) -> Int32 {140 (a0 > gamma2 || a0 < -gamma2 || (a0 == -gamma2 && a1 != 0)) ? 1 : 0141 }142143 /// UseHint (Algorithm 40): r in [0, q), public data.144 @inlinable @inline(__always)145 public static func useHint(_ hint: Bool, _ r: Int32, gamma2: Int32) -> Int32 {146 let (r1, r0) = decompose(r, gamma2: gamma2)147 if !hint { return r1 }148 if gamma2 == 261_888 {149 return r0 > 0 ? (r1 &+ 1) & 15 : (r1 &- 1) & 15150 }151 if r0 > 0 { return r1 == 43 ? 0 : r1 &+ 1 }152 return r1 == 0 ? 43 : r1 &- 1153 }154 }155156 // MARK: - NTT (FIPS 204, section 7.5)157158 public enum NTT {159 /// zetas[i] = 1753^BitRev8(i) 2^32 mod q, centered in (-q/2, q/2) (Montgomery form of160 /// the table of FIPS 204, appendix B). Entry 0 is unused.161 public static let zetas: [Int32] = {162 let q: Int64 = 8_380_417163 var out = [Int32](repeating: 0, count: 256)164 for i in 1..<256 {165 var reversed = 0166 for b in 0..<8 { reversed |= ((i >> b) & 1) << (7 - b) }167 var v: Int64 = 1168 for _ in 0..<reversed { v = v * 1753 % q }169 v = (v << 32) % q170 if v > q / 2 { v -= q }171 out[i] = Int32(v)172 }173 return out174 }()175176 /// 2^64 / 256 mod q: final scaling of the inverse transform (result times 2^32).177 @usableFromInline static let inverseScale: Int32 = 41978178 /// 2^64 mod q.179 @usableFromInline static let montgomerySquared: Int32 = 2_365_951180181 /// In-place forward transform (Algorithm 41). No reduction inside: if the input is182 /// bounded by B in absolute value the output is bounded by B + 8q.183 public static func forward(_ a: UnsafeMutablePointer<Int32>) {184 zetas.withUnsafeBufferPointer { table in185 let z = table.baseAddress!186 var k = 0187 var len = 128188 while len > 0 {189 var start = 0190 while start < 256 {191 k &+= 1192 let zeta = z[k]193 var j = start194 let end = start &+ len195 while j < end {196 let t = Field.multiply(zeta, a[j &+ len])197 a[j &+ len] = a[j] &- t198 a[j] = a[j] &+ t199 j &+= 1200 }201 start = end &+ len202 }203 len >>= 1204 }205 }206 }207208 /// In-place inverse transform (Algorithm 42) times 2^32 (cancels the 2^-32 of a209 /// Montgomery pointwise product). Input bounded by q in absolute value (the sums then stay210 /// below 256 q < 2^31); output in (-q, q).211 public static func inverseToMontgomery(_ a: UnsafeMutablePointer<Int32>) {212 zetas.withUnsafeBufferPointer { table in213 let z = table.baseAddress!214 var k = 256215 var len = 1216 while len < 256 {217 var start = 0218 while start < 256 {219 k &-= 1220 let zeta = 0 &- z[k]221 var j = start222 let end = start &+ len223 while j < end {224 let t = a[j]225 a[j] = t &+ a[j &+ len]226 a[j &+ len] = Field.multiply(zeta, t &- a[j &+ len])227 j &+= 1228 }229 start = end &+ len230 }231 len <<= 1232 }233 for j in 0..<256 { a[j] = Field.multiply(inverseScale, a[j]) }234 }235 }236237 /// r (+)= a b 2^-32, coefficient-wise (MultiplyNTT, Algorithm 45, in Montgomery arithmetic).238 @inline(__always)239 static func pointwise(240 _ r: UnsafeMutablePointer<Int32>, _ a: UnsafePointer<Int32>, _ b: UnsafePointer<Int32>, accumulate: Bool241 ) {242 if accumulate {243 for i in 0..<256 { r[i] = r[i] &+ Field.multiply(a[i], b[i]) }244 } else {245 for i in 0..<256 { r[i] = Field.multiply(a[i], b[i]) }246 }247 }248249 @inline(__always)250 static func reduce(_ a: UnsafeMutablePointer<Int32>) {251 for i in 0..<256 { a[i] = Field.reduce32(a[i]) }252 }253254 @inline(__always)255 static func addQIfNegative(_ a: UnsafeMutablePointer<Int32>) {256 for i in 0..<256 { a[i] = Field.addQIfNegative(a[i]) }257 }258259 // Specification-level wrappers (coefficients in [0, q), plain domain) for tests and benchmarks.260261 /// NTT (Algorithm 41) of a polynomial with 256 coefficients in [0, q).262 public static func ntt(_ w: [Int32]) -> [Int32] {263 precondition(w.count == 256)264 var r = w.map { Field.canonical($0) }265 r.withUnsafeMutableBufferPointer { forward($0.baseAddress!) }266 return r.map { Field.canonical($0) }267 }268269 /// NTT^-1 (Algorithm 42).270 public static func inverseNTT(_ w: [Int32]) -> [Int32] {271 precondition(w.count == 256)272 var r = w.map { Field.canonical($0) }273 r.withUnsafeMutableBufferPointer { inverseToMontgomery($0.baseAddress!) }274 return r.map { Field.addQIfNegative(Field.montgomeryReduce(Int64($0))) }275 }276277 /// MultiplyNTT (Algorithm 45).278 public static func multiplyNTT(_ a: [Int32], _ b: [Int32]) -> [Int32] {279 precondition(a.count == 256 && b.count == 256)280 return (0..<256).map {281 let p = Field.multiply(Field.canonical(a[$0]), Field.canonical(b[$0]))282 return Field.addQIfNegative(Field.multiply(p, montgomerySquared))283 }284 }285 }286287 // MARK: - Sampling (FIPS 204, section 7.3)288289 enum Sampling {290 /// RejNTTPoly (Algorithm 30): uniform element of T_q from SHAKE128(rho || s || r). Public input.291 static func rejNTTPoly(rho: Bytes, _ s: UInt8, _ r: UInt8, into a: UnsafeMutablePointer<Int32>) {292 var xof = SHAKE(128)293 xof.absorb(rho)294 xof.absorb([s, r])295 // 840 bytes = 5 blocks = 280 candidates; further blocks keep the 3-byte alignment.296 var buf = Bytes(repeating: 0, count: 840)297 var count = 0298 var length = 840299 while count < 256 {300 buf.withUnsafeMutableBufferPointer { b in301 xof.squeeze(into: UnsafeMutableBufferPointer(rebasing: b[0..<length]))302 var i = 0303 while i < length && count < 256 {304 let t = Int32(b[i]) | Int32(b[i + 1]) << 8 | Int32(b[i + 2] & 0x7f) << 16305 if t < 8_380_417 {306 a[count] = t307 count += 1308 }309 i += 3310 }311 }312 length = 168313 }314 }315316 /// ExpandA (Algorithm 32): k x l matrix in the NTT domain, entry (r, s) at block r l + s.317 static func expandA(rho: Bytes, k: Int, l: Int, into a: UnsafeMutablePointer<Int32>) {318 for r in 0..<k {319 for s in 0..<l {320 rejNTTPoly(rho: rho, UInt8(s), UInt8(r), into: a + (r * l + s) * 256)321 }322 }323 }324325 /// RejBoundedPoly (Algorithm 31): coefficients in [-eta, eta] from SHAKE256(seed || nonce).326 /// The number of rejected candidates is independent of the accepted ones.327 static func rejBoundedPoly(seed: Bytes, nonce: UInt16, eta: Int, into a: UnsafeMutablePointer<Int32>) {328 var xof = SHAKE(256)329 xof.absorb(seed)330 xof.absorb([UInt8(truncatingIfNeeded: nonce), UInt8(truncatingIfNeeded: nonce >> 8)])331 var buf = Bytes(repeating: 0, count: 136)332 var count = 0333 while count < 256 {334 buf.withUnsafeMutableBufferPointer { b in335 xof.squeeze(into: b)336 var i = 0337 while i < 136 && count < 256 {338 var t0 = Int32(b[i] & 0x0f)339 var t1 = Int32(b[i] >> 4)340 if eta == 2 {341 if t0 < 15 {342 t0 = t0 &- ((205 &* t0) >> 10) &* 5343 a[count] = 2 &- t0344 count += 1345 }346 if t1 < 15 && count < 256 {347 t1 = t1 &- ((205 &* t1) >> 10) &* 5348 a[count] = 2 &- t1349 count += 1350 }351 } else {352 if t0 < 9 {353 a[count] = 4 &- t0354 count += 1355 }356 if t1 < 9 && count < 256 {357 a[count] = 4 &- t1358 count += 1359 }360 }361 i += 1362 }363 }364 }365 xof.wipe()366 SecureMemory.zero(&buf)367 }368369 /// One polynomial of ExpandMask (Algorithm 34): coefficients in (-gamma1, gamma1].370 static func expandMaskPoly(seed: Bytes, nonce: UInt16, gamma1Bits: Int, into a: UnsafeMutablePointer<Int32>) {371 var xof = SHAKE(256)372 xof.absorb(seed)373 xof.absorb([UInt8(truncatingIfNeeded: nonce), UInt8(truncatingIfNeeded: nonce >> 8)])374 var buf = xof.squeeze(32 * (gamma1Bits + 1))375 xof.wipe()376 buf.withUnsafeBufferPointer {377 Coding.unpack($0.baseAddress!, count: 256, bits: gamma1Bits + 1, subtractFrom: 1 << Int32(gamma1Bits), into: a)378 }379 SecureMemory.zero(&buf)380 }381382 /// SampleInBall (Algorithm 29): tau coefficients in {-1, 1}, the others zero. Public output.383 static func sampleInBall(seed: Bytes, tau: Int, into c: UnsafeMutablePointer<Int32>) {384 var xof = SHAKE(256)385 xof.absorb(seed)386 var buf = xof.squeeze(136)387 var signs: UInt64 = 0388 for i in 0..<8 { signs |= UInt64(buf[i]) << UInt64(8 * i) }389 var position = 8390 for i in 0..<256 { c[i] = 0 }391 for i in (256 - tau)..<256 {392 var j: Int393 repeat {394 if position == 136 {395 buf = xof.squeeze(136)396 position = 0397 }398 j = Int(buf[position])399 position += 1400 } while j > i401 c[i] = c[j]402 c[j] = 1 &- 2 &* Int32(truncatingIfNeeded: signs & 1)403 signs >>= 1404 }405 }406 }407408 // MARK: - Bit packing (FIPS 204, section 7.1)409410 enum Coding {411 /// SimpleBitPack / BitPack: appends `count` values of `bits` bits. With `subtractFrom` = b,412 /// the packed value is b - coefficient (BitPack(w, a, b)); otherwise the coefficient itself.413 /// The values must lie in [0, 2^bits). No branch depends on a coefficient.414 static func pack(_ src: UnsafePointer<Int32>, count: Int, bits: Int, subtractFrom base: Int32?, into out: inout Bytes) {415 var acc: UInt64 = 0416 var filled = 0417 let mask: UInt64 = (1 << UInt64(bits)) - 1418 for i in 0..<count {419 let v: Int32420 if let base { v = base &- src[i] } else { v = src[i] }421 acc |= (UInt64(UInt32(bitPattern: v)) & mask) << UInt64(filled)422 filled += bits423 while filled >= 8 {424 out.append(UInt8(truncatingIfNeeded: acc))425 acc >>= 8426 filled -= 8427 }428 }429 }430431 /// SimpleBitUnpack / BitUnpack: reads `count` values of `bits` bits; with `subtractFrom` = b432 /// the coefficient is b - value.433 static func unpack(_ src: UnsafePointer<UInt8>, count: Int, bits: Int, subtractFrom base: Int32?, into dst: UnsafeMutablePointer<Int32>) {434 var acc: UInt64 = 0435 var filled = 0436 var o = 0437 let mask: UInt64 = (1 << UInt64(bits)) - 1438 for i in 0..<count {439 while filled < bits {440 acc |= UInt64(src[o]) << UInt64(filled)441 o += 1442 filled += 8443 }444 let v = Int32(truncatingIfNeeded: acc & mask)445 acc >>= UInt64(bits)446 filled -= bits447 if let base { dst[i] = base &- v } else { dst[i] = v }448 }449 }450451 /// HintBitPack (Algorithm 20). `h` holds k polynomials of 0/1 with at most omega ones.452 static func packHint(_ h: UnsafePointer<Int32>, k: Int, omega: Int, into out: inout Bytes) {453 var y = Bytes(repeating: 0, count: omega + k)454 var index = 0455 for i in 0..<k {456 for j in 0..<256 where h[256 * i + j] != 0 {457 y[index] = UInt8(j)458 index += 1459 }460 y[omega + i] = UInt8(index)461 }462 out += y463 }464465 /// HintBitUnpack (Algorithm 21) with every malformed-input check: cumulative counters466 /// non-decreasing and at most omega, positions strictly increasing inside a polynomial,467 /// unused position bytes zero. Returns false on any violation.468 static func unpackHint(_ y: UnsafePointer<UInt8>, k: Int, omega: Int, into h: UnsafeMutablePointer<Int32>) -> Bool {469 for i in 0..<(256 * k) { h[i] = 0 }470 var index = 0471 for i in 0..<k {472 let limit = Int(y[omega + i])473 if limit < index || limit > omega { return false }474 let first = index475 while index < limit {476 if index > first && y[index - 1] >= y[index] { return false }477 h[256 * i + Int(y[index])] = 1478 index += 1479 }480 }481 for i in index..<omega where y[i] != 0 { return false }482 return true483 }484 }485486 /// Scratch memory for secret-dependent polynomials: wiped with `memset_s` before release.487 struct Workspace: ~Copyable {488 let base: UnsafeMutablePointer<Int32>489 let count: Int490491 init(polynomials: Int) {492 count = polynomials * 256493 base = UnsafeMutablePointer<Int32>.allocate(capacity: count)494 base.initialize(repeating: 0, count: count)495 }496497 /// Pointer to polynomial number `index`.498 @inline(__always)499 func poly(_ index: Int) -> UnsafeMutablePointer<Int32> { base + 256 * index }500501 deinit {502 _ = memset_s(base, count * 4, 0, count * 4)503 base.deallocate()504 }505 }506}507