SPB Git

Repository Public

Targets+Ed25519.swift 12.0 KB 218 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Sources/FuzzTargets/Targets+Ed25519.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 QyvoraMath4445@testable import QyvoraEd255194647// Ed25519: verification, point decoding, signing, SLIP-0010 derivation and the arithmetic underneath.48// Verification handles attacker-chosen keys, signatures and messages (Solana transactions received from an49// endpoint, signed envelopes of the cold mode); the other targets pin the invariants of the code around it.5051func ed25519Seed(_ label: String, messageLength: Int) -> Bytes {52    let seed = fixtureBytes(label, 32)53    let message = fixtureBytes(label + "/m", messageLength)54    guard let pk = try? Ed25519.publicKey(seed: seed), let sig = try? Ed25519.sign(message: message, seed: seed) else { return [] }55    return pk + sig + message56}5758/// Encodings every Ed25519 harness should meet: ℓ, the small-order points and non-canonical encodings.59let ed25519Tokens: [Bytes] = {60    func le(_ low: UInt8, top: UInt8) -> Bytes { [low] + Bytes(repeating: 0xff, count: 30) + [top] }61    var out: [Bytes] = [62        Sc.order.bytes, Sc.subWide(Sc.order, .one).0.bytes, Bytes(repeating: 0, count: 32), [1] + Bytes(repeating: 0, count: 31),63        [1] + Bytes(repeating: 0, count: 30) + [0x80], le(0xec, top: 0x7f), le(0xec, top: 0xff), le(0xed, top: 0x7f), le(0xee, top: 0x7f),64        le(0xee, top: 0xff), le(0xff, top: 0x7f), le(0xff, top: 0xff), EdPoint.base.encode(),65    ]66    // the two encodings of order 8 with each sign (ed25519-speccheck)67    for h in ["26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05", "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a"] {68        if var b = Hex.decode(h) {69            out.append(b)70            b[31] |= 0x8071            out.append(b)72        }73    }74    return out75}()7677let ed25519Targets: [FuzzTarget] = [78    FuzzTarget(79        "ed25519-verify", "Ed25519 strict verification: public key(32) ‖ signature(64) ‖ message", maxLength: 400, acceptOnlySeeds: true,80        tokens: ed25519Tokens,81        seeds: { [ed25519Seed("ed1", messageLength: 0), ed25519Seed("ed2", messageLength: 32), ed25519Seed("ed3", messageLength: 200)] }82    ) { input in83        var f = FuzzInput(input)84        let publicKey = f.upTo(32), signature = f.upTo(64), message = f.rest()85        let ok = Ed25519.verify(signature: signature, message: message, publicKey: publicKey)86        guard ok else {87            FuzzOutcome.note(Ed25519.isValidPublicKey(publicKey) ? "key-ok" : "key-bad")88            return89        }90        // an accepted input satisfies every rule of the documented policy91        fuzzCheck(signature.count == 64 && publicKey.count == 32, "accepted with wrong lengths")92        fuzzCheck(Ed25519.isValidPublicKey(publicKey), "accepted under a public key that is not valid")93        fuzzCheck(Sc(littleEndian: Bytes(signature[32..<64])).isCanonical, "accepted with S at or above the order")94        fuzzCheck(Ed25519.isSmallOrder(Bytes(signature[0..<32])) == false, "accepted with a small-order or non-canonical R")95        FuzzOutcome.accept()96    },9798    FuzzTarget(99        "ed25519-point", "Edwards point decoding (strict RFC 8032 and lenient dalek rules), re-encoding, public predicates", maxLength: 40,100        tokens: ed25519Tokens,101        seeds: {102            var out = ed25519Tokens.filter { $0.count == 32 }103            for label in ["p1", "p2", "p3"] { out.append(EdPoint.multiplyBase(scalar: fixtureBytes(label, 32)).encode()) }104            out.append(fixtureBytes("not-a-point", 32))105            return out106        }107    ) { input in108        let strict = EdPoint.decode(input, strict: true), lenient = EdPoint.decode(input, strict: false)109        fuzzCheck(strict == nil || lenient != nil, "strict decoding accepts what lenient decoding refuses")110        fuzzCheck(Ed25519.isOnCurve(input) == (lenient != nil), "isOnCurve disagrees with lenient decoding")111        fuzzCheck(Ed25519.isCanonicalPoint(input) == (strict != nil), "isCanonicalPoint disagrees with strict decoding")112        fuzzCheck((Ed25519.isSmallOrder(input) == nil) == (strict == nil), "isSmallOrder is nil exactly for non-canonical input")113        if let p = strict {114            FuzzOutcome.note("strict")115            fuzzCheck(p.isValid, "decoded point is not on the curve")116            fuzzCheck(p.encode() == input, "strict decoding accepted a non-canonical encoding")117            fuzzCheck(Ed25519.isValidPublicKey(input) == !p.isSmallOrder, "isValidPublicKey")118            if p.isSmallOrder { FuzzOutcome.note("small") }119        } else if let p = lenient {120            FuzzOutcome.note("lenient")121            fuzzCheck(p.isValid, "leniently decoded point is not on the curve")122            let canonical = p.encode()123            fuzzCheck(input.count == 32 && canonical != input, "lenient-only input re-encodes to itself")124            fuzzCheck(EdPoint.decode(canonical, strict: true).map { EdPoint.equal($0, p) } == true, "canonical re-encoding decodes to another point")125            fuzzCheck(!Ed25519.isValidPublicKey(input), "non-canonical encoding accepted as a public key")126        } else {127            FuzzOutcome.note("nil")128            fuzzCheck(!Ed25519.isValidPublicKey(input), "undecodable input accepted as a public key")129        }130    },131132    FuzzTarget(133        "ed25519-sign", "Ed25519 signing from an arbitrary seed and message: verifies, deterministic, canonical", maxLength: 300,134        seeds: { [fixtureBytes("sign1", 32), fixtureBytes("sign2", 32) + fixtureBytes("sign2/m", 100), Bytes(repeating: 0, count: 32), Bytes(repeating: 0xff, count: 33)] }135    ) { input in136        var f = FuzzInput(input)137        let seed = f.upTo(32), message = f.rest()138        guard let signature = attempt({ try Ed25519.sign(message: message, seed: seed) }) else {139            fuzzCheck(seed.count != 32, "a 32-byte seed was refused")140            fuzzCheck((try? Ed25519.publicKey(seed: seed)) == nil, "publicKey accepts a seed that sign refuses")141            return142        }143        guard let publicKey = try? Ed25519.publicKey(seed: seed) else { fuzzFail("no public key for a seed that signs") }144        fuzzCheck(signature.count == 64 && Ed25519.verify(signature: signature, message: message, publicKey: publicKey), "signature does not verify")145        fuzzCheck((try? Ed25519.sign(message: message, seed: seed)) == signature, "signing is not deterministic")146        fuzzCheck(Ed25519.isValidPublicKey(publicKey), "generated public key is not valid")147        var altered = signature148        altered[Int(input.count) % 64] ^= 0x01149        fuzzCheck(!Ed25519.verify(signature: altered, message: message, publicKey: publicKey), "altered signature verifies")150    },151152    FuzzTarget(153        "slip10-ed25519", "SLIP-0010 ed25519 derivation: seed length byte ‖ seed ‖ 4-byte indices", maxLength: 120,154        seeds: {155            [156                [16] + (0..<16).map { UInt8($0) }, [16] + (0..<16).map { UInt8($0) } + [0, 0, 0, 0, 0, 0, 0, 1],157                [64] + fixtureBytes("slip", 64) + [0, 0, 0, 44, 0, 0, 1, 245, 0, 0, 0, 0, 0, 0, 0, 0], [15] + fixtureBytes("short", 15),158                [32] + fixtureBytes("slip32", 32) + [0x80, 0, 0, 0],159            ]160        }161    ) { input in162        var f = FuzzInput(input)163        let seed = f.upTo(Int(f.byte()))164        var path = [UInt32]()165        while f.remaining >= 4, path.count < 10 {166            let b = f.take(4)167            path.append(UInt32(b[0]) << 24 | UInt32(b[1]) << 16 | UInt32(b[2]) << 8 | UInt32(b[3]))168        }169        guard let node = attempt({ try Ed25519.SLIP10.derive(seed: seed, path: path) }) else {170            fuzzCheck(!(16...64).contains(seed.count) || path.contains { $0 >= 0x8000_0000 }, "valid derivation refused")171            return172        }173        fuzzCheck((16...64).contains(seed.count) && path.allSatisfy { $0 < 0x8000_0000 }, "invalid derivation accepted")174        fuzzCheck(node.privateKey.count == 32 && node.chainCode.count == 32, "node sizes")175        // step by step176        guard var step = try? Ed25519.SLIP10.master(seed: seed) else { fuzzFail("master refused") }177        for index in path {178            guard let next = try? step.deriveHardened(index) else { fuzzFail("child refused") }179            step = next180        }181        fuzzCheck(step == node, "path derivation differs from step-by-step derivation")182        guard let publicKey = try? node.publicKey() else { fuzzFail("no public key") }183        fuzzCheck(Ed25519.isValidPublicKey(publicKey), "derived public key is not valid")184    },185186    FuzzTarget(187        "ed25519-arithmetic", "Field, scalar and group arithmetic identities on arbitrary bytes (a(32) ‖ b(32) ‖ wide(64))", maxLength: 128,188        tokens: ed25519Tokens,189        seeds: { [fixtureBytes("arith1", 128), Bytes(repeating: 0xff, count: 128), Bytes(repeating: 0, count: 128), ed25519Tokens[0] + ed25519Tokens[1] + ed25519Tokens[0] + ed25519Tokens[0]] }190    ) { input in191        var f = FuzzInput(input)192        let aBytes = f.take(32), bBytes = f.take(32), wide = f.take(64)193        // field194        let a = Fe.fromBytes(aBytes), b = Fe.fromBytes(bBytes)195        let product = Fe.mul(a, b)196        if a.isZeroMask == 0 {197            fuzzCheck(Fe.equalMask(Fe.mul(product, Fe.invert(a)), b) == UInt64.max, "(ab)a⁻¹ ≠ b")198        } else {199            FuzzOutcome.note("zero")200            fuzzCheck(product.isZeroMask == UInt64.max && Fe.invert(a).isZeroMask == UInt64.max, "0·b ≠ 0 or 0⁻¹ ≠ 0")201        }202        fuzzCheck(Fe.equalMask(Fe.sub(Fe.add(a, b), b), a) == UInt64.max, "(a + b) − b ≠ a")203        let canonical = a.toBytes()204        fuzzCheck(canonical[31] & 0x80 == 0 && Fe.fromBytes(canonical).toBytes() == canonical, "toBytes is not canonical")205        // scalars206        let sa = Sc(littleEndian: aBytes), sb = Sc(littleEndian: bBytes)207        let ra = Sc.reduce(sa), rw = Sc.reduceWide(wide)208        fuzzCheck(ra.isCanonical && rw.isCanonical && Sc.mulAdd(ra, sb, rw).isCanonical, "scalar result at or above the order")209        fuzzCheck(sa.isCanonical ? ra.bytes == aBytes : ra.bytes != aBytes, "reduce and isCanonical disagree")210        // group: [a]B + [b]B = [a + b]B with a, b reduced; the fixed-base and variable-base paths agree211        let rb = Sc.reduce(sb)212        let left = EdPoint.add(EdPoint.multiplyBase(scalar: ra.bytes), EdPoint.multiplyBase(scalar: rb.bytes))213        let right = EdPoint.multiplyBase(scalar: Sc.addMod(ra, rb).bytes)214        fuzzCheck(EdPoint.equal(left, right) && left.isValid, "[a]B + [b]B ≠ [a + b]B")215        fuzzCheck(EdPoint.equal(EdPoint.multiply(scalar: aBytes, EdPoint.base), EdPoint.multiplyBase(scalar: aBytes)), "variable-base ≠ fixed-base")216    },217]218
Files main
Menu

Theme