SPB Git

Repository Public

Ed25519Tests.swift 29.3 KB 589 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraEd25519Tests/Ed25519Tests.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 CryptoKit42import Foundation43import QyvoraMath44import QyvoraSymmetric45import Testing46@testable import QyvoraEd255194748func hex(_ s: some StringProtocol) -> Bytes { Bytes(hex: String(s))! }4950func fields(_ line: Substring) -> [Substring] { line.split(separator: "|", omittingEmptySubsequences: false) }5152/// The eight points of the torsion subgroup, canonical encodings (computed by the big-integer model `ref_ed.py`;53/// they are also the well-known list of libsodium).54let smallOrderEncodings: [String] = [55    "0100000000000000000000000000000000000000000000000000000000000000",56    "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",57    "0000000000000000000000000000000000000000000000000000000000000000",58    "0000000000000000000000000000000000000000000000000000000000000080",59    "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",60    "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",61    "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",62    "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",63]6465/// ℓ, little endian.66let orderBytes = hex("edd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010")6768@Suite struct RFC8032Tests {69    /// RFC 8032 §7.1: the five Ed25519 vectors — public key, signature (byte for byte) and verification.70    @Test func everySection71Vector() throws {71        var count = 072        for line in StandardVectors.rfc8032.split(separator: "\n") {73            let f = fields(line)74            #expect(f.count == 5)75            let seed = hex(f[1]), publicKey = hex(f[2]), message = hex(f[3]), signature = hex(f[4])76            #expect(try Ed25519.publicKey(seed: seed) == publicKey, "public key of TEST \(f[0])")77            #expect(try Ed25519.sign(message: message, seed: seed) == signature, "signature of TEST \(f[0])")78            #expect(Ed25519.verify(signature: signature, message: message, publicKey: publicKey))79            #expect(!Ed25519.verify(signature: signature, message: message + [0], publicKey: publicKey))80            count += 181        }82        #expect(count == 5)83    }8485    @Test func signingIsDeterministic() throws {86        let seed = Ed25519.generateSeed()87        let message = SystemRandom.bytes(77)88        #expect(try Ed25519.sign(message: message, seed: seed) == Ed25519.sign(message: message, seed: seed))89    }9091    @Test func malformedInputsReturnErrorsOrFalse() throws {92        #expect(throws: Ed25519.Error.invalidSeedLength) { try Ed25519.publicKey(seed: Bytes(repeating: 1, count: 31)) }93        #expect(throws: Ed25519.Error.invalidSeedLength) { try Ed25519.publicKey(seed: []) }94        #expect(throws: Ed25519.Error.invalidSeedLength) { try Ed25519.sign(message: [1], seed: Bytes(repeating: 1, count: 33)) }95        let seed = Bytes(repeating: 7, count: 32)96        let publicKey = try Ed25519.publicKey(seed: seed)97        let signature = try Ed25519.sign(message: [1, 2, 3], seed: seed)98        #expect(Ed25519.verify(signature: signature, message: [1, 2, 3], publicKey: publicKey))99        #expect(!Ed25519.verify(signature: [], message: [1, 2, 3], publicKey: publicKey))100        #expect(!Ed25519.verify(signature: Bytes(signature.dropLast()), message: [1, 2, 3], publicKey: publicKey))101        #expect(!Ed25519.verify(signature: signature + [0], message: [1, 2, 3], publicKey: publicKey))102        #expect(!Ed25519.verify(signature: signature, message: [1, 2, 3], publicKey: []))103        #expect(!Ed25519.verify(signature: signature, message: [1, 2, 3], publicKey: publicKey + [0]))104        #expect(!Ed25519.isOnCurve([]))105        #expect(!Ed25519.isValidPublicKey(Bytes(repeating: 0, count: 31)))106        #expect(Ed25519.isSmallOrder(Bytes(repeating: 0, count: 33)) == nil)107    }108}109110@Suite struct SLIP0010Tests {111    /// SLIP-0010 test vectors 1 and 2 for ed25519: every node (chain code, private key, public key).112    @Test func vectors1And2() throws {113        var count = 0114        for line in StandardVectors.slip0010.split(separator: "\n") {115            let f = fields(line)116            #expect(f.count == 6)117            let path = try f[2].split(separator: "/").dropFirst().map { part -> UInt32 in118                try #require(part.hasSuffix("'"))119                return try #require(UInt32(part.dropLast()))120            }121            let node = try Ed25519.SLIP10.derive(seed: hex(f[1]), path: path)122            #expect(node.chainCode == hex(f[3]), "chain code \(f[0]) \(f[2])")123            #expect(node.privateKey == hex(f[4]), "private key \(f[0]) \(f[2])")124            #expect(try node.publicKey() == hex(f[5]), "public key \(f[0]) \(f[2])")125            count += 1126        }127        #expect(count == 12)128    }129130    @Test func stepByStepEqualsPathAndErrors() throws {131        let seed = hex("000102030405060708090a0b0c0d0e0f")132        var node = try Ed25519.SLIP10.master(seed: seed)133        for i: UInt32 in [44, 501, 0, 0] { node = try node.deriveHardened(i) }134        #expect(node == (try Ed25519.SLIP10.derive(seed: seed, path: [44, 501, 0, 0])))135        #expect(throws: Ed25519.Error.invalidDerivationIndex) { try node.deriveHardened(0x8000_0000) }136        #expect(throws: Ed25519.Error.invalidDerivationIndex) { try Ed25519.SLIP10.derive(seed: seed, path: [0, .max]) }137        #expect(throws: Ed25519.Error.invalidDerivationSeed) { try Ed25519.SLIP10.master(seed: Bytes(repeating: 0, count: 15)) }138        #expect(throws: Ed25519.Error.invalidDerivationSeed) { try Ed25519.SLIP10.master(seed: Bytes(repeating: 0, count: 65)) }139        node.wipe()140        #expect(node.privateKey == Bytes(repeating: 0, count: 32) && node.chainCode == Bytes(repeating: 0, count: 32))141    }142}143144@Suite struct WycheproofEd25519Tests {145    /// Every test of Wycheproof `ed25519_test.json`. "valid" must verify, "invalid" must not. The "acceptable" tests146    /// are decided by the documented policy: small-order public keys are rejected, mixed-order public keys are147    /// accepted when the cofactorless equation holds — the expected answers below are those of an independent148    /// big-integer model of the policy (`ref_ed.py`), which also agrees with libsodium (PyNaCl) on all 210 tests.149    @Test func allVectors() {150        var valid = 0, invalid = 0, acceptableAccepted = 0, acceptableRejected = 0151        for line in WycheproofVectors.ed25519.split(separator: "\n") {152            let f = fields(line)153            #expect(f.count == 6)154            let id = Int(f[0])!155            let result = Ed25519.verify(signature: hex(f[3]), message: hex(f[2]), publicKey: hex(f[1]))156            switch f[4] {157            case "valid":158                #expect(result, "tcId \(id) must verify")159                valid += 1160            case "invalid":161                #expect(!result, "tcId \(id) (\(f[5])) must be rejected")162                invalid += 1163            case "acceptable":164                if f[5] == "SmallOrderPublicKey" {165                    #expect((152...159).contains(id))166                    #expect(!result, "tcId \(id): small-order public key must be rejected")167                    acceptableRejected += 1168                } else {169                    #expect(f[5] == "MixedOrderPublicKey" && (160...180).contains(id))170                    #expect(result, "tcId \(id): mixed-order key, cofactorless equation holds")171                    acceptableAccepted += 1172                }173            default:174                Issue.record("unknown result \(f[4])")175            }176        }177        #expect(valid == 117 && invalid == 64 && acceptableRejected == 8 && acceptableAccepted == 21)178        #expect(valid + invalid + acceptableRejected + acceptableAccepted == WycheproofVectors.numberOfTests)179    }180}181182@Suite struct CryptoKitDifferentialTests {183    static let rounds = 5000184185    /// Random seeds and messages: same public key as CryptoKit; our signatures verify with CryptoKit; CryptoKit's186    /// (randomized) signatures verify with ours; a flipped bit is rejected by both.187    @Test func bothDirections() throws {188        var rng = SystemRandomNumberGenerator()189        for round in 0..<Self.rounds {190            let seed = SystemRandom.bytes(32)191            let message = SystemRandom.bytes(Int(rng.next() % 200))192            let reference = try Curve25519.Signing.PrivateKey(rawRepresentation: Data(seed))193            let publicKey = try Ed25519.publicKey(seed: seed)194            #expect(publicKey == Bytes(reference.publicKey.rawRepresentation), "public key, round \(round)")195196            let ours = try Ed25519.sign(message: message, seed: seed)197            #expect(reference.publicKey.isValidSignature(Data(ours), for: Data(message)), "CryptoKit verifies ours, round \(round)")198            let theirs = Bytes(try reference.signature(for: Data(message)))199            #expect(Ed25519.verify(signature: theirs, message: message, publicKey: publicKey), "we verify CryptoKit's, round \(round)")200201            var tampered = theirs202            tampered[Int(rng.next() % 64)] ^= 1 << UInt8(rng.next() % 8)203            #expect(!Ed25519.verify(signature: tampered, message: message, publicKey: publicKey))204            #expect(!reference.publicKey.isValidSignature(Data(tampered), for: Data(message)))205            #expect(!Ed25519.verify(signature: ours, message: message + [0x01], publicKey: publicKey))206            var otherKey = publicKey207            otherKey[Int(rng.next() % 31)] ^= 0x04208            #expect(!Ed25519.verify(signature: ours, message: message, publicKey: otherKey))209        }210    }211}212213@Suite struct StrictVerificationTests {214    /// S + ℓ encodes the same scalar modulo ℓ: accepting it would make every signature malleable.215    @Test func nonCanonicalSIsRejected() throws {216        let seed = Bytes(repeating: 0x42, count: 32)217        let publicKey = try Ed25519.publicKey(seed: seed)218        var rejected = 0219        for i in 0..<64 {220            let message = Bytes("message \(i)".utf8)221            let signature = try Ed25519.sign(message: message, seed: seed)222            let s = Sc(littleEndian: Bytes(signature[32...]))223            #expect(s.isCanonical)224            let (shifted, carry) = Sc.addWide(s, Sc.order)225            // S + ℓ fits in 256 bits for every S < ℓ226            #expect(carry == 0)227            let malleated = Bytes(signature[..<32]) + shifted.bytes228            #expect(!Ed25519.verify(signature: malleated, message: message, publicKey: publicKey))229            rejected += 1230        }231        #expect(rejected == 64)232        #expect(!Sc(littleEndian: orderBytes).isCanonical)233        #expect(Sc.subWide(Sc(littleEndian: orderBytes), .one).0.isCanonical)234        #expect(!Sc(littleEndian: Bytes(repeating: 0xff, count: 32)).isCanonical)235    }236237    @Test func smallOrderPoints() {238        #expect(Set(smallOrderEncodings).count == 8)239        for encoding in smallOrderEncodings {240            let point = hex(encoding)241            #expect(Ed25519.isCanonicalPoint(point), "\(encoding) is a canonical point")242            #expect(Ed25519.isSmallOrder(point) == true)243            #expect(Ed25519.isOnCurve(point))244            #expect(!Ed25519.isValidPublicKey(point))245            // classic forgery with a small-order key: R = that key's inverse or the identity, S = 0246            for r in smallOrderEncodings {247                let forged = hex(r) + Bytes(repeating: 0, count: 32)248                #expect(!Ed25519.verify(signature: forged, message: Bytes("anything".utf8), publicKey: point))249            }250        }251        // an honest key with a small-order R is rejected too252        let publicKey = try! Ed25519.publicKey(seed: Bytes(repeating: 3, count: 32))253        for r in smallOrderEncodings {254            #expect(!Ed25519.verify(signature: hex(r) + Bytes(repeating: 0, count: 32), message: [], publicKey: publicKey))255        }256        #expect(Ed25519.isSmallOrder(publicKey) == false)257        #expect(Ed25519.isValidPublicKey(publicKey))258    }259260    /// y ≥ p (the 19 values p … 2^255 − 1) and "x = 0 with the sign bit": refused by the strict decoder, and decoded261    /// like their reduced form by the lenient one (Solana's `is_on_curve`).262    @Test func nonCanonicalEncodings() {263        var p = Bytes(repeating: 0xff, count: 32)264        p[0] = 0xed265        p[31] = 0x7f266        var lenientAccepted = 0267        for k in 0..<19 {268            for sign: UInt8 in [0, 0x80] {269                var encoding = p270                encoding[0] = 0xed + UInt8(k)271                encoding[31] |= sign272                var reduced = Bytes(repeating: 0, count: 32)273                reduced[0] = UInt8(k)274                reduced[31] = sign275                #expect(!Ed25519.isCanonicalPoint(encoding), "y = p + \(k) is not canonical")276                #expect(!Ed25519.isValidPublicKey(encoding))277                #expect(Ed25519.isSmallOrder(encoding) == nil)278                #expect(Ed25519.isOnCurve(encoding) == Ed25519.isOnCurve(reduced))279                if Ed25519.isOnCurve(encoding) { lenientAccepted += 1 }280                #expect(!Ed25519.verify(signature: Bytes(repeating: 0, count: 64), message: [], publicKey: encoding))281            }282        }283        #expect(lenientAccepted > 0)284        // y = 1 → x = 0; with the sign bit set the encoding is not canonical285        var identityWithSign = Bytes(repeating: 0, count: 32)286        identityWithSign[0] = 1287        identityWithSign[31] = 0x80288        #expect(!Ed25519.isCanonicalPoint(identityWithSign))289        #expect(Ed25519.isOnCurve(identityWithSign))290        // y = −1 → x = 0 as well291        var minusOneWithSign = hex(smallOrderEncodings[1])292        minusOneWithSign[31] |= 0x80293        #expect(!Ed25519.isCanonicalPoint(minusOneWithSign))294        #expect(Ed25519.isOnCurve(minusOneWithSign))295    }296297    /// About half of the 32-byte strings are y-coordinates of curve points.298    @Test func isOnCurveAgreesWithCryptoKitKeyParsingOnValidPointsAndSplitsRandomStrings() throws {299        var on = 0300        for _ in 0..<2000 {301            let candidate = SystemRandom.bytes(32)302            if Ed25519.isOnCurve(candidate) { on += 1 }303            let key = try Ed25519.publicKey(seed: candidate)304            #expect(Ed25519.isOnCurve(key) && Ed25519.isValidPublicKey(key))305        }306        #expect(on > 850 && on < 1150, "\(on) of 2000 random strings on the curve")307    }308}309310@Suite struct FieldTests {311    static func random() -> Fe { Fe.fromBytes(SystemRandom.bytes(32)) }312    static func eq(_ a: Fe, _ b: Fe) -> Bool { a.toBytes() == b.toBytes() }313314    /// Sum, difference, product, inverse and (p − 5)/8 power against Python big integers, edge values included.315    @Test func referenceModelVectors() {316        var count = 0317        for line in ReferenceModelVectors.field.split(separator: "\n") {318            let f = fields(line).map { hex($0) }319            let a = Fe.fromBytes(f[0]), b = Fe.fromBytes(f[1])320            #expect(a.toBytes() == f[0] && b.toBytes() == f[1])321            #expect(Fe.add(a, b).toBytes() == f[2])322            #expect(Fe.sub(a, b).toBytes() == f[3])323            #expect(Fe.mul(a, b).toBytes() == f[4])324            #expect(Fe.invert(a).toBytes() == f[5])325            #expect(Fe.pow22523(a).toBytes() == f[6])326            count += 1327        }328        #expect(count == 41)329    }330331    @Test func constants() {332        #expect(Fe.d.toBytes() == hex("a3785913ca4deb75abd841414d0a700098e879777940c78c73fe6f2bee6c0352"))333        #expect(Self.eq(Fe.square(Fe.sqrtMinusOne), Fe.neg(.one)))334        #expect(Fe.sqrtMinusOne.toBytes() == hex("b0a00e4a271beec478e42fad0618432fa7d7fb3d99004d2b0bdfc14f8024832b"))335        #expect(Self.eq(Fe.d2, Fe.add(Fe.d, Fe.d)))336    }337338    @Test func fieldLaws() {339        for _ in 0..<2000 {340            let a = Self.random(), b = Self.random(), c = Self.random()341            #expect(Self.eq(Fe.add(a, b), Fe.add(b, a)))342            #expect(Self.eq(Fe.mul(a, b), Fe.mul(b, a)))343            #expect(Self.eq(Fe.add(Fe.add(a, b), c), Fe.add(a, Fe.add(b, c))))344            #expect(Self.eq(Fe.mul(Fe.mul(a, b), c), Fe.mul(a, Fe.mul(b, c))))345            #expect(Self.eq(Fe.mul(a, Fe.add(b, c)), Fe.add(Fe.mul(a, b), Fe.mul(a, c))))346            #expect(Self.eq(Fe.sub(Fe.add(a, b), b), a))347            #expect(Self.eq(Fe.add(a, Fe.neg(a)), .zero))348            #expect(Self.eq(Fe.mul(a, .one), a))349            #expect(Self.eq(Fe.square(a), Fe.mul(a, a)))350            #expect(Self.eq(Fe.mul(a, Fe.invert(a)), a.isZeroMask == 0 ? .one : .zero))351            #expect(Fe.equalMask(a, a) == .max && Fe.equalMask(a, Fe.add(a, .one)) == 0)352        }353        #expect(Self.eq(Fe.invert(.zero), .zero))354        #expect(Fe.zero.isZeroMask == .max && Fe.one.isZeroMask == 0)355    }356357    /// Loose representatives (limbs up to 2^52 − 1, values above p) give the same results as canonical ones.358    @Test func looseRepresentativesAndCanonicalEncoding() {359        let top: UInt64 = (1 << 52) - 1360        var rng = SystemRandomNumberGenerator()361        var loose = [Fe(top, top, top, top, top), Fe(Fe.mask51, Fe.mask51, Fe.mask51, Fe.mask51, Fe.mask51),362                     Fe(Fe.mask51 - 18, Fe.mask51, Fe.mask51, Fe.mask51, Fe.mask51), Fe(Fe.mask51 - 19, Fe.mask51, Fe.mask51, Fe.mask51, Fe.mask51),363                     Fe(top, 0, 0, 0, top), Fe(0, 0, 0, 0, top)]364        for _ in 0..<500 { loose.append(Fe(rng.next() & top, rng.next() & top, rng.next() & top, rng.next() & top, rng.next() & top)) }365        for (i, a) in loose.enumerated() {366            let canonical = Fe.fromBytes(a.toBytes())367            #expect(a.toBytes()[31] & 0x80 == 0)368            #expect(canonical.toBytes() == a.toBytes())369            let b = loose[(i * 13 + 5) % loose.count]370            let cb = Fe.fromBytes(b.toBytes())371            #expect(Self.eq(Fe.mul(a, b), Fe.mul(canonical, cb)), "mul, loose input \(i)")372            #expect(Self.eq(Fe.add(a, b), Fe.add(canonical, cb)))373            #expect(Self.eq(Fe.sub(a, b), Fe.sub(canonical, cb)))374            #expect(a.isNegative == canonical.isNegative && a.isZeroMask == canonical.isZeroMask)375        }376        // p itself and p + 1 … encode as 0 and 1 …377        #expect(loose[1].toBytes() == [18] + Bytes(repeating: 0, count: 31))378        #expect(loose[2].isZeroMask == .max)379        #expect(loose[3].toBytes() == Fe.neg(.one).toBytes())380        // bit 255 of the input is ignored by fromBytes381        var bytes = SystemRandom.bytes(32)382        bytes[31] |= 0x80383        var cleared = bytes384        cleared[31] &= 0x7f385        #expect(Self.eq(Fe.fromBytes(bytes), Fe.fromBytes(cleared)))386    }387388    @Test func selectSwapAndSquareRoots() {389        for _ in 0..<500 {390            var a = Self.random(), b = Self.random()391            let a0 = a, b0 = b392            #expect(Self.eq(Fe.select(.max, a, b), a) && Self.eq(Fe.select(0, a, b), b))393            Fe.conditionalSwap(0, &a, &b)394            #expect(Self.eq(a, a0) && Self.eq(b, b0))395            Fe.conditionalSwap(.max, &a, &b)396            #expect(Self.eq(a, b0) && Self.eq(b, a0))397            // u/v with u = r²·v is a square and the root is ±r, returned non-negative398            let r = Self.random(), v = Self.random()399            let (isSquare, root) = Fe.sqrtRatio(Fe.mul(Fe.square(r), v), v)400            #expect(isSquare == .max || v.isZeroMask == .max)401            #expect(root.isNegative == 0)402            #expect(Self.eq(root, r) || Self.eq(root, Fe.neg(r)) || v.isZeroMask == .max)403            // 2 is not a square modulo p (p ≡ 5 mod 8), so 2·r² is not a square when r ≠ 0404            let (notSquare, _) = Fe.sqrtRatio(Fe.mul(Fe(small: 2), Fe.square(r)), .one)405            #expect(notSquare == 0 || r.isZeroMask == .max)406        }407    }408409    /// The 128-bit accumulator against Swift's overflow-reporting arithmetic.410    @Test func accumulatorCarries() {411        var rng = SystemRandomNumberGenerator()412        let edges: [UInt64] = [0, 1, 0x7fff_ffff_ffff_ffff, 0x8000_0000_0000_0000, .max - 1, .max]413        for _ in 0..<3000 {414            var acc = Acc128()415            var lo: UInt64 = 0, hi: UInt64 = 0416            for _ in 0..<3 {417                // operands below 2^62 keep the running sum of three products and three words below 2^128418                let x = (edges.randomElement(using: &rng)! ^ rng.next()) >> 2, y = (edges.randomElement(using: &rng)! | rng.next()) >> 2419                acc.addProduct(x, y)420                let p = x.multipliedFullWidth(by: y)421                let (s, o) = lo.addingReportingOverflow(p.low)422                lo = s423                hi = hi &+ p.high &+ (o ? 1 : 0)424                let w = edges.randomElement(using: &rng)! | rng.next()425                acc.add(w)426                let (s2, o2) = lo.addingReportingOverflow(w)427                lo = s2428                hi = hi &+ (o2 ? 1 : 0)429            }430            #expect(acc.lo == lo && acc.hi == hi)431        }432    }433}434435@Suite struct ScalarTests {436    /// x mod ℓ by double-and-add with modular additions only (independent of the Montgomery code).437    static func slowReduce(_ bytes: Bytes) -> Sc {438        var r = Sc.zero439        for byte in bytes.reversed() {440            for bit in (0..<8).reversed() {441                r = Sc.addMod(r, r)442                if (byte >> UInt8(bit)) & 1 == 1 { r = Sc.addMod(r, .one) }443            }444        }445        return r446    }447448    static func slowMul(_ a: Sc, _ b: Bytes) -> Sc {449        var r = Sc.zero450        for byte in b.reversed() {451            for bit in (0..<8).reversed() {452                r = Sc.addMod(r, r)453                if (byte >> UInt8(bit)) & 1 == 1 { r = Sc.addMod(r, a) }454            }455        }456        return r457    }458459    @Test func referenceModelVectors() {460        var count = 0461        for line in ReferenceModelVectors.scalar.split(separator: "\n") {462            let f = fields(line).map { hex($0) }463            #expect(Sc.reduceWide(f[0]).bytes == f[1], "512-bit reduction, line \(count)")464            #expect(Sc.mulAdd(Sc(littleEndian: f[2]), Sc(littleEndian: f[3]), Sc(littleEndian: f[4])).bytes == f[5], "mulAdd, line \(count)")465            count += 1466        }467        #expect(count == 29)468    }469470    @Test func reductionAndMultiplyAddAgainstSlowReference() {471        var edges: [Bytes] = [Bytes(repeating: 0, count: 64), Bytes(repeating: 0xff, count: 64), orderBytes + Bytes(repeating: 0, count: 32),472                              Bytes(repeating: 0, count: 32) + orderBytes, Bytes(repeating: 0xff, count: 32) + Bytes(repeating: 0, count: 32)]473        for _ in 0..<1500 { edges.append(SystemRandom.bytes(64)) }474        for wide in edges {475            let reduced = Sc.reduceWide(wide)476            #expect(reduced.bytes == Self.slowReduce(wide).bytes)477            #expect(reduced.isCanonical)478            let a = reduced, b = Bytes(wide[16..<48]), c = Sc.reduce(Sc(littleEndian: Bytes(wide[32...])))479            let expected = Sc.addMod(Self.slowMul(a, b), c)480            #expect(Sc.mulAdd(a, Sc(littleEndian: b), c).bytes == expected.bytes)481        }482        #expect(Sc.reduce(Sc.order).bytes == Sc.zero.bytes)483        #expect(Sc.reduce(Sc(.max, .max, .max, .max)).bytes == Self.slowReduce(Bytes(repeating: 0xff, count: 32)).bytes)484        #expect(Sc.order.bytes == orderBytes)485    }486}487488@Suite struct GroupTests {489    static func randomPoint() -> EdPoint { EdPoint.multiplyBase(scalar: SystemRandom.bytes(32)) }490491    /// Variable-time double-and-add, the reference for the fixed-window multiplication.492    static func slowMultiply(_ scalar: Bytes, _ p: EdPoint) -> EdPoint {493        var r = EdPoint.identity494        for byte in scalar.reversed() {495            for bit in (0..<8).reversed() {496                r = EdPoint.double(r)497                if (byte >> UInt8(bit)) & 1 == 1 { r = EdPoint.add(r, p) }498            }499        }500        return r501    }502503    @Test func basePointAndOrder() {504        #expect(EdPoint.base.isValid)505        #expect(EdPoint.base.encode() == hex("5866666666666666666666666666666666666666666666666666666666666666"))506        // x of the base point (RFC 8032 §5.1)507        #expect(EdPoint.base.x.toBytes() == hex("1ad5258f602d56c9b2a7259560c72c695cdcd6fd31e2a4c0fe536ecdd3366921"))508        #expect(EdPoint.multiplyBase(scalar: orderBytes).isIdentity)509        #expect(!EdPoint.base.isSmallOrder && EdPoint.identity.isSmallOrder && EdPoint.identity.isIdentity)510        var minusOne = orderBytes511        minusOne[0] -= 1512        #expect(EdPoint.equal(EdPoint.multiplyBase(scalar: minusOne), EdPoint.negate(.base)))513        #expect(EdPoint.baseTable.count == 16 && EdPoint.baseTable.allSatisfy(\.isValid))514        // the base table is shifted by one (entry w is (w + 1)·B: no neutral element, QYV-AUD-006) and the constant515        // removed at the end is [0x11…11]B516        var multiple = EdPoint.base517        for entry in EdPoint.baseTable {518            #expect(EdPoint.equal(entry, multiple) && !entry.isIdentity && !entry.isSmallOrder)519            multiple = EdPoint.add(multiple, .base)520        }521        #expect(EdPoint.add(EdPoint.baseOffset, Self.slowMultiply(Bytes(repeating: 0x11, count: 32), .base)).isIdentity)522    }523524    @Test func groupLaws() {525        for _ in 0..<300 {526            let p = Self.randomPoint(), q = Self.randomPoint(), r = Self.randomPoint()527            #expect(p.isValid)528            #expect(EdPoint.equal(EdPoint.add(p, q), EdPoint.add(q, p)))529            #expect(EdPoint.equal(EdPoint.add(EdPoint.add(p, q), r), EdPoint.add(p, EdPoint.add(q, r))))530            #expect(EdPoint.equal(EdPoint.add(p, .identity), p))531            #expect(EdPoint.add(p, EdPoint.negate(p)).isIdentity)532            #expect(EdPoint.equal(EdPoint.double(p), EdPoint.add(p, p)))533            #expect(EdPoint.add(p, q).isValid && EdPoint.double(p).isValid)534            let encoded = p.encode()535            let decoded = EdPoint.decode(encoded, strict: true)536            #expect(decoded != nil && EdPoint.equal(decoded!, p) && decoded!.encode() == encoded)537        }538    }539540    /// The unified addition is complete: it also adds and doubles the eight torsion points correctly.541    @Test func completeOnTorsionPoints() {542        let torsion = smallOrderEncodings.map { EdPoint.decode(hex($0), strict: true)! }543        for t in torsion {544            #expect(t.isValid && t.isSmallOrder)545            #expect(EdPoint.equal(EdPoint.double(t), EdPoint.add(t, t)))546            for u in torsion {547                let sum = EdPoint.add(t, u)548                #expect(sum.isValid && sum.isSmallOrder)549                #expect(smallOrderEncodings.contains(sum.encode().hex))550            }551            let mixed = EdPoint.add(t, .base)552            #expect(mixed.isValid && !mixed.isSmallOrder)553            #expect(EdPoint.equal(EdPoint.add(mixed, EdPoint.negate(t)), .base))554        }555    }556557    @Test func scalarMultiplication() {558        var scalars: [Bytes] = [Bytes(repeating: 0, count: 32), [1] + Bytes(repeating: 0, count: 31), orderBytes,559                                Bytes(repeating: 0xff, count: 32), Bytes(repeating: 0xff, count: 31) + [0x7f],560                                Bytes(repeating: 0, count: 31) + [0x80], Bytes(repeating: 0x0f, count: 32), Bytes(repeating: 0xf0, count: 32)]561        var minusOne = orderBytes562        minusOne[0] -= 1563        scalars.append(minusOne)564        for _ in 0..<150 { scalars.append(SystemRandom.bytes(32)) }565        let p = Self.randomPoint()566        for s in scalars {567            #expect(EdPoint.equal(EdPoint.multiplyBase(scalar: s), Self.slowMultiply(s, .base)), "base, scalar \(s.hex)")568            #expect(EdPoint.equal(EdPoint.multiply(scalar: s, p), Self.slowMultiply(s, p)), "point, scalar \(s.hex)")569        }570        #expect(EdPoint.multiplyBase(scalar: scalars[0]).isIdentity)571        #expect(EdPoint.equal(EdPoint.multiplyBase(scalar: scalars[1]), .base))572        // [a]B + [b]B = [a + b mod ℓ]B573        for _ in 0..<100 {574            let a = Sc.reduceWide(SystemRandom.bytes(64)), b = Sc.reduceWide(SystemRandom.bytes(64))575            let sum = Sc.addMod(a, b)576            #expect(EdPoint.equal(EdPoint.add(EdPoint.multiplyBase(scalar: a.bytes), EdPoint.multiplyBase(scalar: b.bytes)),577                                  EdPoint.multiplyBase(scalar: sum.bytes)))578        }579    }580581    @Test func maskedLookupReturnsTheRequestedEntry() {582        EdPoint.baseTable.withUnsafeBufferPointer { t in583            for i in 0..<16 {584                #expect(EdPoint.lookup(t.baseAddress!, UInt64(i)).encode() == EdPoint.baseTable[i].encode())585            }586        }587    }588}589
Files main
Menu

Theme