SPB Git

Repository Public

Core.swift 16.8 KB 386 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSLHDSA/Core.swift8// Module           : Qyvora SLHDSA9// 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 QyvoraMath4344/// base_2b (FIPS 205, Algorithm 4): the first `outLen` base-2^b digits of the byte string `x`.45/// Requires `x.count >= ceil(outLen · b / 8)` and `b <= 32`.46func base2b(_ x: UnsafeBufferPointer<UInt8>, b: Int, outLen: Int) -> [UInt32] {47    precondition(b >= 1 && b <= 32 && x.count * 8 >= outLen * b)48    var out = [UInt32](repeating: 0, count: outLen)49    var index = 050    var bits = 051    var total: UInt64 = 052    let mask: UInt64 = (1 << UInt64(b)) - 153    for i in 0..<outLen {54        while bits < b {55            total = (total << 8) | UInt64(x[index])56            index += 157            bits += 858        }59        bits -= b60        out[i] = UInt32(truncatingIfNeeded: (total >> UInt64(bits)) & mask)61    }62    return out63}6465func base2b(_ x: Bytes, b: Int, outLen: Int) -> [UInt32] {66    x.withUnsafeBufferPointer { base2b($0, b: b, outLen: outLen) }67}6869/// WOTS+, XMSS, hypertree and FORS (FIPS 205, sections 5 to 8) for one parameter set and one `PK.seed`.70///71/// All node values live in caller-provided flat buffers of n-byte cells. Signing computes whole trees72/// (every leaf, then the levels bottom-up) instead of the recursive `xmss_node` / `fors_node` of the73/// standard: the values are identical, and the leaves, which carry almost all the cost, can be computed74/// on several cores. The result does not depend on scheduling: each task writes only its own cells.75struct Core: Sendable {76    let p: SLHDSA.Params77    let th: TweakHash7879    init(_ p: SLHDSA.Params, pkSeed: UnsafePointer<UInt8>) {80        self.p = p81        self.th = TweakHash(p, pkSeed: pkSeed)82    }8384    // MARK: WOTS+ (section 5)8586    /// chain (Algorithm 5): applies F `steps` times starting at hash address `start`, in place.87    @inline(__always)88    func chain(_ x: UnsafeMutablePointer<UInt8>, start: UInt32, steps: UInt32, _ adrs: inout ADRS) {89        var j = start90        let end = start &+ steps91        while j < end {92            adrs.setHashAddress(j)93            th.F(adrs, x, x)94            j &+= 195        }96    }9798    /// The `len` base-w digits signed by WOTS+: the message digits followed by the checksum digits99    /// (Algorithm 7, lines 1 to 7; identical in Algorithm 8).100    func wotsDigits(_ message: UnsafePointer<UInt8>) -> [UInt32] {101        var digits = base2b(UnsafeBufferPointer(start: message, count: p.n), b: p.lgw, outLen: p.len1)102        var csum: UInt32 = 0103        for d in digits { csum += UInt32(p.w - 1) - d }104        csum <<= UInt32((8 - ((p.len2 * p.lgw) % 8)) % 8)105        let csumLen = (p.len2 * p.lgw + 7) / 8106        var csumBytes = Bytes(repeating: 0, count: csumLen)107        for i in 0..<csumLen { csumBytes[csumLen - 1 - i] = UInt8(truncatingIfNeeded: csum >> UInt32(8 * i)) }108        digits.append(contentsOf: base2b(csumBytes, b: p.lgw, outLen: p.len2))109        return digits110    }111112    /// wots_pkGen (Algorithm 6). `adrs` carries layer, tree, type WOTS_HASH and the key pair address.113    func wotsPkGen(skSeed: UnsafePointer<UInt8>, _ adrs: ADRS, _ out: UnsafeMutablePointer<UInt8>) {114        let n = p.n, len = p.len115        var skADRS = adrs116        skADRS.setTypeAndClear(.wotsPRF)117        skADRS.setKeyPairAddress(adrs.getKeyPairAddress())118        var a = adrs119        withUnsafeTemporaryAllocation(of: UInt8.self, capacity: len * n) { tmp in120            let t = tmp.baseAddress!121            for i in 0..<len {122                skADRS.setChainAddress(UInt32(i))123                th.PRF(skADRS, skSeed, t + i * n)124                a.setChainAddress(UInt32(i))125                chain(t + i * n, start: 0, steps: UInt32(p.w - 1), &a)126            }127            var pkADRS = adrs128            pkADRS.setTypeAndClear(.wotsPK)129            pkADRS.setKeyPairAddress(adrs.getKeyPairAddress())130            th.T(pkADRS, t, len * n, out)131        }132    }133134    /// wots_sign (Algorithm 7): writes `len · n` bytes at `out`.135    func wotsSign(_ message: UnsafePointer<UInt8>, skSeed: UnsafePointer<UInt8>, _ adrs: ADRS, _ out: UnsafeMutablePointer<UInt8>) {136        let n = p.n137        let digits = wotsDigits(message)138        var skADRS = adrs139        skADRS.setTypeAndClear(.wotsPRF)140        skADRS.setKeyPairAddress(adrs.getKeyPairAddress())141        var a = adrs142        for i in 0..<p.len {143            skADRS.setChainAddress(UInt32(i))144            th.PRF(skADRS, skSeed, out + i * n)145            a.setChainAddress(UInt32(i))146            chain(out + i * n, start: 0, steps: digits[i], &a)147        }148    }149150    /// wots_pkFromSig (Algorithm 8).151    func wotsPkFromSig(_ sig: UnsafePointer<UInt8>, _ message: UnsafePointer<UInt8>, _ adrs: ADRS, _ out: UnsafeMutablePointer<UInt8>) {152        let n = p.n, len = p.len153        let digits = wotsDigits(message)154        var a = adrs155        withUnsafeTemporaryAllocation(of: UInt8.self, capacity: len * n) { tmp in156            let t = tmp.baseAddress!157            t.update(from: sig, count: len * n)158            for i in 0..<len {159                a.setChainAddress(UInt32(i))160                chain(t + i * n, start: digits[i], steps: UInt32(p.w - 1) - digits[i], &a)161            }162            var pkADRS = adrs163            pkADRS.setTypeAndClear(.wotsPK)164            pkADRS.setKeyPairAddress(adrs.getKeyPairAddress())165            th.T(pkADRS, t, len * n, out)166        }167    }168169    // MARK: Merkle trees170171    /// Reduces the `2^height` leaves at `nodes` to their root, in place, with H.172    ///173    /// `adrs` is the tree address template (type TREE or FORS_TREE, key pair set where applicable);174    /// the node at height z and position i gets tree index `(treeNumber << (height − z)) + i`175    /// (`treeNumber` is the FORS tree number, 0 for XMSS). When `auth` is given, the authentication176    /// path of `leaf` (`height · n` bytes) is copied out while the levels are built.177    func merkleRoot(178        _ nodes: UnsafeMutablePointer<UInt8>, height: Int, leaf: Int, _ adrs: ADRS, treeNumber: Int,179        auth: UnsafeMutablePointer<UInt8>?, root: UnsafeMutablePointer<UInt8>180    ) {181        let n = p.n182        var a = adrs183        for z in 0..<height {184            if let auth {185                (auth + z * n).update(from: nodes + ((leaf >> z) ^ 1) * n, count: n)186            }187            a.setTreeHeight(UInt32(z + 1))188            let base = treeNumber << (height - z - 1)189            for i in 0..<(1 << (height - z - 1)) {190                a.setTreeIndex(UInt32(base + i))191                th.H(a, nodes + (2 * i) * n, nodes + (2 * i + 1) * n, nodes + i * n)192            }193        }194        root.update(from: nodes, count: n)195    }196197    /// Computes the WOTS+ public keys (XMSS leaves) of `count` whole XMSS trees on all cores.198    /// Tree t is at layer `layers[t]` with tree address `trees[t]`; its leaves go to `out + t · 2^h' · n`.199    func xmssLeaves(skSeed: UnsafePointer<UInt8>, layers: [UInt32], trees: [UInt64], _ out: UnsafeMutablePointer<UInt8>) {200        let n = p.n, hp = p.hPrime201        let perTree = 1 << hp202        nonisolated(unsafe) let out = out203        nonisolated(unsafe) let skSeed = skSeed204        DispatchQueue.concurrentPerform(iterations: layers.count * perTree) { t in205            let tree = t >> hp206            let adrs = ADRS(layer: layers[tree], tree: trees[tree], type: .wotsHash, keyPair: UInt32(t & (perTree - 1)))207            wotsPkGen(skSeed: skSeed, adrs, out + t * n)208        }209    }210211    /// Root of the top XMSS tree (slh_keygen_internal, Algorithm 18, line 3: xmss_node(SK.seed, 0, h')).212    func topRoot(skSeed: UnsafePointer<UInt8>, _ root: UnsafeMutablePointer<UInt8>) {213        let n = p.n, hp = p.hPrime214        let layer = UInt32(p.d - 1)215        let nodes = UnsafeMutablePointer<UInt8>.allocate(capacity: (1 << hp) * n)216        defer { nodes.deallocate() }217        xmssLeaves(skSeed: skSeed, layers: [layer], trees: [0], nodes)218        merkleRoot(nodes, height: hp, leaf: 0, ADRS(layer: layer, tree: 0, type: .tree), treeNumber: 0, auth: nil, root: root)219    }220221    // MARK: XMSS and hypertree verification (sections 6 and 7)222223    /// xmss_pkFromSig (Algorithm 11). `sig` is `len · n` WOTS+ bytes followed by `h' · n` path bytes.224    func xmssPkFromSig(225        idx: UInt32, _ sig: UnsafePointer<UInt8>, _ message: UnsafePointer<UInt8>, layer: UInt32, tree: UInt64,226        _ out: UnsafeMutablePointer<UInt8>227    ) {228        let n = p.n229        var adrs = ADRS(layer: layer, tree: tree, type: .wotsHash, keyPair: idx)230        wotsPkFromSig(sig, message, adrs, out)231        let auth = sig + p.len * n232        adrs.setTypeAndClear(.tree)233        adrs.setTreeIndex(idx)234        for k in 0..<p.hPrime {235            adrs.setTreeHeight(UInt32(k + 1))236            if (idx >> UInt32(k)) & 1 == 0 {237                adrs.setTreeIndex(adrs.getTreeIndex() / 2)238                th.H(adrs, out, auth + k * n, out)239            } else {240                adrs.setTreeIndex((adrs.getTreeIndex() - 1) / 2)241                th.H(adrs, auth + k * n, out, out)242            }243        }244    }245246    /// The (tree address, leaf index) pair of every hypertree layer, bottom-up (Algorithm 12, lines 6 to 8).247    func layerIndices(idxTree: UInt64, idxLeaf: UInt32) -> (trees: [UInt64], leaves: [UInt32]) {248        var trees = [UInt64](repeating: 0, count: p.d)249        var leaves = [UInt32](repeating: 0, count: p.d)250        var t = idxTree251        var l = idxLeaf252        let leafMask: UInt64 = (1 << UInt64(p.hPrime)) - 1253        for j in 0..<p.d {254            trees[j] = t255            leaves[j] = l256            l = UInt32(t & leafMask)257            t >>= UInt64(p.hPrime)258        }259        return (trees, leaves)260    }261262    /// ht_sign (Algorithm 12): writes `d · (len + h') · n` bytes at `out`.263    func htSign(264        _ message: UnsafePointer<UInt8>, skSeed: UnsafePointer<UInt8>, idxTree: UInt64, idxLeaf: UInt32,265        _ out: UnsafeMutablePointer<UInt8>266    ) {267        let n = p.n, hp = p.hPrime, d = p.d268        let (trees, leaves) = layerIndices(idxTree: idxTree, idxLeaf: idxLeaf)269        let perTree = (1 << hp) * n270        let nodes = UnsafeMutablePointer<UInt8>.allocate(capacity: d * perTree)271        defer { nodes.deallocate() }272        xmssLeaves(skSeed: skSeed, layers: (0..<d).map { UInt32($0) }, trees: trees, nodes)273274        let xmssSize = (p.len + hp) * n275        withUnsafeTemporaryAllocation(of: UInt8.self, capacity: n) { cur in276            let m = cur.baseAddress!277            m.update(from: message, count: n)278            for j in 0..<d {279                let sig = out + j * xmssSize280                // xmss_sign (Algorithm 10): WOTS+ signature of the current root, then the path281                wotsSign(m, skSeed: skSeed, ADRS(layer: UInt32(j), tree: trees[j], type: .wotsHash, keyPair: leaves[j]), sig)282                // the root of this tree is the message of the next layer (it equals xmss_pkFromSig)283                merkleRoot(nodes + j * perTree, height: hp, leaf: Int(leaves[j]),284                           ADRS(layer: UInt32(j), tree: trees[j], type: .tree), treeNumber: 0,285                           auth: sig + p.len * n, root: m)286            }287        }288    }289290    /// ht_verify (Algorithm 13): recomputes the top root into `root`.291    func htRoot(292        _ message: UnsafePointer<UInt8>, _ sig: UnsafePointer<UInt8>, idxTree: UInt64, idxLeaf: UInt32,293        _ root: UnsafeMutablePointer<UInt8>294    ) {295        let n = p.n296        let (trees, leaves) = layerIndices(idxTree: idxTree, idxLeaf: idxLeaf)297        let xmssSize = (p.len + p.hPrime) * n298        root.update(from: message, count: n)299        for j in 0..<p.d {300            withUnsafeTemporaryAllocation(of: UInt8.self, capacity: n) { tmp in301                let node = tmp.baseAddress!302                xmssPkFromSig(idx: leaves[j], sig + j * xmssSize, root, layer: UInt32(j), tree: trees[j], node)303                root.update(from: node, count: n)304            }305        }306    }307308    // MARK: FORS (section 8)309310    /// fors_sign (Algorithm 16) together with the FORS public key (the value fors_pkFromSig returns311    /// for this signature). Writes `k · (1 + a) · n` bytes at `out` and n bytes at `pk`.312    func forsSign(313        md: Bytes, skSeed: UnsafePointer<UInt8>, idxTree: UInt64, idxLeaf: UInt32,314        _ out: UnsafeMutablePointer<UInt8>, pk: UnsafeMutablePointer<UInt8>315    ) {316        let n = p.n, a = p.a, k = p.k317        let indices = base2b(md, b: a, outLen: k)318        let roots = UnsafeMutablePointer<UInt8>.allocate(capacity: k * n)319        defer { roots.deallocate() }320        nonisolated(unsafe) let out = out321        nonisolated(unsafe) let skSeed = skSeed322        nonisolated(unsafe) let rootsPtr = roots323        DispatchQueue.concurrentPerform(iterations: k) { i in324            let leavesCount = 1 << a325            let nodes = UnsafeMutablePointer<UInt8>.allocate(capacity: leavesCount * n)326            defer { nodes.deallocate() }327            // fors_skGen (Algorithm 14) address and leaf address328            var skADRS = ADRS(layer: 0, tree: idxTree, type: .forsPRF, keyPair: idxLeaf)329            var treeADRS = ADRS(layer: 0, tree: idxTree, type: .forsTree, keyPair: idxLeaf)330            treeADRS.setTreeHeight(0)331            withUnsafeTemporaryAllocation(of: UInt8.self, capacity: n) { tmp in332                let sk = tmp.baseAddress!333                for j in 0..<leavesCount {334                    let idx = UInt32((i << a) + j)335                    skADRS.setTreeIndex(idx)336                    th.PRF(skADRS, skSeed, sk)337                    treeADRS.setTreeIndex(idx)338                    th.F(treeADRS, sk, nodes + j * n)339                }340                _ = memset_s(sk, n, 0, n)341            }342            let sig = out + i * (1 + a) * n343            skADRS.setTreeIndex(UInt32((i << a) + Int(indices[i])))344            th.PRF(skADRS, skSeed, sig)  // the revealed secret value345            merkleRoot(nodes, height: a, leaf: Int(indices[i]), treeADRS, treeNumber: i, auth: sig + n, root: rootsPtr + i * n)346        }347        var pkADRS = ADRS(layer: 0, tree: idxTree, type: .forsRoots, keyPair: idxLeaf)348        pkADRS.setKeyPairAddress(idxLeaf)349        th.T(pkADRS, roots, k * n, pk)350    }351352    /// fors_pkFromSig (Algorithm 17).353    func forsPkFromSig(354        _ sig: UnsafePointer<UInt8>, md: Bytes, idxTree: UInt64, idxLeaf: UInt32, _ pk: UnsafeMutablePointer<UInt8>355    ) {356        let n = p.n, a = p.a, k = p.k357        let indices = base2b(md, b: a, outLen: k)358        withUnsafeTemporaryAllocation(of: UInt8.self, capacity: k * n) { rootsBuf in359            let roots = rootsBuf.baseAddress!360            var adrs = ADRS(layer: 0, tree: idxTree, type: .forsTree, keyPair: idxLeaf)361            for i in 0..<k {362                let part = sig + i * (1 + a) * n363                let node = roots + i * n364                adrs.setTreeHeight(0)365                adrs.setTreeIndex(UInt32(i << a) + indices[i])366                th.F(adrs, part, node)367                let auth = part + n368                for j in 0..<a {369                    adrs.setTreeHeight(UInt32(j + 1))370                    if (indices[i] >> UInt32(j)) & 1 == 0 {371                        adrs.setTreeIndex(adrs.getTreeIndex() / 2)372                        th.H(adrs, node, auth + j * n, node)373                    } else {374                        adrs.setTreeIndex((adrs.getTreeIndex() - 1) / 2)375                        th.H(adrs, auth + j * n, node, node)376                    }377                }378            }379            var pkADRS = adrs380            pkADRS.setTypeAndClear(.forsRoots)381            pkADRS.setKeyPairAddress(idxLeaf)382            th.T(pkADRS, roots, k * n, pk)383        }384    }385}386
Files main
Menu

Theme