Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraEd25519/Edwards25519.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/// Point of the twisted Edwards curve −x² + y² = 1 + d·x²·y² over GF(2^255 − 19), in extended homogeneous44/// coordinates (X : Y : Z : T) with x = X/Z, y = Y/Z, x·y = T/Z (RFC 8032 §5.1.4).45///46/// The addition formula is the unified one of RFC 8032: it is complete on this curve (a = −1 is a square and d is47/// not), so the same sequence of field operations adds any two points, doubles, and handles the neutral element —48/// there is no special case, hence no branch.49struct EdPoint: Sendable {50 var x: Fe51 var y: Fe52 var z: Fe53 var t: Fe5455 static let identity = EdPoint(x: .zero, y: .one, z: .one, t: .zero)5657 /// The base point B: y = 4/5, x non-negative (RFC 8032 §5.1).58 static let base: EdPoint = {59 var encoding = Bytes(repeating: 0x66, count: 32)60 encoding[0] = 0x5861 return EdPoint.decode(encoding, strict: true)!62 }()6364 /// 1·B … 16·B: the window value w selects (w + 1)·B, so that the multiplication of the base point — the only65 /// scalar multiplication made with secret scalars — never adds the neutral element (see `multiplyBase`).66 static let baseTable: [EdPoint] = {67 var out = [EdPoint]()68 out.reserveCapacity(16)69 var p = base70 for _ in 0..<16 {71 out.append(p)72 p = add(p, base)73 }74 return out75 }()7677 /// −[c]B with c = (16^64 − 1) / 15 = 0x1111…11: the excess of the 64 offset windows of `multiplyBase`.78 /// A public constant, computed once with the general multiplication.79 static let baseOffset: EdPoint = negate(multiply(scalar: Bytes(repeating: 0x11, count: 32), base))8081 static func add(_ p: EdPoint, _ q: EdPoint) -> EdPoint {82 let a = Fe.mul(Fe.sub(p.y, p.x), Fe.sub(q.y, q.x))83 let b = Fe.mul(Fe.add(p.y, p.x), Fe.add(q.y, q.x))84 let c = Fe.mul(Fe.mul(p.t, Fe.d2), q.t)85 let zz = Fe.mul(p.z, q.z)86 let d = Fe.add(zz, zz)87 let e = Fe.sub(b, a)88 let f = Fe.sub(d, c)89 let g = Fe.add(d, c)90 let h = Fe.add(b, a)91 return EdPoint(x: Fe.mul(e, f), y: Fe.mul(g, h), z: Fe.mul(f, g), t: Fe.mul(e, h))92 }9394 static func double(_ p: EdPoint) -> EdPoint {95 let a = Fe.square(p.x)96 let b = Fe.square(p.y)97 let zz = Fe.square(p.z)98 let c = Fe.add(zz, zz)99 let h = Fe.add(a, b)100 let e = Fe.sub(h, Fe.square(Fe.add(p.x, p.y)))101 let g = Fe.sub(a, b)102 let f = Fe.add(c, g)103 return EdPoint(x: Fe.mul(e, f), y: Fe.mul(g, h), z: Fe.mul(f, g), t: Fe.mul(e, h))104 }105106 static func negate(_ p: EdPoint) -> EdPoint {107 EdPoint(x: Fe.neg(p.x), y: p.y, z: p.z, t: Fe.neg(p.t))108 }109110 @inline(__always) static func select(_ mask: UInt64, _ a: EdPoint, _ b: EdPoint) -> EdPoint {111 EdPoint(x: Fe.select(mask, a.x, b.x), y: Fe.select(mask, a.y, b.y), z: Fe.select(mask, a.z, b.z), t: Fe.select(mask, a.t, b.t))112 }113114 /// 0·P, 1·P, … 15·P.115 static func table(of p: EdPoint) -> [EdPoint] {116 var out = [EdPoint](repeating: .identity, count: 16)117 for i in 1..<16 { out[i] = add(out[i - 1], p) }118 return out119 }120121 /// Entry `index` (0…15) of a 16-entry table, read by scanning every entry under a mask: the memory access122 /// pattern does not depend on the index.123 @inline(__always) static func lookup(_ table: UnsafePointer<EdPoint>, _ index: UInt64) -> EdPoint {124 var r = EdPoint(x: .zero, y: .zero, z: .zero, t: .zero)125 for j in 0..<16 {126 let diff = UInt64(truncatingIfNeeded: j) ^ index127 // diff < 16: (diff − 1) has its top bit set exactly when diff = 0128 let mask = 0 &- ((diff &- 1) >> 63)129 let e = table[j]130 r.x.l0 |= e.x.l0 & mask; r.x.l1 |= e.x.l1 & mask; r.x.l2 |= e.x.l2 & mask; r.x.l3 |= e.x.l3 & mask; r.x.l4 |= e.x.l4 & mask131 r.y.l0 |= e.y.l0 & mask; r.y.l1 |= e.y.l1 & mask; r.y.l2 |= e.y.l2 & mask; r.y.l3 |= e.y.l3 & mask; r.y.l4 |= e.y.l4 & mask132 r.z.l0 |= e.z.l0 & mask; r.z.l1 |= e.z.l1 & mask; r.z.l2 |= e.z.l2 & mask; r.z.l3 |= e.z.l3 & mask; r.z.l4 |= e.z.l4 & mask133 r.t.l0 |= e.t.l0 & mask; r.t.l1 |= e.t.l1 & mask; r.t.l2 |= e.t.l2 & mask; r.t.l3 |= e.t.l3 & mask; r.t.l4 |= e.t.l4 & mask134 }135 return r136 }137138 /// Σ table[wᵢ]·16ⁱ over the 64 four-bit windows wᵢ of a 256-bit little-endian scalar (32 bytes): scalar · P for139 /// the table 0·P … 15·P.140 ///141 /// Fixed 4-bit windows, most significant first: 64 iterations of four doublings, one masked table lookup and one142 /// complete addition, whatever the scalar. No branch and no memory index depends on the scalar.143 static func multiply(scalar: Bytes, table: [EdPoint]) -> EdPoint {144 precondition(scalar.count == 32 && table.count == 16)145 return scalar.withUnsafeBufferPointer { s in146 table.withUnsafeBufferPointer { t in147 var acc = EdPoint.identity148 var i = 63149 while i >= 0 {150 acc = double(double(double(double(acc))))151 let byte = UInt64(s[i >> 1])152 let nibble = (byte >> UInt64((i & 1) << 2)) & 15153 acc = add(acc, lookup(t.baseAddress!, nibble))154 i -= 1155 }156 return acc157 }158 }159 }160161 /// scalar · B, for any 256-bit scalar.162 ///163 /// The same fixed-window loop as `multiply(scalar:table:)`, on a table shifted by one: the window value w adds164 /// (w + 1)·B, and the constant excess [c]B, c = 0x1111…11, is removed by one last addition. For every scalar the165 /// 64 windows therefore add a point of the prime-order subgroup that is not the neutral element, and the166 /// accumulator leaves the neutral element at the first window: the degenerate scalars (0, 1, a power of two)167 /// process the same kind of values as any other (QYV-AUD-006: with the plain table their windows added the168 /// neutral element, and the duration of the multiplication was measurably different from that of random scalars).169 static func multiplyBase(scalar: Bytes) -> EdPoint {170 add(multiply(scalar: scalar, table: baseTable), baseOffset)171 }172173 /// scalar · P.174 static func multiply(scalar: Bytes, _ p: EdPoint) -> EdPoint { multiply(scalar: scalar, table: table(of: p)) }175176 /// 32-byte encoding of RFC 8032 §5.1.2: y little endian, with the sign of x in the top bit.177 func encode() -> Bytes {178 let zInv = Fe.invert(z)179 let ax = Fe.mul(x, zInv)180 var out = Fe.mul(y, zInv).toBytes()181 out[31] |= UInt8(truncatingIfNeeded: ax.isNegative << 7)182 return out183 }184185 /// Decoding of RFC 8032 §5.1.3. Public data only (variable time).186 ///187 /// `strict` applies the RFC rules: y must be canonical (below p) and the encoding "x = 0 with the sign bit set"188 /// is refused. Without `strict` the decoding is the lenient one of curve25519-dalek, on which Solana's189 /// `is_on_curve` is defined: y is taken modulo p and the sign bit of x = 0 is ignored.190 static func decode(_ bytes: Bytes, strict: Bool) -> EdPoint? {191 guard bytes.count == 32 else { return nil }192 let y = Fe.fromBytes(bytes)193 if strict {194 var canonical = y.toBytes()195 canonical[31] |= bytes[31] & 0x80196 guard canonical == bytes else { return nil }197 }198 let yy = Fe.square(y)199 let u = Fe.sub(yy, .one)200 let v = Fe.add(Fe.mul(yy, Fe.d), .one)201 let (isSquare, root) = Fe.sqrtRatio(u, v)202 guard isSquare != 0 else { return nil }203 let sign = UInt64(bytes[31] >> 7)204 if strict, root.isZeroMask != 0, sign == 1 { return nil }205 let x = root.isNegative == sign ? root : Fe.neg(root)206 return EdPoint(x: x, y: y, z: .one, t: Fe.mul(x, y))207 }208209 /// True when the point is the neutral element (variable time).210 var isIdentity: Bool { x.isZeroMask != 0 && Fe.equalMask(y, z) != 0 }211212 /// True when 8·P is the neutral element: P is one of the eight points of the torsion subgroup (variable time).213 var isSmallOrder: Bool { EdPoint.double(EdPoint.double(EdPoint.double(self))).isIdentity }214215 /// Projective equality (variable time).216 static func equal(_ p: EdPoint, _ q: EdPoint) -> Bool {217 Fe.equalMask(Fe.mul(p.x, q.z), Fe.mul(q.x, p.z)) != 0 && Fe.equalMask(Fe.mul(p.y, q.z), Fe.mul(q.y, p.z)) != 0218 }219220 /// True when the coordinates satisfy the curve equation and T·Z = X·Y (used by the tests).221 var isValid: Bool {222 let xx = Fe.square(x), yy = Fe.square(y), zz = Fe.square(z)223 let left = Fe.mul(Fe.sub(yy, xx), zz)224 let right = Fe.add(Fe.square(zz), Fe.mul(Fe.d, Fe.mul(xx, yy)))225 return Fe.equalMask(left, right) != 0 && Fe.equalMask(Fe.mul(t, z), Fe.mul(x, y)) != 0226 }227}228