Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraBenchmarks/Catalogue.swift8// Module : Qyvora Benchmarks9// 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 QyvoraCrypto43import Synchronization4445/// Key, signature and ciphertext sizes of one parameter set, in bytes.46public struct ParameterSetSizes: Codable, Sendable, Equatable, Identifiable {47 public let name: String48 public let standard: String49 /// "KEM" or "signature".50 public let kind: String51 /// NIST security category, nil for classical algorithms.52 public let category: Int?53 public let publicKey: Int54 public let privateKey: Int55 /// Ciphertext (KEM) or signature size.56 public let output: Int57 /// Shared secret size (KEM only).58 public let sharedSecret: Int?5960 public var id: String { name }61}6263/// The benchmark suite of the QYVORA engine.64public enum BenchmarkCatalogue {65 /// Size of the buffer used by the throughput benchmarks: 1 MiB.66 public static let bufferSize = 1 << 206768 /// Every benchmark, grouped by family in presentation order.69 public static let all: [Benchmark] = mlkem + mldsa + slhdsa + hashes + symmetric + kdf + ntt + secp256k17071 public static func benchmarks(in family: BenchmarkFamily) -> [Benchmark] {72 all.filter { $0.family == family }73 }7475 /// Sizes of all KEM and signature parameter sets, computed from the engine's parameter sets.76 public static let sizeTable: [ParameterSetSizes] = {77 var table = [ParameterSetSizes]()78 let kemCategory = [1, 3, 5]79 for (i, p) in MLKEM.ParameterSet.allCases.enumerated() {80 table.append(ParameterSetSizes(81 name: p.name, standard: "FIPS 203", kind: "KEM", category: kemCategory[i],82 publicKey: p.publicKeySize, privateKey: p.privateKeySize, output: p.ciphertextSize, sharedSecret: p.sharedSecretSize))83 }84 let dsaCategory = [2, 3, 5]85 for (i, p) in MLDSA.ParameterSet.allCases.enumerated() {86 table.append(ParameterSetSizes(87 name: p.name, standard: "FIPS 204", kind: "signature", category: dsaCategory[i],88 publicKey: p.publicKeySize, privateKey: p.privateKeySize, output: p.signatureSize, sharedSecret: nil))89 }90 for p in SLHDSA.ParameterSet.allCases {91 table.append(ParameterSetSizes(92 name: p.name, standard: "FIPS 205", kind: "signature", category: p.securityCategory,93 publicKey: p.publicKeySize, privateKey: p.secretKeySize, output: p.signatureSize, sharedSecret: nil))94 }95 table.append(ParameterSetSizes(96 name: "secp256k1 ECDSA", standard: "SEC 2 / RFC 6979", kind: "signature", category: nil,97 publicKey: 33, privateKey: 32, output: 64, sharedSecret: nil))98 table.append(ParameterSetSizes(99 name: "secp256k1 Schnorr", standard: "BIP-340", kind: "signature", category: nil,100 publicKey: 32, privateKey: 32, output: 64, sharedSecret: nil))101 return table102 }()103104 // MARK: - Helpers105106 /// Deterministic filler bytes (xorshift64*); benchmarks never draw from the system generator,107 /// so two runs measure exactly the same inputs.108 static func pattern(_ count: Int, seed: UInt64) -> Bytes {109 var state = seed &* 0x9E37_79B9_7F4A_7C15 | 1110 var out = Bytes(repeating: 0, count: count)111 out.withUnsafeMutableBufferPointer { buffer in112 var i = 0113 while i < count {114 state ^= state >> 12115 state ^= state << 25116 state ^= state >> 27117 var word = state &* 0x2545_F491_4F6C_DD1D118 var j = 0119 while j < 8, i < count {120 buffer[i] = UInt8(truncatingIfNeeded: word)121 word >>= 8122 i += 1123 j += 1124 }125 }126 }127 return out128 }129130 static func slug(_ text: String) -> String {131 var out = ""132 for ch in text.lowercased() {133 if ch.isLetter || ch.isNumber {134 out.append(ch)135 } else if ch == " " || ch == "-" || ch == "/" || ch == "[" {136 if !out.hasSuffix("-") { out.append("-") }137 }138 }139 while out.hasSuffix("-") { out.removeLast() }140 return out141 }142143 static func make(144 _ family: BenchmarkFamily, _ algorithm: String, _ operation: String,145 metric: BenchmarkMetric = .time, units: Double = 1, unitLabel: String? = nil,146 sizes: BenchmarkSizes? = nil, cost: BenchmarkCost = .standard,147 prepare: @escaping @Sendable () throws -> BenchmarkBody148 ) -> Benchmark {149 Benchmark(150 id: "\(slug(algorithm)).\(slug(operation))", family: family, algorithm: algorithm, operation: operation,151 metric: metric, unitsPerOperation: units, unitLabel: unitLabel, sizes: sizes, cost: cost, prepare: prepare)152 }153154 /// Keys and signatures shared by the benchmarks of one parameter set, so that the seconds-long155 /// SLH-DSA key generations and signatures needed as inputs are computed once per process.156 private static let fixtures = Mutex<[String: [Bytes]]>([:])157158 static func fixture(_ key: String, _ compute: () throws -> [Bytes]) throws -> [Bytes] {159 if let cached = fixtures.withLock({ $0[key] }) { return cached }160 let value = try compute()161 fixtures.withLock { $0[key] = value }162 return value163 }164165 static let message = pattern(64, seed: 0x51)166167 /// Message whose first 8 bytes are a counter: makes consecutive signatures differ.168 static func counterMessage(_ counter: UInt64) -> Bytes {169 var m = message170 for i in 0..<8 { m[i] = UInt8(truncatingIfNeeded: counter >> (8 * UInt64(i))) }171 return m172 }173174 // MARK: - ML-KEM175176 static let mlkem: [Benchmark] = MLKEM.ParameterSet.allCases.flatMap { p -> [Benchmark] in177 let sizes = BenchmarkSizes(178 publicKey: p.publicKeySize, privateKey: p.privateKeySize, output: p.ciphertextSize, outputLabel: "ciphertext")179 let d = pattern(32, seed: 1), z = pattern(32, seed: 2), m = pattern(32, seed: 3)180 let keys: @Sendable () throws -> [Bytes] = {181 try fixture("mlkem.\(p.name)") {182 let pair = try MLKEM.keyGenInternal(p, d: d, z: z)183 let enc = try MLKEM.encapsInternal(p, encapsulationKey: pair.encapsulationKey, m: m)184 return [pair.encapsulationKey, pair.decapsulationKey, enc.ciphertext]185 }186 }187 return [188 make(.mlkem, p.name, "keygen", sizes: sizes) {189 { BlackBox.consume(try MLKEM.keyGenInternal(p, d: d, z: z).encapsulationKey) }190 },191 make(.mlkem, p.name, "encaps", sizes: sizes) {192 let ek = try keys()[0]193 return { BlackBox.consume(try MLKEM.encapsInternal(p, encapsulationKey: ek, m: m).ciphertext) }194 },195 make(.mlkem, p.name, "decaps", sizes: sizes) {196 let k = try keys()197 return { BlackBox.consume(try MLKEM.decapsInternal(p, decapsulationKey: k[1], ciphertext: k[2])) }198 },199 ]200 }201202 // MARK: - ML-DSA203204 static let mldsa: [Benchmark] = MLDSA.ParameterSet.allCases.flatMap { p -> [Benchmark] in205 let sizes = BenchmarkSizes(206 publicKey: p.publicKeySize, privateKey: p.privateKeySize, output: p.signatureSize, outputLabel: "signature")207 let seed = pattern(32, seed: 4)208 let keys: @Sendable () throws -> [Bytes] = {209 try fixture("mldsa.\(p.name)") {210 let pair = try MLDSA.keyGenInternal(p, seed: seed)211 let signature = try MLDSA.sign(p, privateKey: pair.privateKey, message: message, randomness: .deterministic)212 return [pair.publicKey, pair.privateKey, signature]213 }214 }215 return [216 make(.mldsa, p.name, "keygen", sizes: sizes) {217 { BlackBox.consume(try MLDSA.keyGenInternal(p, seed: seed).publicKey) }218 },219 // The message changes at every call: the number of rejection-sampling rounds of ML-DSA220 // depends on it, so the samples spread and the mean is the representative figure.221 make(.mldsa, p.name, "sign", sizes: sizes) {222 let sk = try keys()[1]223 var counter: UInt64 = 0224 return {225 counter &+= 1226 BlackBox.consume(try MLDSA.sign(p, privateKey: sk, message: counterMessage(counter), randomness: .deterministic))227 }228 },229 make(.mldsa, p.name, "verify", sizes: sizes) {230 let k = try keys()231 return { BlackBox.consume(MLDSA.verify(p, publicKey: k[0], message: message, signature: k[2])) }232 },233 ]234 }235236 // MARK: - SLH-DSA237238 static let slhdsa: [Benchmark] = SLHDSA.ParameterSet.allCases.flatMap { p -> [Benchmark] in239 let sizes = BenchmarkSizes(240 publicKey: p.publicKeySize, privateKey: p.secretKeySize, output: p.signatureSize, outputLabel: "signature")241 let n = p.n242 let skSeed = pattern(n, seed: 5), skPrf = pattern(n, seed: 6), pkSeed = pattern(n, seed: 7)243 // The "s" (small signature) sets pay for their size with seconds-long signatures.244 let small = p.name.hasSuffix("s")245 let keys: @Sendable () throws -> [Bytes] = {246 try fixture("slhdsa.\(p.name)") {247 let pair = try SLHDSA.keyGenInternal(p, skSeed: skSeed, skPrf: skPrf, pkSeed: pkSeed)248 let signature = try SLHDSA.sign(p, message: message, secretKey: pair.secretKey, randomization: .deterministic)249 return [pair.publicKey, pair.secretKey, signature]250 }251 }252 return [253 make(.slhdsa, p.name, "keygen", sizes: sizes, cost: small ? .slow : .standard) {254 { BlackBox.consume(try SLHDSA.keyGenInternal(p, skSeed: skSeed, skPrf: skPrf, pkSeed: pkSeed).publicKey) }255 },256 make(.slhdsa, p.name, "sign", sizes: sizes, cost: .slow) {257 let sk = try keys()[1]258 var counter: UInt64 = 0259 return {260 counter &+= 1261 BlackBox.consume(262 try SLHDSA.sign(p, message: counterMessage(counter), secretKey: sk, randomization: .deterministic))263 }264 },265 make(.slhdsa, p.name, "verify", sizes: sizes) {266 let k = try keys()267 return { BlackBox.consume(SLHDSA.verify(p, message: message, signature: k[2], publicKey: k[0])) }268 },269 ]270 }271272 // MARK: - Hashes273274 private static func throughput(275 _ family: BenchmarkFamily, _ algorithm: String, _ operation: String = "1 MiB",276 _ hash: @escaping @Sendable (Bytes) -> Bytes277 ) -> Benchmark {278 make(family, algorithm, operation, metric: .throughput, units: Double(bufferSize)) {279 let data = pattern(bufferSize, seed: 8)280 return { BlackBox.consume(hash(data)) }281 }282 }283284 static let hashes: [Benchmark] = [285 throughput(.hash, "SHA-256") { SHA256.hash($0) },286 throughput(.hash, "SHA-512") { SHA512.hash($0) },287 throughput(.hash, "SHA3-256") { SHA3.sha3_256($0) },288 throughput(.hash, "SHA3-512") { SHA3.sha3_512($0) },289 throughput(.hash, "SHAKE128") { SHAKE.shake128($0, outputLength: 32) },290 throughput(.hash, "SHAKE256") { SHAKE.shake256($0, outputLength: 64) },291 throughput(.hash, "Keccak-256") { SHA3.keccak256($0) },292 throughput(.hash, "RIPEMD-160") { RIPEMD160.hash($0) },293 throughput(.hash, "BLAKE2b-512") { BLAKE2b.hash($0) },294 make(.hash, "Keccak-f[1600]", "permutation", metric: .rate, units: 64, unitLabel: "permutation") {295 let state = Scratch<UInt64>(count: 25)296 for i in 0..<25 { state.pointer[i] = UInt64(i) &* 0x0101_0101_0101_0101 }297 return {298 let s = state.pointer299 for _ in 0..<64 { KeccakF1600.permute(s) }300 BlackBox.consume(s[0])301 }302 },303 ]304305 // MARK: - Symmetric306307 static let symmetric: [Benchmark] = {308 let key = pattern(32, seed: 9), nonce = pattern(12, seed: 10), aad = pattern(16, seed: 11)309 let size = Double(bufferSize)310 return [311 make(.symmetric, "AES-256-GCM", "seal 1 MiB", metric: .throughput, units: size) {312 let data = pattern(bufferSize, seed: 12)313 return { BlackBox.consume(try AES256GCM.seal(key: key, nonce: nonce, plaintext: data, associatedData: aad).tag) }314 },315 make(.symmetric, "AES-256-GCM", "open 1 MiB", metric: .throughput, units: size) {316 let sealed = try AES256GCM.seal(key: key, nonce: nonce, plaintext: pattern(bufferSize, seed: 12), associatedData: aad)317 return {318 BlackBox.consume(319 try AES256GCM.open(key: key, nonce: nonce, ciphertext: sealed.ciphertext, tag: sealed.tag, associatedData: aad))320 }321 },322 make(.symmetric, "ChaCha20-Poly1305", "seal 1 MiB", metric: .throughput, units: size) {323 let data = pattern(bufferSize, seed: 12)324 return {325 BlackBox.consume(try ChaCha20Poly1305.seal(key: key, nonce: nonce, plaintext: data, associatedData: aad).tag)326 }327 },328 make(.symmetric, "ChaCha20-Poly1305", "open 1 MiB", metric: .throughput, units: size) {329 let sealed = try ChaCha20Poly1305.seal(330 key: key, nonce: nonce, plaintext: pattern(bufferSize, seed: 12), associatedData: aad)331 return {332 BlackBox.consume(333 try ChaCha20Poly1305.open(334 key: key, nonce: nonce, ciphertext: sealed.ciphertext, tag: sealed.tag, associatedData: aad))335 }336 },337 throughput(.symmetric, "HMAC-SHA256") { HMAC<SHA256>.authenticate(key: key, message: $0) },338 make(.symmetric, "HMAC-SHA256", "64-byte message") {339 { BlackBox.consume(HMAC<SHA256>.authenticate(key: key, message: message)) }340 },341 make(.symmetric, "HKDF-SHA256", "derive 32 bytes") {342 let salt = pattern(32, seed: 13), info = pattern(16, seed: 14)343 return { BlackBox.consume(HKDF<SHA256>.deriveKey(inputKeyMaterial: key, salt: salt, info: info, length: 32) ?? []) }344 },345 ]346 }()347348 // MARK: - Key derivation349350 static let kdf: [Benchmark] = {351 let mnemonic = Bytes("legal winner thank year wave sausage worth useful legal winner thank yellow".utf8)352 let salt = Bytes("mnemonic".utf8)353 let argonSalt = pattern(16, seed: 15)354 return [355 make(.kdf, "PBKDF2-HMAC-SHA512", "2048 iterations (BIP-39)") {356 { BlackBox.consume(PBKDF2<SHA512>.deriveKey(password: mnemonic, salt: salt, iterations: 2048, length: 64)) }357 },358 make(.kdf, "Argon2id", "19 MiB t=2 p=1", cost: .slow) {359 let parameters = Argon2.Parameters(memoryKiB: 19 * 1024, iterations: 2, parallelism: 1)360 return { BlackBox.consume(try Argon2.id(password: mnemonic, salt: argonSalt, parameters: parameters)) }361 },362 make(.kdf, "Argon2id", "64 MiB t=3 p=4", cost: .slow) {363 let parameters = Argon2.Parameters(memoryKiB: 64 * 1024, iterations: 3, parallelism: 4)364 return { BlackBox.consume(try Argon2.id(password: mnemonic, salt: argonSalt, parameters: parameters)) }365 },366 ]367 }()368369 // MARK: - NTT370371 /// Transforms per call of the body. Each transform runs on a fresh copy of the same input372 /// (the transforms are in place and their bounds do not allow chaining), so the figure includes373 /// one 256-coefficient copy per transform.374 static let transformsPerOperation = 32375376 static let ntt: [Benchmark] = {377 let count = transformsPerOperation378 func kem(_ operation: String, _ transform: @escaping @Sendable (UnsafeMutablePointer<Int16>) -> Void) -> Benchmark {379 make(.ntt, "ML-KEM NTT", operation, metric: .timePerItem, units: Double(count), unitLabel: "transform") {380 let input = Scratch<Int16>(count: 256), work = Scratch<Int16>(count: 256)381 for i in 0..<256 { input.pointer[i] = Int16((i * 2731 + 17) % 3329) }382 return {383 let source = input.pointer, p = work.pointer384 var fold: UInt64 = 0385 for round in 0..<count {386 p.update(from: source, count: 256)387 transform(p)388 fold &+= UInt64(truncatingIfNeeded: p[(round &* 37) & 255])389 }390 BlackBox.consume(fold)391 }392 }393 }394 func dsa(_ operation: String, _ transform: @escaping @Sendable (UnsafeMutablePointer<Int32>) -> Void) -> Benchmark {395 make(.ntt, "ML-DSA NTT", operation, metric: .timePerItem, units: Double(count), unitLabel: "transform") {396 let input = Scratch<Int32>(count: 256), work = Scratch<Int32>(count: 256)397 for i in 0..<256 { input.pointer[i] = Int32((i * 7_340_033 + 12_345) % 8_380_417) }398 return {399 let source = input.pointer, p = work.pointer400 var fold: UInt64 = 0401 for round in 0..<count {402 p.update(from: source, count: 256)403 transform(p)404 fold &+= UInt64(truncatingIfNeeded: p[(round &* 37) & 255])405 }406 BlackBox.consume(fold)407 }408 }409 }410 return [411 kem("forward") { MLKEM.NTT.forward($0) },412 kem("inverse") { MLKEM.NTT.inverseToMontgomery($0) },413 dsa("forward") { MLDSA.NTT.forward($0) },414 dsa("inverse") { MLDSA.NTT.inverseToMontgomery($0) },415 ]416 }()417418 // MARK: - secp256k1419420 static let secp256k1: [Benchmark] = {421 var privateKey = pattern(32, seed: 16)422 privateKey[0] = 0x12423 let sk = privateKey424 let digest = pattern(32, seed: 17)425 let aux = Bytes(repeating: 0, count: 32)426 let ecdsa = BenchmarkSizes(publicKey: 33, privateKey: 32, output: 64, outputLabel: "signature")427 let schnorr = BenchmarkSizes(publicKey: 32, privateKey: 32, output: 64, outputLabel: "signature")428 return [429 make(.secp256k1, "secp256k1", "public key", sizes: ecdsa) {430 { BlackBox.consume(try Secp256k1.publicKey(privateKey: sk)) }431 },432 make(.secp256k1, "secp256k1 ECDSA", "sign", sizes: ecdsa) {433 { BlackBox.consume(try Secp256k1.sign(digest: digest, privateKey: sk).compact) }434 },435 make(.secp256k1, "secp256k1 ECDSA", "verify", sizes: ecdsa) {436 let publicKey = try Secp256k1.publicKey(privateKey: sk)437 let signature = try Secp256k1.sign(digest: digest, privateKey: sk)438 return { BlackBox.consume(Secp256k1.verify(compactSignature: signature.compact, digest: digest, publicKey: publicKey)) }439 },440 make(.secp256k1, "secp256k1 ECDSA", "recover", sizes: ecdsa) {441 let signature = try Secp256k1.sign(digest: digest, privateKey: sk)442 return {443 BlackBox.consume(444 try Secp256k1.recoverPublicKey(445 compactSignature: signature.compact, recoveryID: signature.recoveryID, digest: digest))446 }447 },448 make(.secp256k1, "secp256k1 Schnorr", "sign", sizes: schnorr) {449 { BlackBox.consume(try Secp256k1.schnorrSign(message: digest, privateKey: sk, auxRand: aux)) }450 },451 make(.secp256k1, "secp256k1 Schnorr", "verify", sizes: schnorr) {452 let publicKey = try Secp256k1.xOnlyPublicKey(privateKey: sk)453 let signature = try Secp256k1.schnorrSign(message: digest, privateKey: sk, auxRand: aux)454 return { BlackBox.consume(Secp256k1.schnorrVerify(signature: signature, message: digest, publicKey: publicKey)) }455 },456 ]457 }()458}459460/// Heap buffer owned by a benchmark body (freed with the closure that captures it).461final class Scratch<T: FixedWidthInteger> {462 let pointer: UnsafeMutablePointer<T>463 let count: Int464465 init(count: Int) {466 self.count = count467 pointer = .allocate(capacity: count)468 pointer.initialize(repeating: 0, count: count)469 }470471 deinit { pointer.deallocate() }472}473