SPB Git

Repository Public

Ed25519DiffTests.swift 35.1 KB 577 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/DifferentialAuditTests/Ed25519DiffTests.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 CryptoKit43import Foundation44import QyvoraMath45import Testing4647@testable import QyvoraEd255194849// Ed25519 against independent implementations (test environment only):50//   - an integer transcription of RFC 8032 written for this audit (Python integers: field, scalars, group,51//     decoding, both verification equations) — the "bigint" oracle, which also evaluates the documented strict52//     policy rule by rule;53//   - libsodium (PyNaCl), OpenSSL (python `cryptography`), ed25519-dalek `verify_strict` (solders, the Solana SDK),54//     Apple CryptoKit, bip-utils and a direct HMAC transcription for SLIP-0010.55//56// Where the verification policies legitimately differ, the difference is asserted in ONE direction and counted:57//   - ed25519-dalek verify_strict and libsodium: no difference observed on any generated input (same verdicts);58//   - OpenSSL and CryptoKit accept inputs the engine refuses (small-order public keys, small-order R, non-canonical59//     encodings of a small-order public key); the engine never accepts what one of them refuses.6061enum EdCraft {62    /// The eight points of the torsion subgroup, found by multiplying random curve points by ℓ (no table).63    static let torsion: [EdPoint] = {64        var found = [String: EdPoint]()65        var rng = AuditRNG(seed: 0x746f_7273_696f_6e)66        while found.count < 8 {67            guard let p = EdPoint.decode(rng.bytes(32), strict: false) else { continue }68            let t = EdPoint.multiply(scalar: Sc.order.bytes, p)69            found[Hex.encode(t.encode())] = t70        }71        // the neutral element first, then the seven others in the order of their encodings72        let neutral = Hex.encode(EdPoint.identity.encode())73        return ([neutral] + found.keys.filter { $0 != neutral }.sorted()).compactMap { found[$0] }74    }()7576    /// Encodings that are not canonical: y ≥ p (p, p + 1 … of the points with y = 0, 1 …) and "x = 0 with the sign bit".77    static let nonCanonical: [Bytes] = {78        func le(_ low: UInt8, top: UInt8) -> Bytes { [low] + Bytes(repeating: 0xff, count: 30) + [top] }79        var out: [Bytes] = [80            le(0xee, top: 0x7f),  // y = p + 1: the neutral element81            le(0xee, top: 0xff),  // the same with the sign bit82            le(0xed, top: 0x7f),  // y = p: a point of order 483            le(0xed, top: 0xff),84            le(0xec, top: 0xff),  // y = p − 1 (order 2, x = 0) with the sign bit85            [0x01] + Bytes(repeating: 0, count: 30) + [0x80],  // the neutral element with the sign bit86        ]87        for low in UInt8(0xef)...UInt8(0xff) { out.append(le(low, top: 0x7f)) }  // y = p + 2 … p + 1888        return out89    }()9091    static func scalar(_ rng: inout AuditRNG) -> Sc { Sc.reduceWide(rng.bytes(64)) }9293    struct Input {94        let label: String95        let publicKey: Bytes, message: Bytes, signature: Bytes96        var json: [String: Any] { ["public_key": Hex.encode(publicKey), "message": Hex.encode(message), "signature": Hex.encode(signature)] }97    }9899    /// One verification input of the class chosen by `kind` (see the labels).100    static func input(_ kind: Int, _ rng: inout AuditRNG) -> Input {101        let seed = rng.bytes(32)102        let message = rng.bytes(rng.pick([0, 1, 31, 32, 33, 64, 111, 112, 127, 128, 129, rng.int(0...300)]))103        let (aBytes, _) = Ed25519.expand(seed: seed)104        let a = Sc(littleEndian: aBytes)105        let honestKey = EdPoint.multiplyBase(scalar: aBytes)106        let honestPK = honestKey.encode()107        let honest = (try? Ed25519.sign(message: message, seed: seed)) ?? Bytes(repeating: 0, count: 64)108        let r = scalar(&rng)109        let rB = EdPoint.multiplyBase(scalar: r.bytes)110        func sign(_ encodedR: Bytes, _ pk: Bytes, secret: Sc, nonce: Sc) -> Bytes {111            let k = Ed25519.challenge(encodedR: encodedR, publicKey: pk, message: message)112            return encodedR + Sc.mulAdd(k, secret, nonce).bytes113        }114        switch kind {115        case 0: return Input(label: "valid", publicKey: honestPK, message: message, signature: honest)116        case 1:117            var pk = honestPK, m = message, s = honest118            switch rng.int(0...2) {119            case 0: s[rng.int(0...63)] ^= 1 << UInt8(rng.int(0...7))120            case 1 where !m.isEmpty: m[rng.int(0...(m.count - 1))] ^= 1 << UInt8(rng.int(0...7))121            default: pk[rng.int(0...31)] ^= 1 << UInt8(rng.int(0...7))122            }123            return Input(label: "bit-flip", publicKey: pk, message: m, signature: s)124        case 2:125            let s = Sc(littleEndian: Bytes(honest[32..<64]))126            return Input(label: "s-plus-order", publicKey: honestPK, message: message, signature: Bytes(honest[0..<32]) + Sc.addWide(s, Sc.order).0.bytes)127        case 3:128            // mixed-order public key A + T: valid for the cofactorless equation exactly when k·T is the neutral element129            let pk = EdPoint.add(honestKey, torsion[rng.int(1...7)]).encode()130            return Input(label: "mixed-order-key", publicKey: pk, message: message, signature: sign(rB.encode(), pk, secret: a, nonce: r))131        case 4:132            let encodedR = EdPoint.add(rB, torsion[rng.int(1...7)]).encode()133            return Input(label: "mixed-order-r", publicKey: honestPK, message: message, signature: sign(encodedR, honestPK, secret: a, nonce: r))134        case 5:135            let pk = torsion[rng.int(0...7)].encode()136            return Input(label: "small-order-key", publicKey: pk, message: message, signature: rB.encode() + r.bytes)137        case 6:138            // small-order R: with R the neutral element and S = k·a the cofactorless equation holds139            let encodedR = torsion[rng.pick([0, 0, 0, 1, 2, 3, 4, 5, 6, 7])].encode()140            let s = rng.bool() ? sign(encodedR, honestPK, secret: a, nonce: .zero) : encodedR + Bytes(repeating: 0, count: 32)141            return Input(label: "small-order-r", publicKey: honestPK, message: message, signature: s)142        case 7:143            let encodedR = rng.pick(nonCanonical)144            return Input(label: "non-canonical-r", publicKey: honestPK, message: message, signature: sign(encodedR, honestPK, secret: a, nonce: .zero))145        case 8:146            let pk = rng.pick(nonCanonical)147            return Input(label: "non-canonical-key", publicKey: pk, message: message, signature: rB.encode() + r.bytes)148        case 9:149            // mixed-order key AND small-order R: R = T', valid for the cofactorless equation when −k·T = T'150            let pk = EdPoint.add(honestKey, torsion[rng.int(1...7)]).encode()151            let encodedR = torsion[rng.int(0...7)].encode()152            return Input(label: "mixed-order-key-small-order-r", publicKey: pk, message: message, signature: sign(encodedR, pk, secret: a, nonce: .zero))153        case 10:154            var s = honest, pk = honestPK155            switch rng.int(0...3) {156            case 0: s.removeLast(rng.int(1...3))157            case 1: s += rng.bytes(rng.int(1...3))158            case 2: pk.removeLast()159            default: pk.append(0)160            }161            return Input(label: "wrong-length", publicKey: pk, message: message, signature: s)162        case 11:163            // boundary values of S with an honest R164            let s = rng.pick([Sc.zero, Sc.one, Sc.order, Sc.subWide(Sc.order, .one).0, Sc(UInt64.max, UInt64.max, UInt64.max, UInt64.max)])165            return Input(label: "boundary-s", publicKey: honestPK, message: message, signature: Bytes(honest[0..<32]) + s.bytes)166        default:167            return Input(label: "random", publicKey: rng.bytes(32), message: message, signature: rng.bytes(64))168        }169    }170171    static let kinds = 13172}173174@Suite struct Ed25519Differential {175    static let script = "ed25519"176177    static var references: String {178        [MCOracle.label(script, "pynacl", "libsodium"), MCOracle.label(script, "cryptography", MCOracle.versions(script)?["openssl"] ?? "OpenSSL"),179         MCOracle.label(script, "solders", "ed25519-dalek verify_strict"), "integer transcription of RFC 8032"].joined(separator: "; ")180    }181182    // MARK: Keys and signatures183184    @Test func publicKeysAndSignaturesAreByteIdentical() throws {185        let name = "ed25519-keys-signatures"186        guard MCOracle.available(Self.script, campaign: name, needs: ["pynacl", "cryptography", "solders"]) else { return }187        let seed = DiffSeed.make(name)188        var rng = AuditRNG(seed: seed)189        var tally = DiffTally(name, algorithm: "Ed25519", oracle: Self.references, seed: seed)190        let n = AuditMode.cases(quick: 400, full: 5000)191        var cases = [(Bytes, Bytes)]()192        let edgeSeeds: [Bytes] = [Bytes(repeating: 0, count: 32), Bytes(repeating: 0xff, count: 32), Bytes(0..<32)]193        for i in 0..<n {194            let s = i < edgeSeeds.count ? edgeSeeds[i] : rng.bytes(32)195            cases.append((s, rng.bytes(rng.edgeLength(block: 128, max: 400))))196        }197        let keys = try MCOracle.batch(Self.script, "keys", cases.map { ["seed": Hex.encode($0.0)] })198        let sigs = try MCOracle.batch(Self.script, "sign", cases.map { ["seed": Hex.encode($0.0), "message": Hex.encode($0.1)] })199        for (i, c) in cases.enumerated() {200            let pk = try Ed25519.publicKey(seed: c.0)201            let sig = try Ed25519.sign(message: c.1, seed: c.0)202            for ref in ["bigint", "pynacl", "cryptography", "solders"] {203                tally.check(keys[i][ref] as? String == Hex.encode(pk), "public key vs \(ref): seed \(Hex.encode(c.0))")204                tally.check(sigs[i][ref] as? String == Hex.encode(sig), "signature vs \(ref): seed \(Hex.encode(c.0)) message \(Hex.encode(c.1))")205            }206        }207        #expect(tally.finish() == 0)208    }209210    @Test func cryptoKitKeysAndCrossVerification() throws {211        let name = "ed25519-cryptokit"212        let seed = DiffSeed.make(name)213        var rng = AuditRNG(seed: seed)214        var tally = DiffTally(name, algorithm: "Ed25519", oracle: "Apple CryptoKit (Curve25519.Signing)", seed: seed)215        for _ in 0..<AuditMode.cases(quick: 300, full: 3000) {216            let s = rng.bytes(32), message = rng.bytes(rng.edgeLength(block: 128, max: 300))217            let reference = try Curve25519.Signing.PrivateKey(rawRepresentation: Data(s))218            let pk = try Ed25519.publicKey(seed: s)219            tally.check(Bytes(reference.publicKey.rawRepresentation) == pk, "public key: seed \(Hex.encode(s))")220            // ours verified by CryptoKit221            let ours = try Ed25519.sign(message: message, seed: s)222            tally.check(reference.publicKey.isValidSignature(Data(ours), for: Data(message)), "CryptoKit refuses our signature: seed \(Hex.encode(s))")223            // CryptoKit's (randomised) signature verified by us, and refused after one bit flip224            var theirs = Bytes(try reference.signature(for: Data(message)))225            tally.check(Ed25519.verify(signature: theirs, message: message, publicKey: pk), "CryptoKit signature refused: \(Hex.encode(theirs))")226            theirs[rng.int(0...63)] ^= 1 << UInt8(rng.int(0...7))227            let oursVerdict = Ed25519.verify(signature: theirs, message: message, publicKey: pk)228            let theirVerdict = reference.publicKey.isValidSignature(Data(theirs), for: Data(message))229            tally.verdict(oursVerdict)230            tally.check(oursVerdict == theirVerdict && !oursVerdict, "altered signature: ours \(oursVerdict), CryptoKit \(theirVerdict)")231        }232        #expect(tally.finish() == 0)233    }234235    // MARK: Verification agreement on random and adversarial inputs236237    @Test func verificationAgreementOnAdversarialInputs() throws {238        let name = "ed25519-verify-adversarial"239        guard MCOracle.available(Self.script, campaign: name, needs: ["pynacl", "cryptography", "solders"]) else { return }240        let seed = DiffSeed.make(name)241        var rng = AuditRNG(seed: seed)242        var tally = DiffTally(name, algorithm: "Ed25519", parameterSet: "strict", oracle: Self.references + "; Apple CryptoKit", seed: seed)243        let n = AuditMode.cases(quick: 650, full: 6500)244        let inputs = (0..<n).map { EdCraft.input($0 % EdCraft.kinds, &rng) }245        let answers = try MCOracle.batch(Self.script, "verify", inputs.map(\.json))246        var perClass = [String: (total: Int, accepted: Int)]()247        var opensslLenient = [String: Int](), cryptoKitLenient = [String: Int]()248        for (i, input) in inputs.enumerated() {249            let ans = answers[i]250            let ours = Ed25519.verify(signature: input.signature, message: input.message, publicKey: input.publicKey)251            tally.verdict(ours)252            var c = perClass[input.label] ?? (0, 0)253            c.total += 1254            if ours { c.accepted += 1 }255            perClass[input.label] = c256            let detail = "\(input.label): pk \(Hex.encode(input.publicKey)) msg \(Hex.encode(input.message)) sig \(Hex.encode(input.signature))"257            // 1. the documented policy, evaluated rule by rule by the integer reference258            tally.check(ans["bigint_strict"] as? Bool == ours, "policy (integer reference) \(String(describing: ans["bigint_strict"])) vs ours \(ours) — \(detail)")259            // 2. ed25519-dalek verify_strict (what a Solana validator applies) and libsodium: same verdict260            tally.check(ans["solders"] as? Bool == ours, "ed25519-dalek verify_strict \(String(describing: ans["solders"])) vs ours \(ours) — \(detail)")261            tally.check(ans["pynacl"] as? Bool == ours, "libsodium \(String(describing: ans["pynacl"])) vs ours \(ours) — \(detail)")262            // 3. OpenSSL and CryptoKit: the engine never accepts what they refuse; what they accept and the engine263            //    refuses must be one of the documented classes264            let cls = ans["class"] as? [String: Any] ?? [:]265            let documented = cls["a_small_order"] as? Bool == true || cls["r_small_order"] as? Bool == true266                || cls["a_canonical"] as? Bool == false || cls["r_canonical"] as? Bool == false267            let openssl = ans["cryptography"] as? Bool ?? false268            tally.check(!ours || openssl, "accepted here, refused by OpenSSL — \(detail)")269            if openssl, !ours {270                opensslLenient[input.label, default: 0] += 1271                tally.check(documented, "OpenSSL accepts, engine refuses, outside the documented classes — \(detail)")272            }273            var cryptoKit = false274            if input.publicKey.count == 32, let key = try? Curve25519.Signing.PublicKey(rawRepresentation: Data(input.publicKey)) {275                cryptoKit = key.isValidSignature(Data(input.signature), for: Data(input.message))276            }277            tally.check(!ours || cryptoKit, "accepted here, refused by CryptoKit — \(detail)")278            if cryptoKit, !ours {279                cryptoKitLenient[input.label, default: 0] += 1280                tally.check(documented || cls["cofactored"] as? Bool == true, "CryptoKit accepts, engine refuses, outside the documented classes — \(detail)")281            }282        }283        // every class was exercised, and the classes that can be valid produced accepted cases284        #expect(perClass.count == EdCraft.kinds)285        #expect(perClass["valid"].map { $0.accepted == $0.total } == true)286        if n >= 600 { #expect((perClass["mixed-order-key"]?.accepted ?? 0) > 0, "no cofactorless-valid mixed-order case generated") }287        for label in ["bit-flip", "s-plus-order", "mixed-order-r", "small-order-key", "small-order-r", "non-canonical-r", "non-canonical-key",288                      "mixed-order-key-small-order-r", "wrong-length", "boundary-s", "random"] {289            #expect(perClass[label]?.accepted == 0, "\(label): an input of this class was accepted")290        }291        let failed = tally.finish()292        let summary = perClass.sorted { $0.key < $1.key }.map { "\($0.key) \($0.value.accepted)/\($0.value.total)" }.joined(separator: ", ")293        AuditRecorder.record(294            area: "differential", name: name + "/policy-differences", algorithm: "Ed25519", parameterSet: "strict", oracle: "OpenSSL, CryptoKit",295            cases: n, failed: 0, seed: seed,296            note: "accepted/total per class: \(summary). Refused here but accepted by OpenSSL: \(opensslLenient.sorted { $0.key < $1.key }); by CryptoKit: \(cryptoKitLenient.sorted { $0.key < $1.key }). No input accepted here and refused by a reference.")297        #expect(failed == 0)298    }299300    /// The Wycheproof and speccheck files against ed25519-dalek verify_strict and libsodium: same verdict on every case.301    @Test func vectorFilesAgreeWithDalekStrict() throws {302        let name = "ed25519-vector-files-vs-references"303        guard MCOracle.available(Self.script, campaign: name, needs: ["pynacl", "solders"]) else { return }304        var tally = DiffTally(name, algorithm: "Ed25519", parameterSet: "strict", oracle: Self.references, seed: 0)305        var inputs = [EdCraft.Input]()306        for g in try AuditVectors.acvpGroups(AuditPaths.vectors.appendingPathComponent("wycheproof/ed25519_test.json.gz")) {307            guard let pk = (g["publicKey"] as? [String: Any])?.hex("pk") else { continue }308            for t in g.acvpTests {309                if let m = t.hex("msg"), let s = t.hex("sig") { inputs.append(.init(label: "wycheproof \(t["tcId"] ?? "?")", publicKey: pk, message: m, signature: s)) }310            }311        }312        let spec = try #require(try AuditVectors.json(AuditPaths.vectors.appendingPathComponent("ed25519/speccheck-cases.json")) as? [[String: Any]])313        for (i, c) in spec.enumerated() {314            if let pk = c.hex("pub_key"), let m = c.hex("message"), let s = c.hex("signature") {315                inputs.append(.init(label: "speccheck \(i)", publicKey: pk, message: m, signature: s))316            }317        }318        #expect(inputs.count >= 222)319        let answers = try MCOracle.batch(Self.script, "verify", inputs.map(\.json))320        for (i, input) in inputs.enumerated() {321            let ours = Ed25519.verify(signature: input.signature, message: input.message, publicKey: input.publicKey)322            tally.verdict(ours)323            tally.check(answers[i]["solders"] as? Bool == ours, "\(input.label): ed25519-dalek \(String(describing: answers[i]["solders"])) ours \(ours)")324            tally.check(answers[i]["pynacl"] as? Bool == ours, "\(input.label): libsodium \(String(describing: answers[i]["pynacl"])) ours \(ours)")325            tally.check(answers[i]["bigint_strict"] as? Bool == ours, "\(input.label): integer policy \(String(describing: answers[i]["bigint_strict"])) ours \(ours)")326        }327        #expect(tally.finish() == 0)328    }329330    // MARK: Arithmetic against Python integers331332    static let limbEdges: [UInt64] = [333        0, 1, 2, 18, 19, 20, (1 << 51) - 20, (1 << 51) - 19, (1 << 51) - 18, (1 << 51) - 2, (1 << 51) - 1, 1 << 51, (1 << 51) + 1,334        (1 << 51) + 18, (1 << 51) + 19, (1 << 52) - 20, (1 << 52) - 2, (1 << 52) - 1, 0x000a_aaaa_aaaa_aaaa, 0x0005_5555_5555_5555,335    ]336337    /// A loose field element: every limb below 2^52, edges one time in three.338    static func looseElement(_ rng: inout AuditRNG) -> Fe {339        func limb(_ rng: inout AuditRNG) -> UInt64 { rng.int(0...2) == 0 ? rng.pick(limbEdges) : rng.next() & ((1 << 52) - 1) }340        switch rng.int(0...11) {341        case 0: return Fe(rng.pick(limbEdges), 0, 0, 0, 0)342        case 1: let v = rng.pick(limbEdges); return Fe(v, v, v, v, v)343        case 2: return Fe((1 << 51) - 19, (1 << 51) - 1, (1 << 51) - 1, (1 << 51) - 1, (1 << 51) - 1)  // p344        case 3: return Fe((1 << 51) - 20 + UInt64(rng.int(0...40)), (1 << 51) - 1, (1 << 51) - 1, (1 << 51) - 1, (1 << 51) - 1)  // around p345        case 4: return Fe((1 << 52) - 38 + UInt64(rng.int(0...37)), (1 << 52) - 1, (1 << 52) - 1, (1 << 52) - 1, (1 << 52) - 1)  // around 2p .. the largest loose value346        default: return Fe(limb(&rng), limb(&rng), limb(&rng), limb(&rng), limb(&rng))347        }348    }349350    static func limbs(_ f: Fe) -> [String] { [f.l0, f.l1, f.l2, f.l3, f.l4].map(String.init) }351352    @Test func fieldArithmeticAgainstIntegers() throws {353        let name = "ed25519-field-vs-integers"354        guard MCOracle.available(Self.script, campaign: name) else { return }355        let seed = DiffSeed.make(name)356        var rng = AuditRNG(seed: seed)357        var tally = DiffTally(name, algorithm: "GF(2^255-19)", oracle: "Python integers", seed: seed)358        let n = AuditMode.cases(quick: 1500, full: 20_000)359        let pairs = (0..<n).map { _ in (Self.looseElement(&rng), Self.looseElement(&rng)) }360        let answers = try MCOracle.batch(Self.script, "field", pairs.map { ["a": Self.limbs($0.0), "b": Self.limbs($0.1)] })361        for (i, (a, b)) in pairs.enumerated() {362            let ans = answers[i]363            func eq(_ key: String, _ value: Fe) -> Bool { ans[key] as? String == Hex.encode(value.toBytes()) }364            let detail = "a \(Self.limbs(a)) b \(Self.limbs(b))"365            tally.check(eq("a", a), "toBytes: \(detail)")366            tally.check(eq("add", Fe.add(a, b)), "add: \(detail)")367            tally.check(eq("sub", Fe.sub(a, b)), "sub: \(detail)")368            tally.check(eq("mul", Fe.mul(a, b)), "mul: \(detail)")369            tally.check(eq("square", Fe.square(a)), "square: \(detail)")370            tally.check(eq("neg", Fe.neg(a)), "neg: \(detail)")371            tally.check(eq("invert", Fe.invert(a)), "invert: \(detail)")372            tally.check(eq("pow22523", Fe.pow22523(a)), "pow22523: \(detail)")373            tally.check((a.isZeroMask == UInt64.max) == (ans["is_zero"] as? Bool ?? false) && (a.isZeroMask == 0 || a.isZeroMask == UInt64.max), "isZero: \(detail)")374            tally.check((a.isNegative == 1) == (ans["is_negative"] as? Bool ?? false) && a.isNegative <= 1, "isNegative: \(detail)")375            tally.check((Fe.equalMask(a, b) == UInt64.max) == (ans["equal"] as? Bool ?? false), "equal: \(detail)")376            let (isSquare, root) = Fe.sqrtRatio(a, b)377            let expectedSquare = ans["sqrt_is_square"] as? Bool ?? false378            tally.check((isSquare == UInt64.max) == expectedSquare && (isSquare == 0 || isSquare == UInt64.max), "sqrtRatio square: \(detail)")379            if expectedSquare, isSquare != 0 { tally.check(eq("sqrt_root", root), "sqrtRatio root: \(detail)") }380        }381        #expect(tally.finish() == 0)382    }383384    @Test func fieldDecodingAgainstIntegers() throws {385        let name = "ed25519-field-bytes-vs-integers"386        guard MCOracle.available(Self.script, campaign: name) else { return }387        let seed = DiffSeed.make(name)388        var rng = AuditRNG(seed: seed)389        var tally = DiffTally(name, algorithm: "GF(2^255-19)", oracle: "Python integers", seed: seed)390        var inputs = [Bytes]()391        // every encoding from p − 20 to p + 18 with and without bit 255, and 2^255 − 1392        for delta in -20...18 {393            var v = Bytes(repeating: 0xff, count: 32)394            v[31] = 0x7f395            v[0] = UInt8(truncatingIfNeeded: 0xed + delta)396            if delta < -0xed { continue }397            inputs.append(v)398            v[31] = 0xff399            inputs.append(v)400        }401        inputs.append(Bytes(repeating: 0, count: 32))402        inputs.append(Bytes(repeating: 0xff, count: 32))403        for _ in 0..<AuditMode.cases(quick: 1500, full: 20_000) {404            var v = rng.bytes(32)405            if rng.int(0...3) == 0 { for j in rng.int(1...31)..<32 { v[j] = 0xff } }406            inputs.append(v)407        }408        let answers = try MCOracle.batch(Self.script, "field_bytes", inputs.map { ["bytes": Hex.encode($0)] })409        for (i, v) in inputs.enumerated() {410            let fe = Fe.fromBytes(v)411            tally.check(answers[i]["canonical"] as? String == Hex.encode(fe.toBytes()), "fromBytes/toBytes \(Hex.encode(v))")412            // loose invariant after decoding: every limb below 2^51413            tally.check(max(fe.l0, fe.l1, fe.l2, fe.l3, fe.l4) < (1 << 51), "limb range \(Hex.encode(v))")414        }415        #expect(tally.finish() == 0)416    }417418    @Test func scalarArithmeticAgainstIntegers() throws {419        let name = "ed25519-scalar-vs-integers"420        guard MCOracle.available(Self.script, campaign: name) else { return }421        let seed = DiffSeed.make(name)422        var rng = AuditRNG(seed: seed)423        var tally = DiffTally(name, algorithm: "integers modulo ℓ", oracle: "Python integers", seed: seed)424        let order = Sc.order.bytes425        func around(_ base: Bytes, _ delta: Int) -> Bytes {426            // base + delta for small |delta| (little endian)427            var out = base428            var carry = delta429            for j in 0..<out.count {430                let v = Int(out[j]) + carry431                out[j] = UInt8(truncatingIfNeeded: v)432                carry = v >> 8433                if carry == 0 { break }434            }435            return out436        }437        var edges: [Bytes] = [Bytes(repeating: 0, count: 32), Bytes(repeating: 0xff, count: 32), [1] + Bytes(repeating: 0, count: 31)]438        for d in -3...3 { edges.append(around(order, d)) }439        var twiceOrder = Sc.addWide(Sc.order, Sc.order).0.bytes440        edges.append(twiceOrder)441        twiceOrder = around(twiceOrder, -1)442        edges.append(twiceOrder)443        for limb in 0..<4 {444            var v = Bytes(repeating: 0, count: 32)445            for j in 0..<8 { v[limb * 8 + j] = 0xff }446            edges.append(v)447            edges.append(v.map { ~$0 })448        }449        let n = AuditMode.cases(quick: 2000, full: 30_000)450        var cases = [(Bytes, Bytes, Bytes, Bytes)]()451        for _ in 0..<n {452            let wide = rng.int(0...7) == 0 ? rng.pick(edges) + rng.pick(edges) : rng.bytes(64)453            cases.append((rng.bytes(32, orEdge: edges, oneIn: 4), rng.bytes(32, orEdge: edges, oneIn: 4), rng.bytes(32, orEdge: edges, oneIn: 4), wide))454        }455        let answers = try MCOracle.batch(Self.script, "scalar", cases.map {456            ["a": Hex.encode($0.0), "b": Hex.encode($0.1), "c": Hex.encode($0.2), "wide": Hex.encode($0.3)]457        })458        for (i, c) in cases.enumerated() {459            let ans = answers[i]460            let a = Sc(littleEndian: c.0), b = Sc(littleEndian: c.1), cc = Sc(littleEndian: c.2)461            let detail = "a \(Hex.encode(c.0)) b \(Hex.encode(c.1)) c \(Hex.encode(c.2))"462            let ra = Sc.reduce(a), rc = Sc.reduce(cc)463            tally.check(ans["reduce"] as? String == Hex.encode(ra.bytes), "reduce: \(detail)")464            tally.check(ans["reduce_wide"] as? String == Hex.encode(Sc.reduceWide(c.3).bytes), "reduceWide: \(Hex.encode(c.3))")465            tally.check(ans["mul_add"] as? String == Hex.encode(Sc.mulAdd(ra, b, rc).bytes), "mulAdd: \(detail)")466            tally.check(ans["add"] as? String == Hex.encode(Sc.addMod(ra, rc).bytes), "addMod: \(detail)")467            tally.check(ans["mont_mul"] as? String == Hex.encode(Sc.montMul(ra, b).bytes), "montMul: \(detail)")468            tally.check(ans["is_canonical"] as? Bool == a.isCanonical, "isCanonical: \(detail)")469            // every result is fully reduced470            tally.check(ra.isCanonical && Sc.reduceWide(c.3).isCanonical && Sc.mulAdd(ra, b, rc).isCanonical && Sc.montMul(ra, b).isCanonical, "range: \(detail)")471        }472        #expect(tally.finish() == 0)473    }474475    @Test func groupOperationsAndDecodingAgainstIntegers() throws {476        let name = "ed25519-group-vs-integers"477        guard MCOracle.available(Self.script, campaign: name, needs: ["solders", "pynacl"]) else { return }478        let seed = DiffSeed.make(name)479        var rng = AuditRNG(seed: seed)480        var tally = DiffTally(481            name, algorithm: "edwards25519", oracle: "Python integers (RFC 8032 formulas); solders is_on_curve; libsodium base multiplication", seed: seed)482        let order = Sc.order.bytes483        var scalarEdges: [Bytes] = [Bytes(repeating: 0, count: 32), Bytes(repeating: 0xff, count: 32), order, Sc.subWide(Sc.order, .one).0.bytes]484        for v in [UInt8(1), 2, 7, 8, 15, 16, 17] { scalarEdges.append([v] + Bytes(repeating: 0, count: 31)) }485        scalarEdges.append(Bytes(repeating: 0, count: 31) + [0x80])486        scalarEdges.append(Bytes(repeating: 0xf0, count: 32))487        scalarEdges.append(Bytes(repeating: 0x0f, count: 32))488        var pointEdges = EdCraft.torsion.map { $0.encode() } + EdCraft.nonCanonical489        pointEdges.append(EdPoint.base.encode())490        func point(_ rng: inout AuditRNG) -> Bytes {491            switch rng.int(0...5) {492            case 0: return rng.pick(pointEdges)493            case 1: return rng.bytes(32)  // about half of them are not on the curve494            case 2: return EdPoint.add(EdPoint.multiplyBase(scalar: rng.bytes(32)), rng.pick(EdCraft.torsion)).encode()495            default: return EdPoint.multiplyBase(scalar: rng.bytes(32)).encode()496            }497        }498        let n = AuditMode.cases(quick: 400, full: 5000)499        let cases = (0..<n).map { _ in (point(&rng), point(&rng), rng.bytes(32, orEdge: scalarEdges, oneIn: 5)) }500        let answers = try MCOracle.batch(Self.script, "point", cases.map { ["p": Hex.encode($0.0), "q": Hex.encode($0.1), "scalar": Hex.encode($0.2)] })501        var decoded = 0502        for (i, c) in cases.enumerated() {503            let ans = answers[i]504            let detail = "p \(Hex.encode(c.0)) q \(Hex.encode(c.1)) scalar \(Hex.encode(c.2))"505            let baseMul = EdPoint.multiplyBase(scalar: c.2)506            tally.check(ans["base_mul"] as? String == Hex.encode(baseMul.encode()) && baseMul.isValid, "multiplyBase: \(detail)")507            if let sodium = ans["sodium_base_mul"] as? String, !sodium.isEmpty, c.2[31] & 0x80 == 0 {508                // libsodium's noclamp multiplication takes the scalar as given, except bit 255 which it clears509                tally.check(sodium == Hex.encode(baseMul.encode()), "multiplyBase vs libsodium: \(detail)")510            }511            let strict = EdPoint.decode(c.0, strict: true), lenient = EdPoint.decode(c.0, strict: false)512            tally.check(ans["p_strict"] as? Bool == (strict != nil), "strict decoding: \(detail)")513            tally.check(ans["p_lenient"] as? Bool == (lenient != nil), "lenient decoding: \(detail)")514            tally.check(ans["solders_on_curve"] as? Bool == Ed25519.isOnCurve(c.0), "isOnCurve vs solders: \(detail)")515            tally.check(Ed25519.isCanonicalPoint(c.0) == (strict != nil), "isCanonicalPoint: \(detail)")516            guard let p = lenient else { continue }517            decoded += 1518            tally.check(p.isValid && ans["p_encoded"] as? String == Hex.encode(p.encode()), "encode: \(detail)")519            tally.check(ans["p_small_order"] as? Bool == p.isSmallOrder, "isSmallOrder: \(detail)")520            let product = EdPoint.multiply(scalar: c.2, p)521            tally.check(ans["mul"] as? String == Hex.encode(product.encode()) && product.isValid, "multiply: \(detail)")522            tally.check(ans["double"] as? String == Hex.encode(EdPoint.double(p).encode()), "double: \(detail)")523            tally.check(ans["neg"] as? String == Hex.encode(EdPoint.negate(p).encode()), "negate: \(detail)")524            if let q = EdPoint.decode(c.1, strict: false) {525                let sum = EdPoint.add(p, q)526                tally.check(ans["add"] as? String == Hex.encode(sum.encode()) && sum.isValid, "add: \(detail)")527            }528        }529        #expect(decoded > n / 2)530        #expect(tally.finish() == 0)531    }532533    // MARK: SLIP-0010534535    @Test func slip0010AgainstReferences() throws {536        let name = "slip10-ed25519"537        guard MCOracle.available(Self.script, campaign: name, needs: ["bip-utils"]) else { return }538        let seed = DiffSeed.make(name)539        var rng = AuditRNG(seed: seed)540        var tally = DiffTally(541            name, algorithm: "SLIP-0010", parameterSet: "ed25519",542            oracle: MCOracle.label(Self.script, "bip-utils") + "; HMAC-SHA512 transcription of SLIP-0010 (Python hashlib)", seed: seed)543        let n = AuditMode.cases(quick: 300, full: 4000)544        var cases = [(Bytes, [UInt32])]()545        for _ in 0..<n {546            let s = rng.bytes(rng.pick([16, 32, 64, 64, 64, rng.int(16...64)]))547            let path = (0..<rng.int(0...6)).map { _ in rng.pick([UInt32(0), 1, 44, 501, 0x7fff_ffff, UInt32(truncatingIfNeeded: rng.next()) & 0x7fff_ffff]) }548            cases.append((s, path))549        }550        let answers = try MCOracle.batch(Self.script, "slip10", cases.map { ["seed": Hex.encode($0.0), "path": $0.1.map { Int($0) }] })551        for (i, c) in cases.enumerated() {552            let ans = answers[i]553            let detail = "seed \(Hex.encode(c.0)) path \(c.1)"554            guard let node = try? Ed25519.SLIP10.derive(seed: c.0, path: c.1) else {555                tally.check(false, "derivation failed: \(detail)")556                continue557            }558            let pk = try node.publicKey()559            tally.check(ans["hmac_private"] as? String == Hex.encode(node.privateKey), "private key vs HMAC transcription: \(detail)")560            tally.check(ans["hmac_chain_code"] as? String == Hex.encode(node.chainCode), "chain code vs HMAC transcription: \(detail)")561            tally.check(ans["hmac_public"] as? String == Hex.encode(pk), "public key vs integer reference: \(detail)")562            tally.check(ans["biputils_private"] as? String == Hex.encode(node.privateKey), "private key vs bip-utils (\(ans["biputils_error"] ?? "")): \(detail)")563            tally.check(ans["biputils_chain_code"] as? String == Hex.encode(node.chainCode), "chain code vs bip-utils: \(detail)")564            tally.check(ans["biputils_public"] as? String == Hex.encode(pk), "public key vs bip-utils: \(detail)")565        }566        // refusals: seed length outside 16…64, index with the hardened bit567        for length in [0, 1, 15, 65, 128] {568            tally.check((try? Ed25519.SLIP10.master(seed: Bytes(repeating: 7, count: length))) == nil, "seed of \(length) bytes accepted")569        }570        let master = try Ed25519.SLIP10.master(seed: Bytes(repeating: 7, count: 32))571        for index in [UInt32(0x8000_0000), 0x8000_0001, UInt32.max] {572            tally.check((try? master.deriveHardened(index)) == nil, "index \(index) accepted")573        }574        #expect(tally.finish() == 0)575    }576}577
Files main
Menu

Theme