SPB Git

Repository Public

Ed25519Properties.swift 21.9 KB 373 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/PropertyAuditTests/Ed25519Properties.swift8// Module           : Tests9// 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 AuditSupport42import Foundation43import QyvoraMath44import Testing4546@testable import QyvoraEd255194748// Property and invariant tests of the Ed25519 implementation: field laws including boundary limbs and49// non-canonical inputs, the limb-range invariant on which the multiplication relies, group laws, torsion50// handling, ranges of the scalar reductions, sign ∘ verify, and rejection of every single-bit alteration51// of a signature, of its message and of its public key.5253@Suite struct Ed25519FieldLaws {54    static let top: UInt64 = (1 << 52) - 155    static let edges: [UInt64] = [0, 1, 18, 19, (1 << 51) - 19, (1 << 51) - 1, 1 << 51, (1 << 52) - 2, (1 << 52) - 1]5657    static func element(_ rng: inout AuditRNG) -> Fe {58        func limb(_ rng: inout AuditRNG) -> UInt64 { rng.int(0...3) == 0 ? rng.pick(edges) : rng.next() & top }59        switch rng.int(0...9) {60        case 0: return Fe(top, top, top, top, top)  // the largest loose representative61        case 1: return Fe((1 << 51) - 19, (1 << 51) - 1, (1 << 51) - 1, (1 << 51) - 1, (1 << 51) - 1)  // p, a representative of 062        case 2: return Fe((1 << 51) - 18, (1 << 51) - 1, (1 << 51) - 1, (1 << 51) - 1, (1 << 51) - 1)  // p + 163        case 3: return Fe(small: UInt32(truncatingIfNeeded: rng.next() & 0xff))64        default: return Fe(limb(&rng), limb(&rng), limb(&rng), limb(&rng), limb(&rng))65        }66    }6768    static func same(_ a: Fe, _ b: Fe) -> Bool { a.toBytes() == b.toBytes() }69    static func loose(_ a: Fe) -> Bool { max(a.l0, a.l1, a.l2, a.l3, a.l4) <= top }7071    @Test func ringLawsOnLooseAndBoundaryElements() {72        let seed = AuditSeed.make("ed25519-field-laws")73        var rng = AuditRNG(seed: seed)74        var p = Prop("field-laws", algorithm: "GF(2^255-19)", seed: seed)75        for _ in 0..<AuditMode.cases(quick: 2000, full: 30_000) {76            let a = Self.element(&rng), b = Self.element(&rng), c = Self.element(&rng)77            let d = "a \([a.l0, a.l1, a.l2, a.l3, a.l4]) b \([b.l0, b.l1, b.l2, b.l3, b.l4]) c \([c.l0, c.l1, c.l2, c.l3, c.l4])"78            p.check(Self.same(Fe.add(a, b), Fe.add(b, a)), "a + b = b + a: \(d)")79            p.check(Self.same(Fe.mul(a, b), Fe.mul(b, a)), "ab = ba: \(d)")80            p.check(Self.same(Fe.add(Fe.add(a, b), c), Fe.add(a, Fe.add(b, c))), "(a + b) + c: \(d)")81            p.check(Self.same(Fe.mul(Fe.mul(a, b), c), Fe.mul(a, Fe.mul(b, c))), "(ab)c: \(d)")82            p.check(Self.same(Fe.mul(a, Fe.add(b, c)), Fe.add(Fe.mul(a, b), Fe.mul(a, c))), "a(b + c): \(d)")83            p.check(Self.same(Fe.mul(a, Fe.sub(b, c)), Fe.sub(Fe.mul(a, b), Fe.mul(a, c))), "a(b − c): \(d)")84            p.check(Self.same(Fe.sub(Fe.add(a, b), b), a), "(a + b) − b = a: \(d)")85            p.check(Fe.add(a, Fe.neg(a)).isZeroMask == UInt64.max, "a + (−a) = 0: \(d)")86            p.check(Self.same(Fe.square(a), Fe.mul(a, a)) && Self.same(Fe.squareTimes(a, 3), Fe.square(Fe.square(Fe.square(a)))), "squares: \(d)")87            p.check(Self.same(Fe.mul(a, .one), a) && Fe.mul(a, .zero).isZeroMask == UInt64.max, "identities: \(d)")88            // inversion: a · a⁻¹ = 1 unless a = 0, and 0⁻¹ = 089            let product = Fe.mul(a, Fe.invert(a))90            p.check(a.isZeroMask == UInt64.max ? product.isZeroMask == UInt64.max : Self.same(product, .one), "a · a⁻¹: \(d)")91            // the limb-range invariant every operation must preserve (the bound the multiplication relies on)92            p.check(93                Self.loose(Fe.add(a, b)) && Self.loose(Fe.sub(a, b)) && Self.loose(Fe.mul(a, b)) && Self.loose(Fe.neg(a)) && Self.loose(Fe.invert(a))94                    && Self.loose(Fe.select(UInt64.max, a, b)), "limb range: \(d)")95            // canonical encoding: below p, stable under decode ∘ encode96            let bytes = a.toBytes()97            p.check(bytes[31] & 0x80 == 0 && Fe.fromBytes(bytes).toBytes() == bytes, "canonical bytes: \(d)")98            var reversed = bytes99            reversed.reverse()100            let pBE: Bytes = [0x7f] + Bytes(repeating: 0xff, count: 30) + [0xed]101            p.check(reversed.lexicographicallyPrecedes(pBE), "encoding below p: \(d)")102            // masks, selection, swap103            p.check(Self.same(Fe.select(UInt64.max, a, b), a) && Self.same(Fe.select(0, a, b), b), "select: \(d)")104            var x = a, y = b105            Fe.conditionalSwap(UInt64.max, &x, &y)106            var u = a, v = b107            Fe.conditionalSwap(0, &u, &v)108            p.check(Self.same(x, b) && Self.same(y, a) && Self.same(u, a) && Self.same(v, b), "conditionalSwap: \(d)")109            p.check((Fe.equalMask(a, b) == UInt64.max) == (a.toBytes() == b.toBytes()), "equalMask: \(d)")110            // square roots: for a square the returned root is the non-negative root of the ratio111            let sq = Fe.square(a)112            let (isSquare, root) = Fe.sqrtRatio(sq, .one)113            p.check(isSquare == UInt64.max && Self.same(Fe.square(root), sq) && root.isNegative == 0, "sqrt of a square: \(d)")114            let (isSquare2, root2) = Fe.sqrtRatio(a, b)115            if isSquare2 == UInt64.max {116                p.check(Self.same(Fe.mul(Fe.square(root2), b), a) && root2.isNegative == 0, "sqrtRatio: \(d)")117            } else {118                // not a square: then √−1 · u/v is one (exactly one of r and i·r is a square for non-zero ratios)119                // (a ratio with denominator 0 and a non-zero numerator is reported as "not a square" both ways)120                p.check(isSquare2 == 0 && (b.isZeroMask == UInt64.max || Fe.sqrtRatio(Fe.mul(a, Fe.sqrtMinusOne), b).0 == UInt64.max), "non-square: \(d)")121            }122        }123        // constants124        p.check(Self.same(Fe.square(Fe.sqrtMinusOne), Fe.neg(.one)), "√−1")125        p.check(Self.same(Fe.mul(Fe.d, Fe(small: 121_666)), Fe.neg(Fe(small: 121_665))), "d")126        p.check(Self.same(Fe.d2, Fe.add(Fe.d, Fe.d)), "2d")127        p.finish(note: "loose limbs up to 2^52 − 1, boundary limbs and non-canonical representatives of 0 and 1 included")128    }129130    /// Long random chains of operations starting from the worst-case limbs: the range invariant never breaks131    /// and the result always equals the same chain computed on canonical representatives.132    @Test func limbRangeInvariantOverOperationChains() {133        let seed = AuditSeed.make("ed25519-field-chains")134        var rng = AuditRNG(seed: seed)135        var p = Prop("field-operation-chains", algorithm: "GF(2^255-19)", seed: seed)136        for _ in 0..<AuditMode.cases(quick: 300, full: 4000) {137            var loose = Self.element(&rng)138            var canonical = Fe.fromBytes(loose.toBytes())139            for _ in 0..<40 {140                let other = Self.element(&rng)141                let otherCanonical = Fe.fromBytes(other.toBytes())142                switch rng.int(0...5) {143                case 0: (loose, canonical) = (Fe.add(loose, other), Fe.add(canonical, otherCanonical))144                case 1: (loose, canonical) = (Fe.sub(loose, other), Fe.sub(canonical, otherCanonical))145                case 2: (loose, canonical) = (Fe.sub(other, loose), Fe.sub(otherCanonical, canonical))146                case 3: (loose, canonical) = (Fe.mul(loose, other), Fe.mul(canonical, otherCanonical))147                case 4: (loose, canonical) = (Fe.square(loose), Fe.square(canonical))148                default: (loose, canonical) = (Fe.neg(loose), Fe.neg(canonical))149                }150                p.check(Self.loose(loose) && Self.same(loose, canonical), "chain diverged or left the limb range")151            }152        }153        p.finish()154    }155}156157@Suite struct Ed25519GroupLaws {158    static func point(_ rng: inout AuditRNG) -> EdPoint {159        switch rng.int(0...7) {160        case 0: return rng.pick(EdTorsion.points)161        case 1: return EdPoint.add(EdPoint.multiplyBase(scalar: rng.bytes(32)), rng.pick(EdTorsion.points))162        case 2: return .identity163        default: return EdPoint.multiplyBase(scalar: rng.bytes(32))164        }165    }166167    static func scalarBytes(_ s: Sc) -> Bytes { s.bytes }168169    @Test func groupLawsIncludingTorsion() {170        let seed = AuditSeed.make("ed25519-group-laws")171        var rng = AuditRNG(seed: seed)172        var p = Prop("group-laws", algorithm: "edwards25519", seed: seed)173        for _ in 0..<AuditMode.cases(quick: 250, full: 3000) {174            let a = Self.point(&rng), b = Self.point(&rng), c = Self.point(&rng)175            p.check(a.isValid && b.isValid && EdPoint.add(a, b).isValid && EdPoint.double(a).isValid, "closure")176            p.check(EdPoint.equal(EdPoint.add(a, b), EdPoint.add(b, a)), "commutativity")177            p.check(EdPoint.equal(EdPoint.add(EdPoint.add(a, b), c), EdPoint.add(a, EdPoint.add(b, c))), "associativity")178            p.check(EdPoint.equal(EdPoint.add(a, .identity), a) && EdPoint.add(a, EdPoint.negate(a)).isIdentity, "neutral element and opposite")179            p.check(EdPoint.equal(EdPoint.double(a), EdPoint.add(a, a)), "doubling is addition with itself (unified formula)")180            // scalar multiplication is a homomorphism: [s + t]P = [s]P + [t]P and [s]([t]P) = [st]P (integers modulo ℓ on181            // the prime-order part; with torsion the scalars are multiplied by 8 so that the identity holds exactly)182            let s = Sc.reduceWide(rng.bytes(64)), t = Sc.reduceWide(rng.bytes(64))183            let eight = Sc(8, 0, 0, 0)184            let s8 = Sc.mulAdd(s, eight, .zero), t8 = Sc.mulAdd(t, eight, .zero)185            let cleared = EdPoint.double(EdPoint.double(EdPoint.double(a)))  // 8·a: in the prime-order subgroup186            p.check(187                EdPoint.equal(EdPoint.multiply(scalar: Sc.addMod(s8, t8).bytes, cleared), EdPoint.add(EdPoint.multiply(scalar: s8.bytes, cleared), EdPoint.multiply(scalar: t8.bytes, cleared))),188                "[s + t]P")189            p.check(190                EdPoint.equal(EdPoint.multiply(scalar: s.bytes, EdPoint.multiply(scalar: t.bytes, cleared)), EdPoint.multiply(scalar: Sc.mulAdd(s, t, .zero).bytes, cleared)),191                "[s][t]P")192            // the fixed-base and the variable-base paths agree, for any 256-bit scalar193            let raw = rng.bytes(32)194            p.check(EdPoint.equal(EdPoint.multiplyBase(scalar: raw), EdPoint.multiply(scalar: raw, EdPoint.base)), "fixed base = variable base")195            // encoding round trip (canonical, strict)196            let encoded = a.encode()197            p.check(EdPoint.decode(encoded, strict: true).map { EdPoint.equal($0, a) } == true, "decode ∘ encode")198            // [ℓ]P is a torsion point, [8ℓ]P the neutral element199            let lp = EdPoint.multiply(scalar: Sc.order.bytes, a)200            p.check(lp.isSmallOrder && EdPoint.double(EdPoint.double(EdPoint.double(lp))).isIdentity, "[8ℓ]P = 0")201        }202        p.check(EdPoint.multiplyBase(scalar: Sc.order.bytes).isIdentity, "[ℓ]B = 0")203        p.check(!EdPoint.multiplyBase(scalar: Sc.subWide(Sc.order, .one).0.bytes).isIdentity, "[ℓ − 1]B ≠ 0")204        p.check(EdPoint.multiplyBase(scalar: Bytes(repeating: 0, count: 32)).isIdentity, "[0]B = 0")205        p.check(!EdPoint.base.isSmallOrder && EdPoint.base.isValid, "base point")206        p.finish()207    }208209    @Test func torsionSubgroupAndSmallOrderDetection() {210        var p = Prop("torsion", algorithm: "edwards25519")211        let t = EdTorsion.points212        p.check(t.count == 8, "eight torsion points")213        p.check(Set(t.map { Hex.encode($0.encode()) }).count == 8, "distinct encodings")214        // orders 1, 2, 4, 4, 8, 8, 8, 8215        var orders = [Int: Int]()216        for point in t {217            var q = point218            var order = 1219            while !q.isIdentity && order < 16 {220                q = EdPoint.add(q, point)221                order += 1222            }223            orders[order, default: 0] += 1224            p.check(point.isSmallOrder && point.isValid, "small order")225            p.check(Ed25519.isSmallOrder(point.encode()) == true && !Ed25519.isValidPublicKey(point.encode()), "public predicates")226            p.check(Ed25519.isCanonicalPoint(point.encode()) && Ed25519.isOnCurve(point.encode()), "canonical torsion encoding")227        }228        p.check(orders == [1: 1, 2: 1, 4: 2, 8: 4], "orders \(orders)")229        // the subgroup is closed and the addition formula is complete on it (every pair, including P + P and P + (−P))230        let encodings = Set(t.map { Hex.encode($0.encode()) })231        for a in t {232            for b in t {233                let sum = EdPoint.add(a, b)234                p.check(sum.isValid && encodings.contains(Hex.encode(sum.encode())), "closure of the torsion subgroup")235            }236        }237        // a point with a prime-order component is never reported as small order, with or without torsion238        var rng = AuditRNG(seed: 0x51_5956)239        for _ in 0..<64 {240            let q = EdPoint.multiplyBase(scalar: Sc.reduceWide(rng.bytes(64)).bytes)241            guard !q.isIdentity else { continue }242            for torsionPoint in t {243                let mixed = EdPoint.add(q, torsionPoint)244                p.check(!mixed.isSmallOrder && Ed25519.isValidPublicKey(mixed.encode()), "mixed-order point reported as small order")245            }246        }247        p.finish(note: "isValidPublicKey accepts mixed-order keys (as ed25519-dalek verify_strict), refuses the eight small-order points")248    }249}250251/// The torsion points, derived independently of the differential tests (multiplication of random points by ℓ).252enum EdTorsion {253    static let points: [EdPoint] = {254        var found = [String: EdPoint]()255        var rng = AuditRNG(seed: 0x7131_7a02)256        while found.count < 8 {257            guard let p = EdPoint.decode(rng.bytes(32), strict: false) else { continue }258            let t = EdPoint.multiply(scalar: Sc.order.bytes, p)259            found[Hex.encode(t.encode())] = t260        }261        return found.keys.sorted().compactMap { found[$0] }262    }()263}264265@Suite struct Ed25519ScalarRanges {266    @Test func reductionsAlwaysLandBelowTheOrder() {267        let seed = AuditSeed.make("ed25519-scalar-ranges")268        var rng = AuditRNG(seed: seed)269        var p = Prop("scalar-ranges", algorithm: "integers modulo ℓ", seed: seed)270        let max = Sc(UInt64.max, UInt64.max, UInt64.max, UInt64.max)271        let lMinus1 = Sc.subWide(Sc.order, .one).0272        let edges: [Sc] = [.zero, .one, lMinus1, Sc.order, Sc.addWide(Sc.order, .one).0, max, Sc(0, 0, 0, 1 << 63), Sc(UInt64.max, 0, 0, 0)]273        func any(_ rng: inout AuditRNG) -> Sc { rng.int(0...3) == 0 ? rng.pick(edges) : Sc(littleEndian: rng.bytes(32)) }274        for _ in 0..<AuditMode.cases(quick: 3000, full: 40_000) {275            let a = any(&rng), b = any(&rng), c = any(&rng)276            let ra = Sc.reduce(a), rc = Sc.reduce(c)277            p.check(ra.isCanonical && rc.isCanonical, "reduce")278            p.check(a.isCanonical ? ra.bytes == a.bytes : true, "reduce is the identity below ℓ")279            p.check(Sc.montMul(ra, b).isCanonical && Sc.montMul(b, ra).isCanonical, "montMul with one reduced operand")280            p.check(Sc.mulAdd(ra, b, rc).isCanonical && Sc.addMod(ra, rc).isCanonical, "mulAdd, addMod")281            p.check(Sc.mulAdd(ra, .one, .zero).bytes == ra.bytes && Sc.mulAdd(ra, .zero, rc).bytes == rc.bytes, "mulAdd identities")282            p.check(Sc.mulAdd(ra, b, rc).bytes == Sc.mulAdd(ra, Sc.reduce(b), rc).bytes, "mulAdd does not depend on the representative of b")283            let wide = rng.int(0...5) == 0 ? rng.pick(edges).bytes + rng.pick(edges).bytes : rng.bytes(64)284            p.check(Sc.reduceWide(wide).isCanonical, "reduceWide")285            // low + high·2^256, with 2^256 mod ℓ computed by doubling286            var twoTo256 = Sc.one287            for _ in 0..<256 { twoTo256 = Sc.addMod(twoTo256, twoTo256) }288            let low = Sc.reduce(Sc(littleEndian: Bytes(wide[0..<32]))), high = Sc(littleEndian: Bytes(wide[32..<64]))289            p.check(Sc.reduceWide(wide).bytes == Sc.mulAdd(twoTo256, high, low).bytes, "reduceWide = low + high·2^256")290        }291        p.check(Sc.reduce(Sc.order).bytes == Sc.zero.bytes && !Sc.order.isCanonical && lMinus1.isCanonical, "ℓ itself")292        p.check(Sc.reduceWide(Bytes(repeating: 0xff, count: 64)).isCanonical, "2^512 − 1")293        p.finish()294    }295}296297@Suite struct Ed25519SignatureProperties {298    @Test func signThenVerifyAndDeterminism() throws {299        let seed = AuditSeed.make("ed25519-sign-verify")300        var rng = AuditRNG(seed: seed)301        var p = Prop("sign-verify", algorithm: "Ed25519", seed: seed)302        for _ in 0..<AuditMode.cases(quick: 400, full: 5000) {303            let s = rng.bytes(32), message = rng.bytes(rng.edgeLength(block: 128, max: 300))304            let pk = try Ed25519.publicKey(seed: s)305            let sig = try Ed25519.sign(message: message, seed: s)306            p.check(sig.count == 64 && Ed25519.verify(signature: sig, message: message, publicKey: pk), "sign then verify")307            p.check(try Ed25519.sign(message: message, seed: s) == sig, "deterministic")308            p.check(Sc(littleEndian: Bytes(sig[32..<64])).isCanonical, "S below ℓ")309            p.check(Ed25519.isValidPublicKey(pk) && Ed25519.isSmallOrder(Bytes(sig[0..<32])) == false, "key and R are not of small order")310            // a different message or key never verifies311            let otherKey = try Ed25519.publicKey(seed: rng.bytes(32))312            p.check(!Ed25519.verify(signature: sig, message: message + [0], publicKey: pk) && !Ed25519.verify(signature: sig, message: message, publicKey: otherKey), "other message or key")313        }314        for length in [0, 1, 31, 33, 64] {315            p.check((try? Ed25519.sign(message: [1], seed: Bytes(repeating: 1, count: length))) == nil, "seed of \(length) bytes accepted by sign")316            p.check((try? Ed25519.publicKey(seed: Bytes(repeating: 1, count: length))) == nil, "seed of \(length) bytes accepted by publicKey")317        }318        p.finish()319    }320321    /// Every single-bit flip of the signature (512), of the public key (256) and of the message is refused.322    @Test func everySingleBitFlipIsRefused() throws {323        let seed = AuditSeed.make("ed25519-bit-flips")324        var rng = AuditRNG(seed: seed)325        var p = Prop("single-bit-flips", algorithm: "Ed25519", seed: seed)326        for _ in 0..<AuditMode.cases(quick: 6, full: 60) {327            let s = rng.bytes(32), message = rng.bytes(rng.int(1...96))328            let pk = try Ed25519.publicKey(seed: s)329            let sig = try Ed25519.sign(message: message, seed: s)330            #expect(Ed25519.verify(signature: sig, message: message, publicKey: pk))331            for bit in 0..<512 {332                var altered = sig333                altered[bit >> 3] ^= 1 << UInt8(bit & 7)334                p.check(!Ed25519.verify(signature: altered, message: message, publicKey: pk), "signature bit \(bit)")335            }336            for bit in 0..<256 {337                var altered = pk338                altered[bit >> 3] ^= 1 << UInt8(bit & 7)339                p.check(!Ed25519.verify(signature: sig, message: message, publicKey: altered), "public key bit \(bit)")340            }341            for bit in 0..<(message.count * 8) {342                var altered = message343                altered[bit >> 3] ^= 1 << UInt8(bit & 7)344                p.check(!Ed25519.verify(signature: sig, message: altered, publicKey: pk), "message bit \(bit)")345            }346        }347        p.finish()348    }349350    /// SLIP-0010: the path API equals step-by-step derivation, children differ from parents, and `wipe` clears a node.351    @Test func slip10Structure() throws {352        let seed = AuditSeed.make("ed25519-slip10-structure")353        var rng = AuditRNG(seed: seed)354        var p = Prop("slip10-structure", algorithm: "SLIP-0010", parameterSet: "ed25519", seed: seed)355        for _ in 0..<AuditMode.cases(quick: 100, full: 1500) {356            let master = rng.bytes(rng.int(16...64))357            let path = (0..<rng.int(1...5)).map { _ in UInt32(truncatingIfNeeded: rng.next()) & 0x7fff_ffff }358            var node = try Ed25519.SLIP10.master(seed: master)359            var seen = Set([Hex.encode(node.privateKey)])360            for index in path {361                node = try node.deriveHardened(index)362                p.check(seen.insert(Hex.encode(node.privateKey)).inserted, "repeated private key along a path")363            }364            let direct = try Ed25519.SLIP10.derive(seed: master, path: path)365            p.check(direct == node && node.privateKey.count == 32 && node.chainCode.count == 32, "path = steps")366            var wiped = node367            wiped.wipe()368            p.check(wiped.privateKey == Bytes(repeating: 0, count: 32) && wiped.chainCode == Bytes(repeating: 0, count: 32), "wipe")369        }370        p.finish()371    }372}373
Files main
Menu

Theme