SPB Git

Repository Public

Secp256k1DiffTests.swift 27.6 KB 476 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/DifferentialAuditTests/Secp256k1DiffTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import AuditSupport42import Foundation43import QyvoraCore44import QyvoraMath45import QyvoraSecp256k146import Testing4748// secp256k1 against libsecp256k1 (through the Python package coincurve), the BIP-340 reference49// implementation and a textbook integer implementation written in the oracle; BIP-32 against embit50// and a second derivation written in the oracle; BIP-39 against the Trezor `mnemonic` package.5152private let orderHex = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"53private let fieldHex = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"5455private func be(_ hexString: String) -> Bytes { Hex.decode(hexString)! }5657/// n + delta as 32 big-endian bytes (delta small, may be negative).58private func orderPlus(_ delta: Int) -> Bytes { offset(be(orderHex), delta) }59private func fieldPlus(_ delta: Int) -> Bytes { offset(be(fieldHex), delta) }6061private func offset(_ value: Bytes, _ delta: Int) -> Bytes {62    var b = value63    var carry = delta64    var i = 3165    while carry != 0, i >= 0 {66        let v = Int(b[i]) + carry67        b[i] = UInt8(truncatingIfNeeded: v & 0xff)68        carry = v >> 869        i -= 170    }71    return b72}7374private func scalar(_ v: UInt8) -> Bytes { Bytes(repeating: 0, count: 31) + [v] }7576private let validKeyEdges: [Bytes] = [scalar(1), scalar(2), scalar(3), orderPlus(-1), orderPlus(-2), be("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0")]77private let invalidKeys: [Bytes] = [scalar(0), orderPlus(0), orderPlus(1), Bytes(repeating: 0xff, count: 32)]78private let digestEdges: [Bytes] = [scalar(0), scalar(1), orderPlus(-1), Bytes(repeating: 0x80, count: 1) + Bytes(repeating: 0, count: 31)]79/// Digests ≥ n: reduced modulo n by RFC 6979 (bits2octets); both implementations must still give identical signatures.80private let digestsAboveOrder: [Bytes] = [orderPlus(0), orderPlus(1), orderPlus(7), Bytes(repeating: 0xff, count: 32)]8182@Suite struct Secp256k1Differential {83    private let libsecp = Oracle.label("coincurve", "libsecp256k1")8485    @Test func publicKeyDerivation() throws {86        let name = "libsecp256k1-public-key"87        guard Py.available(name, needs: ["coincurve"]) else { return }88        let seed = DiffSeed.make(name)89        var rng = AuditRNG(seed: seed)90        var tally = DiffTally(name, algorithm: "secp256k1", parameterSet: "public key from private key (compressed, uncompressed, x-only)", oracle: libsecp, seed: seed)91        var keys = [Bytes]()92        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) { keys.append(rng.bytes(32, orEdge: validKeyEdges + invalidKeys, oneIn: 12)) }93        let answers = try Py.batch("secp_pub", keys.map { ["sk": hex($0)] })94        for (k, a) in zip(keys, answers) {95            let c = try? Secp256k1.publicKey(privateKey: k, compressed: true)96            let u = try? Secp256k1.publicKey(privateKey: k, compressed: false)97            let x = try? Secp256k1.xOnlyPublicKey(privateKey: k)98            let ok: Bool99            if a.oracleError != nil {100                ok = c == nil && u == nil && x == nil && !Secp256k1.isValidPrivateKey(k)101            } else {102                ok = c == a.bytes("pub33") && u == a.bytes("pub65") && x == a.bytes("xonly") && Secp256k1.isValidPrivateKey(k)103            }104            tally.check(ok, "private_key=\(hex(k))")105        }106        #expect(tally.finish() == 0)107    }108109    /// Deterministic ECDSA (RFC 6979, low s): byte-identical signatures and recovery identifiers.110    @Test func ecdsaSigning() throws {111        let name = "libsecp256k1-ecdsa-sign"112        guard Py.available(name, needs: ["coincurve"]) else { return }113        let seed = DiffSeed.make(name)114        var rng = AuditRNG(seed: seed)115        var tally = DiffTally(name, algorithm: "ECDSA secp256k1", parameterSet: "RFC 6979 signing, low s, recovery id", oracle: libsecp, seed: seed)116        var inputs = [(sk: Bytes, digest: Bytes)]()117        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {118            inputs.append((rng.bytes(32, orEdge: validKeyEdges, oneIn: 12), rng.bytes(32, orEdge: digestEdges + digestsAboveOrder, oneIn: 8)))119        }120        let answers = try Py.batch("ecdsa_sign", inputs.map { ["sk": hex($0.sk), "digest": hex($0.digest)] })121        for (i, a) in zip(inputs, answers) {122            let s = try? Secp256k1.sign(digest: i.digest, privateKey: i.sk)123            let ok = s != nil && s?.compact == a.bytes("compact") && Int(s?.recoveryID ?? 255) == a["recid"] as? Int124            tally.check(ok, "private_key=\(hex(i.sk)) digest=\(hex(i.digest)) ours=\(s.map { hex($0.compact) } ?? "nil") libsecp256k1=\(a.string("compact") ?? "nil")")125        }126        #expect(tally.finish() == 0)127    }128129    /// Verification verdicts on valid, mutated, high-s and out-of-range signatures and on malformed keys.130    @Test func ecdsaVerification() throws {131        let name = "libsecp256k1-ecdsa-verify"132        guard Py.available(name, needs: ["coincurve"]) else { return }133        let seed = DiffSeed.make(name)134        var rng = AuditRNG(seed: seed)135        var tally = DiffTally(name, algorithm: "ECDSA secp256k1", parameterSet: "verification verdicts (valid, mutated, high s, r/s out of range, bad keys)",136                              oracle: libsecp + " + integer ECDSA in the oracle", seed: seed)137        var cases = [(pub: Bytes, digest: Bytes, sig: Bytes, kind: Int)]()138        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {139            let sk = rng.bytes(32, orEdge: validKeyEdges, oneIn: 20)140            var digest = rng.bytes(32, orEdge: digestEdges + digestsAboveOrder, oneIn: 12)141            var pub = try Secp256k1.publicKey(privateKey: sk, compressed: rng.bool())142            var sig = try Secp256k1.sign(digest: digest, privateKey: sk).compact143            let kind = rng.int(0...9)144            switch kind {145            case 0: sig[rng.int(0...63)] ^= 1 << UInt8(rng.int(0...7))146            case 1: digest[rng.int(0...31)] ^= 1 << UInt8(rng.int(0...7))147            case 2: pub[rng.int(1...(pub.count - 1))] ^= 1 << UInt8(rng.int(0...7))  // usually not on the curve148            case 3:  // high s: n − s149                let s = Bytes(sig[32...])150                var out = Bytes(repeating: 0, count: 32), borrow = 0151                let n = be(orderHex)152                for i in (0..<32).reversed() {153                    var v = Int(n[i]) - Int(s[i]) - borrow154                    borrow = v < 0 ? 1 : 0155                    if v < 0 { v += 256 }156                    out[i] = UInt8(v)157                }158                sig = Bytes(sig[0..<32]) + out159            case 4: sig = rng.pick([scalar(0), orderPlus(0), orderPlus(1), Bytes(repeating: 0xff, count: 32)]) + Bytes(sig[32...])160            case 5: sig = Bytes(sig[0..<32]) + rng.pick([scalar(0), orderPlus(0), orderPlus(1), Bytes(repeating: 0xff, count: 32)])161            case 6: pub = try Secp256k1.publicKey(privateKey: rng.bytes(32, orEdge: validKeyEdges, oneIn: 4))  // another key162            default: break  // valid163            }164            cases.append((pub, digest, sig, kind))165        }166        // libsecp256k1 judges every case; the (slow) integer implementation re-checks one case in ten167        let answers = try Py.batch("ecdsa_verify", cases.enumerated().map { i, c in168            ["pub": hex(c.pub), "digest": hex(c.digest), "sig": hex(c.sig), "int": i % 10 == 0] as Case169        })170        for (c, a) in zip(cases, answers) {171            let any = Secp256k1.verify(compactSignature: c.sig, digest: c.digest, publicKey: c.pub, requireLowS: false)172            let strict = Secp256k1.verify(compactSignature: c.sig, digest: c.digest, publicKey: c.pub, requireLowS: true)173            tally.verdict(strict)174            let valid = a.bool("valid") == true, low = a.bool("low_s") == true175            // libsecp256k1 verifies low-s signatures only: its verdict must equal ours in strict mode176            var ok = any == valid && strict == (valid && low) && strict == (a.bool("libsecp_valid") == true)177            if let integer = a.bool("int_valid") { ok = ok && integer == valid }178            tally.check(ok, "kind=\(c.kind) pub=\(hex(c.pub)) digest=\(hex(c.digest)) sig=\(hex(c.sig)) ours(any s)=\(any) ours(low s)=\(strict) oracle=\(a)")179        }180        #expect(tally.finish() == 0)181    }182183    @Test func ecdsaRecovery() throws {184        let name = "libsecp256k1-ecdsa-recover"185        guard Py.available(name, needs: ["coincurve"]) else { return }186        let seed = DiffSeed.make(name)187        var rng = AuditRNG(seed: seed)188        var tally = DiffTally(name, algorithm: "ECDSA secp256k1", parameterSet: "public-key recovery (valid signatures, wrong ids, random r ‖ s)", oracle: libsecp, seed: seed)189        var cases = [(digest: Bytes, sig: Bytes, id: UInt8)]()190        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {191            let digest = rng.bytes(32, orEdge: digestEdges + digestsAboveOrder, oneIn: 12)192            switch rng.int(0...3) {193            case 0:  // random r ‖ s: r is an x coordinate about half of the time194                cases.append((digest, rng.bytes(64), UInt8(rng.int(0...3))))195            case 1:  // right signature, any id196                let s = try Secp256k1.sign(digest: digest, privateKey: rng.bytes(32, orEdge: validKeyEdges, oneIn: 12))197                cases.append((digest, s.compact, UInt8(rng.int(0...3))))198            default:199                let s = try Secp256k1.sign(digest: digest, privateKey: rng.bytes(32, orEdge: validKeyEdges, oneIn: 12))200                cases.append((digest, s.compact, s.recoveryID))201            }202        }203        let answers = try Py.batch("ecdsa_recover", cases.map { ["digest": hex($0.digest), "sig": hex($0.sig), "recid": Int($0.id)] })204        for (c, a) in zip(cases, answers) {205            let mine = try? Secp256k1.recoverPublicKey(compactSignature: c.sig, recoveryID: c.id, digest: c.digest, compressed: true)206            let mineU = try? Secp256k1.recoverPublicKey(compactSignature: c.sig, recoveryID: c.id, digest: c.digest, compressed: false)207            tally.verdict(mine != nil)208            tally.check(mine == a.bytes("pub33") && mineU == a.bytes("pub65"),209                "digest=\(hex(c.digest)) sig=\(hex(c.sig)) recid=\(c.id) ours=\(mine.map(hex) ?? "nil") libsecp256k1=\(a.string("pub33") ?? "nil")")210        }211        #expect(tally.finish() == 0)212    }213214    /// The tweak operations of BIP-32: (key + tweak) mod n and P + tweak·G, with the refusal cases.215    @Test func tweaks() throws {216        let name = "libsecp256k1-tweak-add"217        guard Py.available(name, needs: ["coincurve"]) else { return }218        let seed = DiffSeed.make(name)219        var rng = AuditRNG(seed: seed)220        var tally = DiffTally(name, algorithm: "secp256k1", parameterSet: "private and public tweak addition", oracle: libsecp, seed: seed)221        var cases = [(sk: Bytes, pub: Bytes, tweak: Bytes)]()222        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {223            let sk = rng.bytes(32, orEdge: validKeyEdges, oneIn: 8)224            var tweak = rng.bytes(32, orEdge: validKeyEdges + invalidKeys, oneIn: 6)225            if rng.int(0...19) == 0 {  // tweak = n − sk: the sum is zero, both must refuse226                var out = Bytes(repeating: 0, count: 32), borrow = 0227                let n = be(orderHex)228                for i in (0..<32).reversed() {229                    var v = Int(n[i]) - Int(sk[i]) - borrow230                    borrow = v < 0 ? 1 : 0231                    if v < 0 { v += 256 }232                    out[i] = UInt8(v)233                }234                tweak = out235            }236            cases.append((sk, try Secp256k1.publicKey(privateKey: sk), tweak))237        }238        let answers = try Py.batch("secp_tweak", cases.map { ["sk": hex($0.sk), "pub": hex($0.pub), "tweak": hex($0.tweak)] })239        for (c, a) in zip(cases, answers) {240            let k = try? Secp256k1.privateKeyAdd(c.sk, tweak: c.tweak)241            let p = try? Secp256k1.publicKeyAdd(c.pub, tweak: c.tweak)242            tally.verdict(k != nil)243            tally.check(k == a.bytes("sk") && p == a.bytes("pub"),244                "private_key=\(hex(c.sk)) tweak=\(hex(c.tweak)) ours=(\(k.map(hex) ?? "nil"), \(p.map(hex) ?? "nil")) libsecp256k1=\(a)")245        }246        #expect(tally.finish() == 0)247    }248249    /// Public-key parsing: random and mutated encodings, x ≥ p, points off the curve, hybrid prefixes, wrong lengths.250    @Test func publicKeyParsing() throws {251        let name = "libsecp256k1-public-key-parse"252        guard Py.available(name, needs: ["coincurve"]) else { return }253        let seed = DiffSeed.make(name)254        var rng = AuditRNG(seed: seed)255        var tally = DiffTally(name, algorithm: "secp256k1", parameterSet: "SEC 1 public-key parsing and conversion",256                              oracle: libsecp + " + integer parser in the oracle", seed: seed)257        var keys = [Bytes]()258        for _ in 0..<AuditMode.cases(quick: 3000, full: 30000) {259            let good = try Secp256k1.publicKey(privateKey: rng.bytes(32, orEdge: validKeyEdges, oneIn: 8), compressed: rng.bool())260            var k = good261            switch rng.int(0...9) {262            case 0: k = [rng.pick([2, 3])] + rng.bytes(32)  // on the curve about half of the time263            case 1: k = [rng.pick([2, 3])] + rng.pick([fieldPlus(0), fieldPlus(1), fieldPlus(5), Bytes(repeating: 0xff, count: 32), scalar(0), fieldPlus(-1)])264            case 2: k = [4] + rng.bytes(64)265            case 3: k[rng.int(0...(k.count - 1))] ^= 1 << UInt8(rng.int(0...7))266            case 4: k[0] = rng.pick([0, 1, 5, 6, 7, 8, 0xff])267            case 5: k = Bytes(k.prefix(rng.int(0...(k.count - 1))))268            case 6: k += rng.bytes(rng.int(1...3))269            case 7 where k.count == 65: k[0] = k[64] & 1 == 0 ? 6 : 7  // well-formed hybrid encoding270            case 8 where k.count == 65:  // y replaced by p − y is still on the curve; y + p is not canonical271                k = [4] + Bytes(k[1..<33]) + fieldPlus(0)272            default: break273            }274            keys.append(k)275        }276        let answers = try Py.batch("secp_parse", keys.map { ["pub": hex($0)] })277        for (k, a) in zip(keys, answers) {278            let valid = Secp256k1.isValidPublicKey(k)279            tally.verdict(valid)280            var ok = valid == (a.bool("valid") == true)281            if valid {282                ok = ok && (try? Secp256k1.convert(publicKey: k, compressed: true)) == a.bytes("pub33")283                ok = ok && (try? Secp256k1.convert(publicKey: k, compressed: false)) == a.bytes("pub65")284            }285            // libsecp256k1 agrees with the strict parser except on hybrid encodings (0x06 / 0x07), which it accepts286            if a.bool("hybrid") != true { ok = ok && valid == (a.bool("libsecp_valid") == true) }287            tally.check(ok, "public_key=\(hex(k)) ours=\(valid) oracle=\(a)")288        }289        #expect(tally.finish() == 0)290    }291292    // MARK: BIP-340293294    @Test func schnorrSigning() throws {295        let name = "libsecp256k1-bip340-sign"296        guard Py.available(name, needs: ["coincurve"]) else { return }297        let seed = DiffSeed.make(name)298        var rng = AuditRNG(seed: seed)299        var tally = DiffTally(name, algorithm: "Schnorr BIP-340", parameterSet: "signing with auxiliary randomness, x-only keys (32-byte messages)", oracle: libsecp, seed: seed)300        var inputs = [(sk: Bytes, msg: Bytes, aux: Bytes)]()301        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {302            inputs.append((rng.bytes(32, orEdge: validKeyEdges, oneIn: 12), rng.bytes(32, orEdge: digestEdges + digestsAboveOrder, oneIn: 12),303                           rng.bytes(32, orEdge: [scalar(0), Bytes(repeating: 0xff, count: 32)], oneIn: 6)))304        }305        let answers = try Py.batch("schnorr", inputs.map { ["sk": hex($0.sk), "msg": hex($0.msg), "aux": hex($0.aux)] })306        for (i, a) in zip(inputs, answers) {307            let sig = try? Secp256k1.schnorrSign(message: i.msg, privateKey: i.sk, auxRand: i.aux)308            let x = try? Secp256k1.xOnlyPublicKey(privateKey: i.sk)309            let ok = sig != nil && sig == a.bytes("sig") && x == a.bytes("xonly")310                && Secp256k1.schnorrVerify(signature: sig ?? [], message: i.msg, publicKey: x ?? [])311            tally.check(ok, "private_key=\(hex(i.sk)) message=\(hex(i.msg)) aux=\(hex(i.aux))")312        }313        #expect(tally.finish() == 0)314    }315316    /// The BIP's own reference implementation (pure Python, slow): messages of any length.317    @Test func schnorrSigningReference() throws {318        let name = "bip340-reference-sign"319        guard Py.available(name, needs: ["coincurve"]) else { return }320        let seed = DiffSeed.make(name)321        var rng = AuditRNG(seed: seed)322        var tally = DiffTally(name, algorithm: "Schnorr BIP-340", parameterSet: "signing, messages of 0–200 bytes",323                              oracle: "BIP-340 reference.py (bitcoin/bips f98774a) and " + libsecp, seed: seed)324        var inputs = [(sk: Bytes, msg: Bytes, aux: Bytes)]()325        for _ in 0..<AuditMode.cases(quick: 60, full: 600) {326            inputs.append((rng.bytes(32, orEdge: validKeyEdges, oneIn: 8), rng.bytes(rng.pick([0, 1, 31, 32, 33, 64, 100, 200])), rng.bytes(32)))327        }328        // coincurve signs 32-byte messages only: the per-case operation asks the reference for the others329        let answers = try Py.batch("schnorr_ref", inputs.map { ["sk": hex($0.sk), "msg": hex($0.msg), "aux": hex($0.aux)] })330        for (i, a) in zip(inputs, answers) {331            let sig = try? Secp256k1.schnorrSign(message: i.msg, privateKey: i.sk, auxRand: i.aux)332            let x = try? Secp256k1.xOnlyPublicKey(privateKey: i.sk)333            tally.check(sig != nil && sig == a.bytes("ref_sig") && x == a.bytes("ref_xonly"),334                "private_key=\(hex(i.sk)) message=\(hex(i.msg)) aux=\(hex(i.aux))")335        }336        #expect(tally.finish() == 0)337    }338339    @Test func schnorrVerification() throws {340        let name = "libsecp256k1-bip340-verify"341        guard Py.available(name, needs: ["coincurve"]) else { return }342        let seed = DiffSeed.make(name)343        var rng = AuditRNG(seed: seed)344        var tally = DiffTally(name, algorithm: "Schnorr BIP-340", parameterSet: "verification verdicts (valid, mutated, r ≥ p, s ≥ n, keys off the curve)",345                              oracle: libsecp + " (+ reference.py on one case in 20)", seed: seed)346        var cases = [(pub: Bytes, msg: Bytes, sig: Bytes, ref: Bool)]()347        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {348            let sk = rng.bytes(32, orEdge: validKeyEdges, oneIn: 12)349            var msg = rng.bytes(32)350            var pub = try Secp256k1.xOnlyPublicKey(privateKey: sk)351            var sig = try Secp256k1.schnorrSign(message: msg, privateKey: sk, auxRand: rng.bytes(32))352            switch rng.int(0...9) {353            case 0: sig[rng.int(0...63)] ^= 1 << UInt8(rng.int(0...7))354            case 1: msg[rng.int(0...31)] ^= 1 << UInt8(rng.int(0...7))355            case 2: pub[rng.int(0...31)] ^= 1 << UInt8(rng.int(0...7))356            case 3: sig = rng.pick([fieldPlus(0), fieldPlus(1), Bytes(repeating: 0xff, count: 32), scalar(0)]) + Bytes(sig[32...])357            case 4: sig = Bytes(sig[0..<32]) + rng.pick([orderPlus(0), orderPlus(1), Bytes(repeating: 0xff, count: 32), scalar(0)])358            case 5: pub = rng.pick([fieldPlus(0), fieldPlus(1), scalar(0), Bytes(repeating: 0xff, count: 32), rng.bytes(32)])359            default: break360            }361            cases.append((pub, msg, sig, rng.int(0...39) == 0))362        }363        let answers = try Py.batch("schnorr_verify", cases.map { ["pub": hex($0.pub), "msg": hex($0.msg), "sig": hex($0.sig), "ref": $0.ref] })364        for (c, a) in zip(cases, answers) {365            let mine = Secp256k1.schnorrVerify(signature: c.sig, message: c.msg, publicKey: c.pub)366            tally.verdict(mine)367            var ok = mine == (a.bool("valid") == true)368            if let r = a.bool("ref_valid") { ok = ok && mine == r }369            tally.check(ok, "public_key=\(hex(c.pub)) message=\(hex(c.msg)) sig=\(hex(c.sig)) ours=\(mine) oracle=\(a)")370        }371        #expect(tally.finish() == 0)372    }373374    // MARK: BIP-32 and BIP-39375376    @Test func bip32Derivation() throws {377        let name = "bip32-derivation"378        guard Py.available(name, needs: ["coincurve", "embit", "pycryptodome"]) else { return }379        let seed = DiffSeed.make(name)380        var rng = AuditRNG(seed: seed)381        var tally = DiffTally(name, algorithm: "BIP-32", parameterSet: "private derivation, public derivation, xprv / xpub serialization",382                              oracle: Oracle.label("embit") + " and a second derivation on " + libsecp, seed: seed)383        var inputs = [(seed: Bytes, path: [UInt32])]()384        for _ in 0..<AuditMode.cases(quick: 800, full: 8000) {385            var path = [UInt32]()386            for _ in 0..<rng.int(0...6) {387                let i = rng.pick([0, 1, 2, 44, 84, 0x7fff_ffff, UInt32(truncatingIfNeeded: rng.next()) & 0x7fff_ffff])388                path.append(rng.bool() ? i | 0x8000_0000 : i)389            }390            inputs.append((rng.bytes(rng.pick([16, 32, 64])), path))391        }392        let answers = try Py.batch("bip32", inputs.map { ["seed": hex($0.seed), "path": $0.path.map { Int($0) }] })393        for (i, a) in zip(inputs, answers) {394            var ok = a.oracleError == nil395            do {396                let master = try ExtendedKey.master(seed: i.seed)397                let node = try master.derive(DerivationPath(i.path.map { ChildIndex(raw: $0) }))398                ok = ok && node.privateKey == a.bytes("priv") && node.publicKey == a.bytes("pub") && node.chainCode == a.bytes("chain")399                ok = try ok && node.serialized(.xprv) == a.string("xprv") && node.serialized(.xpub) == a.string("xpub")400                // public-only derivation over the trailing non-hardened steps401                let lastHardened = i.path.lastIndex { $0 & 0x8000_0000 != 0 }.map { $0 + 1 } ?? 0402                if lastHardened < i.path.count {403                    var pub = try master.derive(DerivationPath(i.path[0..<lastHardened].map { ChildIndex(raw: $0) })).neutered404                    for step in i.path[lastHardened...] { pub = try pub.derive(ChildIndex(raw: step)) }405                    ok = try ok && pub.privateKey == nil && pub.publicKey == a.bytes("public_only_pub") && pub.publicKey == node.publicKey406                        && pub.chainCode == node.chainCode && pub.serialized(.xpub) == a.string("xpub")407                }408                // round trip through the serialized forms409                let back = try ExtendedKey.parse(try node.serialized(.xprv))410                ok = ok && back.key.privateKey == node.privateKey && back.key.chainCode == node.chainCode && back.version == .xprv411            } catch {412                ok = false413            }414            tally.check(ok, "seed=\(hex(i.seed)) path=\(i.path) oracle=\(a.oracleError ?? "ok")")415        }416        #expect(tally.finish() == 0)417    }418419    @Test func bip39() throws {420        let name = "bip39-mnemonic-seed"421        guard Py.available(name, needs: ["mnemonic"]) else { return }422        let seed = DiffSeed.make(name)423        var rng = AuditRNG(seed: seed)424        var tally = DiffTally(name, algorithm: "BIP-39", parameterSet: "entropy → words → seed (PBKDF2-HMAC-SHA512, 2048), 12–24 words, Unicode passphrases",425                              oracle: Oracle.label("mnemonic", "Trezor reference"), seed: seed)426        let passphrases = ["", "TREZOR", "correct horse battery staple", "pässwörd", "パスワード", "fi Å ligature", "🔑 clé", "a\u{0301}"]427        var inputs = [(entropy: Bytes, passphrase: String)]()428        for _ in 0..<AuditMode.cases(quick: 300, full: 3000) {429            let e = rng.bytes(rng.pick([16, 20, 24, 28, 32]), orEdge: [Bytes(repeating: 0, count: 16), Bytes(repeating: 0xff, count: 32), Bytes(repeating: 0x80, count: 24)], oneIn: 20)430            inputs.append((e, rng.pick(passphrases)))431        }432        let answers = try Py.batch("bip39", inputs.map { ["entropy": hex($0.entropy), "passphrase": $0.passphrase] })433        for (i, a) in zip(inputs, answers) {434            var ok = false435            if let words = try? BIP39.mnemonic(entropy: i.entropy) {436                ok = words.joined(separator: " ") == a.string("mnemonic")437                    && (try? BIP39.seed(mnemonic: words, passphrase: i.passphrase)) == a.bytes("seed")438                    && (try? BIP39.entropy(mnemonic: words)) == i.entropy439            }440            tally.check(ok, "entropy=\(hex(i.entropy)) passphrase=\(i.passphrase)")441        }442        #expect(tally.finish() == 0)443    }444445    /// Sentences with a replaced, swapped, missing or added word: same validity verdict on both sides.446    @Test func bip39Validation() throws {447        let name = "bip39-validation"448        guard Py.available(name, needs: ["mnemonic"]) else { return }449        let seed = DiffSeed.make(name)450        var rng = AuditRNG(seed: seed)451        var tally = DiffTally(name, algorithm: "BIP-39", parameterSet: "checksum and word validation of altered sentences",452                              oracle: Oracle.label("mnemonic", "Trezor reference"), seed: seed)453        var sentences = [[String]]()454        for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {455            var words = try BIP39.mnemonic(entropy: rng.bytes(rng.pick([16, 20, 24, 28, 32])))456            switch rng.int(0...5) {457            case 0: words[rng.int(0...(words.count - 1))] = rng.pick(BIP39.wordList)  // valid one time in 16–256458            case 1: words.swapAt(rng.int(0...(words.count - 1)), rng.int(0...(words.count - 1)))459            case 2: words.removeLast()460            case 3: words.append(rng.pick(BIP39.wordList))461            case 4: words[rng.int(0...(words.count - 1))] = rng.pick(["abandonn", "zzz", "", "Abandon", "about1"])462            default: break463            }464            sentences.append(words)465        }466        let answers = try Py.batch("bip39", sentences.map { ["mnemonic": $0.joined(separator: " ")] })467        for (w, a) in zip(sentences, answers) {468            // an empty word disappears when the reference splits the sentence: skip that shape on both sides469            if w.contains("") { continue }470            tally.verdict(BIP39.isValid(w))471            tally.check(BIP39.isValid(w) == (a.bool("valid") == true), "sentence=\(w.joined(separator: " ")) ours=\(BIP39.isValid(w)) oracle=\(a)")472        }473        #expect(tally.finish() == 0)474    }475}476
Files main
Menu

Theme