Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Tests/PropertyAuditTests/Secp256k1Properties.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 QyvoraMath44import Testing4546@testable import QyvoraSecp256k147@testable import QyvoraSymmetric4849/// Counter of one property campaign: every `check` is one executed case.50struct Prop {51 let name: String, algorithm: String, parameterSet: String, seed: UInt64?52 var cases = 0, failed = 053 var failures: [String] = []5455 init(_ name: String, algorithm: String, parameterSet: String = "", seed: UInt64? = nil) {56 self.name = name57 self.algorithm = algorithm58 self.parameterSet = parameterSet59 self.seed = seed60 }6162 mutating func check(_ ok: Bool, _ what: @autoclosure () -> String = "") {63 cases += 164 if !ok {65 failed += 166 if failures.count < 10 { failures.append(what()) }67 }68 }6970 func finish(oracle: String = "", note: String = "") {71 AuditRecorder.record(72 area: "property", name: name, algorithm: algorithm, parameterSet: parameterSet, oracle: oracle,73 cases: cases, failed: failed, seed: seed, note: note)74 #expect(failed == 0, "\(algorithm) \(name) (seed \(seed.map(String.init) ?? "-")): \(failures.joined(separator: " | "))")75 #expect(cases > 0)76 }77}7879/// Big-integer oracle: Python integers evaluate `expr` for each case (variables a, b, c, m), answers as 64-digit hex.80enum BigIntOracle {81 static func eval(_ expr: String, modulus: U256, cases: [[U256]]) -> [U256]? {82 let script = """83 import sys, json84 m = int(sys.argv[2], 16)85 out = []86 for case in json.load(sys.stdin):87 v = [int(x, 16) for x in case] + [0, 0, 0]88 a, b, c = v[0], v[1], v[2]89 out.append('%064x' % (eval(sys.argv[1]) % (1 << 256)))90 print(json.dumps(out))91 """92 guard let input = try? JSONSerialization.data(withJSONObject: cases.map { $0.map { Hex.encode($0.bytes) } }),93 let out = try? Oracle.run(94 URL(fileURLWithPath: "/usr/bin/env"), ["python3", "-I", "-c", script, expr, Hex.encode(modulus.bytes)], input: input),95 let list = try? JSONSerialization.jsonObject(with: out) as? [String], list.count == cases.count96 else { return nil }97 return list.compactMap { Hex.decode($0).flatMap { U256(bigEndian: $0) } }98 }99}100101@Suite struct Secp256k1FieldAndScalarLaws {102 static func edges(_ m: U256) -> [U256] {103 let one = U256.one104 let mMinus1 = U256.sub(m, one).0105 let mMinus2 = U256.sub(mMinus1, one).0106 return [107 .zero, one, U256(2, 0, 0, 0), U256(UInt64.max, 0, 0, 0), U256(0, 1, 0, 0), U256(0, 0, 0, 1 << 63),108 U256(UInt64.max, UInt64.max, UInt64.max, UInt64.max >> 1), mMinus1, mMinus2,109 ]110 }111112 static func random(_ rng: inout AuditRNG, below m: Modulus) -> U256 {113 // uniform 256-bit value reduced once (m > 2^255, so one conditional subtraction is a full reduction)114 m.reduce(U256(bigEndian: rng.bytes(32))!)115 }116117 @Test(arguments: ["field p", "scalar n"]) func laws(_ which: String) {118 let m = which == "field p" ? Secp256k1.field : Secp256k1.order119 let seed = AuditSeed.make("secp256k1.laws." + which)120 var rng = AuditRNG(seed: seed)121 var prop = Prop("ring and field laws", algorithm: "secp256k1 arithmetic", parameterSet: which, seed: seed)122 var values = Self.edges(m.m)123 for _ in 0..<AuditMode.cases(quick: 400, full: 4000) { values.append(Self.random(&rng, below: m)) }124 for i in 0..<values.count {125 let a = values[i], b = values[(i * 7 + 3) % values.count], c = values[(i * 13 + 5) % values.count]126 prop.check(m.add(a, b) == m.add(b, a), "a+b=b+a")127 prop.check(m.mul(a, b) == m.mul(b, a), "ab=ba")128 prop.check(m.add(m.add(a, b), c) == m.add(a, m.add(b, c)), "(a+b)+c")129 prop.check(m.mul(m.mul(a, b), c) == m.mul(a, m.mul(b, c)), "(ab)c")130 prop.check(m.mul(a, m.add(b, c)) == m.add(m.mul(a, b), m.mul(a, c)), "a(b+c)")131 prop.check(m.add(a, m.neg(a)).isZero, "a+(-a)=0")132 prop.check(m.sub(a, b) == m.add(a, m.neg(b)), "a-b=a+(-b)")133 prop.check(m.add(a, .zero) == a && m.mul(a, .one) == a && m.mul(a, .zero).isZero, "identities")134 prop.check(m.fromMont(m.toMont(a)) == a, "Montgomery round trip")135 let inv = m.inverse(a)136 prop.check(a.isZero ? inv.isZero : m.mul(a, inv) == .one, "a·a⁻¹=1 (and inverse(0)=0)")137 for r in [m.add(a, b), m.sub(a, b), m.mul(a, b), inv] { prop.check(U256.lessThan(r, m.m), "result below the modulus") }138 }139 prop.finish()140 }141142 @Test(arguments: ["field p", "scalar n"]) func againstBigIntegers(_ which: String) {143 let m = which == "field p" ? Secp256k1.field : Secp256k1.order144 let seed = AuditSeed.make("secp256k1.bigint." + which)145 var rng = AuditRNG(seed: seed)146 var cases: [[U256]] = []147 let edges = Self.edges(m.m)148 for a in edges { for b in edges { cases.append([a, b]) } }149 for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) { cases.append([Self.random(&rng, below: m), Self.random(&rng, below: m)]) }150 let operations: [(String, String, (U256, U256) -> U256)] = [151 ("add", "(a + b) % m", { m.add($0, $1) }),152 ("sub", "(a - b) % m", { m.sub($0, $1) }),153 ("mul", "(a * b) % m", { m.mul($0, $1) }),154 ("inverse", "pow(a, m - 2, m)", { a, _ in m.inverse(a) }),155 ]156 for (name, expr, f) in operations {157 var prop = Prop("\(name) against Python integers", algorithm: "secp256k1 arithmetic", parameterSet: which, seed: seed)158 guard let expected = BigIntOracle.eval(expr, modulus: m.m, cases: cases) else {159 AuditRecorder.notRun(area: "property", name: "secp256k1 \(which) \(name) against Python integers", reason: "python3 unavailable")160 continue161 }162 for (c, e) in zip(cases, expected) { prop.check(f(c[0], c[1]) == e, "\(name)(\(Hex.encode(c[0].bytes)), \(Hex.encode(c[1].bytes)))") }163 prop.finish(oracle: "Python int")164 }165 }166167 /// The API refuses out-of-range scalars and coordinates.168 @Test func rangeChecksAtTheInterface() throws {169 var prop = Prop("out-of-range scalars and coordinates refused", algorithm: "secp256k1 arithmetic")170 let n = Secp256k1.n, p = Secp256k1.p171 let one = Bytes(repeating: 0, count: 31) + [1]172 let nMinus1 = U256.sub(n, .one).0.bytes173 let nPlus1 = U256.add(n, .one).0.bytes174 let ff = Bytes(repeating: 0xff, count: 32)175 let zero = Bytes(repeating: 0, count: 32)176 prop.check(Secp256k1.isValidPrivateKey(one) && Secp256k1.isValidPrivateKey(nMinus1), "1 and n−1 are valid keys")177 for bad in [zero, n.bytes, nPlus1, ff, Bytes(repeating: 1, count: 31), Bytes(repeating: 1, count: 33), []] {178 prop.check(!Secp256k1.isValidPrivateKey(bad), "invalid private key accepted")179 prop.check((try? Secp256k1.publicKey(privateKey: bad)) == nil, "publicKey of an invalid key")180 prop.check((try? Secp256k1.sign(digest: zero, privateKey: bad)) == nil, "sign with an invalid key")181 prop.check((try? Secp256k1.schnorrSign(message: [], privateKey: bad, auxRand: zero)) == nil, "schnorrSign with an invalid key")182 }183 // tweaks ≥ n, and tweak = n − key (sum zero)184 for badTweak in [n.bytes, nPlus1, ff] {185 prop.check((try? Secp256k1.privateKeyAdd(one, tweak: badTweak)) == nil, "tweak ≥ n accepted")186 prop.check((try? Secp256k1.publicKeyAdd(try Secp256k1.publicKey(privateKey: one), tweak: badTweak)) == nil, "public tweak ≥ n accepted")187 }188 prop.check((try? Secp256k1.privateKeyAdd(one, tweak: nMinus1)) == nil, "key + tweak = 0 accepted")189 prop.check((try? Secp256k1.publicKeyAdd(try Secp256k1.publicKey(privateKey: one), tweak: nMinus1)) == nil, "P + tweak·G = identity accepted")190 // x ≥ p, points off the curve, wrong prefixes and lengths191 let g = try Secp256k1.publicKey(privateKey: one, compressed: false)192 var offCurve = g193 offCurve[64] ^= 1194 let pPlus = U256.add(p, U256(5, 0, 0, 0)).0.bytes195 for bad in [[0x02] + p.bytes, [0x02] + pPlus, [0x03] + ff, [0x04] + p.bytes + Bytes(g[33...]), offCurve, [0x05] + Bytes(g[1...33]), [0x00], [], Bytes(g.dropLast()), [0x04] + zero + zero] {196 prop.check(!Secp256k1.isValidPublicKey(bad), "invalid public key accepted: \(Hex.encode(bad.prefix(8)))")197 }198 // x = 5 has no square root of x³+7 on this curve? Checked instead: every accepted compressed key round-trips.199 let pk = try Secp256k1.publicKey(privateKey: one)200 prop.check(try Secp256k1.convert(publicKey: try Secp256k1.convert(publicKey: pk, compressed: false), compressed: true) == pk, "round trip")201 // signature components 0 and ≥ n202 let digest = SHA256.hash([1, 2, 3])203 let sig = try Secp256k1.sign(digest: digest, privateKey: one)204 for (r, s) in [(zero, sig.s), (sig.r, zero), (n.bytes, sig.s), (sig.r, n.bytes), (ff, sig.s), (sig.r, ff)] {205 prop.check(!Secp256k1.verify(compactSignature: r + s, digest: digest, publicKey: pk, requireLowS: false), "r or s out of range accepted")206 for id: UInt8 in 0..<4 {207 prop.check((try? Secp256k1.recoverPublicKey(compactSignature: r + s, recoveryID: id, digest: digest)) == nil, "recover with r or s out of range")208 }209 }210 prop.check((try? Secp256k1.recoverPublicKey(compactSignature: sig.compact, recoveryID: 4, digest: digest)) == nil, "recovery id 4 accepted")211 prop.finish()212 }213}214215@Suite struct Secp256k1GroupLaw {216 typealias Point = Secp256k1.Point217218 static func same(_ a: Point, _ b: Point) -> Bool {219 Secp256k1.serialize(a, compressed: false) == Secp256k1.serialize(b, compressed: false)220 }221222 static func onCurve(_ p: Point) -> Bool {223 guard let a = p.affine() else { return true } // identity224 return Point.fromAffine(x: a.x, y: a.y) != nil225 }226227 @Test func groupLaws() {228 let seed = AuditSeed.make("secp256k1.group")229 var rng = AuditRNG(seed: seed)230 var prop = Prop("group laws", algorithm: "secp256k1 group", seed: seed)231 let g = Secp256k1.generator, n = Secp256k1.n, order = Secp256k1.order232 // fixed identities233 prop.check(Point.multiply(n, g).isIdentity, "n·G = O")234 prop.check(Self.same(Point.multiply(U256.sub(n, .one).0, g), g.negated()), "(n−1)·G = −G")235 prop.check(Point.multiply(.zero, g).isIdentity, "0·G = O")236 prop.check(Self.same(Point.multiply(.one, g), g), "1·G = G")237 prop.check(Self.same(Point.add(g, g), Point.double(g)), "G+G = 2G")238 prop.check(Self.same(Point.add(g, .identity), g) && Self.same(Point.add(.identity, g), g), "G+O = G")239 prop.check(Point.add(.identity, .identity).isIdentity && Point.double(.identity).isIdentity, "O+O = O")240 prop.check(Point.add(g, g.negated()).isIdentity, "G+(−G) = O")241 for _ in 0..<AuditMode.cases(quick: 40, full: 400) {242 let a = order.reduce(U256(bigEndian: rng.bytes(32))!), b = order.reduce(U256(bigEndian: rng.bytes(32))!)243 let c = order.reduce(U256(bigEndian: rng.bytes(32))!)244 let pa = Point.multiply(a, g), pb = Point.multiply(b, g), pc = Point.multiply(c, g)245 prop.check(Self.onCurve(pa) && Self.onCurve(Point.add(pa, pb)) && Self.onCurve(Point.double(pa)), "closure")246 prop.check(Self.same(Point.add(pa, pb), Point.add(pb, pa)), "P+Q = Q+P")247 prop.check(Self.same(Point.add(Point.add(pa, pb), pc), Point.add(pa, Point.add(pb, pc))), "(P+Q)+R = P+(Q+R)")248 prop.check(Self.same(Point.add(pa, pa), Point.double(pa)), "P+P = 2P (complete formulas)")249 prop.check(Point.add(pa, pa.negated()).isIdentity, "P+(−P) = O")250 prop.check(Self.same(Point.multiply(order.add(a, b), g), Point.add(pa, pb)), "(a+b)G = aG+bG")251 prop.check(Self.same(Point.multiply(a, pb), Point.multiply(order.mul(a, b), g)), "a(bG) = (ab)G")252 prop.check(Point.multiply(n, pa).isIdentity, "n·P = O")253 }254 prop.finish()255 }256}257258@Suite struct Secp256k1Signatures {259 @Test func ecdsaInvariants() throws {260 let seed = AuditSeed.make("secp256k1.ecdsa")261 var rng = AuditRNG(seed: seed)262 var prop = Prop("ECDSA sign/verify/recover invariants, malleability, cross-key rejection", algorithm: "ECDSA secp256k1", seed: seed)263 let n = Secp256k1.n264 for _ in 0..<AuditMode.cases(quick: 150, full: 2000) {265 let key = Secp256k1.order.reduce(U256(bigEndian: rng.bytes(32))!).bytes266 let other = Secp256k1.order.reduce(U256(bigEndian: rng.bytes(32))!).bytes267 guard Secp256k1.isValidPrivateKey(key), Secp256k1.isValidPrivateKey(other), key != other else { continue }268 let digest = rng.bytes(32)269 let pk = try Secp256k1.publicKey(privateKey: key), otherPk = try Secp256k1.publicKey(privateKey: other)270 let sig = try Secp256k1.sign(digest: digest, privateKey: key)271 prop.check(Secp256k1.verify(compactSignature: sig.compact, digest: digest, publicKey: pk), "own signature verifies")272 prop.check(try Secp256k1.sign(digest: digest, privateKey: key) == sig, "deterministic (RFC 6979)")273 prop.check(!U256.lessThan(Secp256k1.halfN, U256(bigEndian: sig.s)!), "s in the lower half")274 prop.check(try Secp256k1.recoverPublicKey(compactSignature: sig.compact, recoveryID: sig.recoveryID, digest: digest) == pk, "recovery")275 prop.check((try? Secp256k1.recoverPublicKey(compactSignature: sig.compact, recoveryID: sig.recoveryID ^ 1, digest: digest)) != pk, "other parity ≠ key")276 prop.check(try Secp256k1.parseDER(sig.der) == sig.compact, "DER round trip")277 // malleability: (r, n − s) is the same ECDSA signature; refused under the low-s rule278 let highS = sig.r + U256.sub(n, U256(bigEndian: sig.s)!).0.bytes279 prop.check(!Secp256k1.verify(compactSignature: highS, digest: digest, publicKey: pk, requireLowS: true), "high-s refused")280 prop.check(Secp256k1.verify(compactSignature: highS, digest: digest, publicKey: pk, requireLowS: false), "high-s valid without the rule")281 prop.check(!Secp256k1.verify(compactSignature: sig.compact, digest: digest, publicKey: otherPk, requireLowS: false), "cross-key")282 var d2 = digest283 d2[rng.int(0...31)] ^= UInt8(1 << rng.int(0...7))284 prop.check(!Secp256k1.verify(compactSignature: sig.compact, digest: d2, publicKey: pk, requireLowS: false), "modified digest")285 var s2 = sig.compact286 s2[rng.int(0...63)] ^= UInt8(1 << rng.int(0...7))287 prop.check(!Secp256k1.verify(compactSignature: s2, digest: digest, publicKey: pk, requireLowS: false), "modified signature")288 }289 prop.finish()290 }291292 @Test func schnorrInvariants() throws {293 let seed = AuditSeed.make("secp256k1.schnorr")294 var rng = AuditRNG(seed: seed)295 var prop = Prop("BIP-340 sign/verify invariants, bit flips, cross-key rejection", algorithm: "Schnorr BIP-340", seed: seed)296 for _ in 0..<AuditMode.cases(quick: 100, full: 1500) {297 let key = Secp256k1.order.reduce(U256(bigEndian: rng.bytes(32))!).bytes298 let other = Secp256k1.order.reduce(U256(bigEndian: rng.bytes(32))!).bytes299 guard Secp256k1.isValidPrivateKey(key), Secp256k1.isValidPrivateKey(other), key != other else { continue }300 let message = rng.bytes(rng.int(0...80)), aux = rng.bytes(32)301 let pk = try Secp256k1.xOnlyPublicKey(privateKey: key), otherPk = try Secp256k1.xOnlyPublicKey(privateKey: other)302 let sig = try Secp256k1.schnorrSign(message: message, privateKey: key, auxRand: aux)303 prop.check(Secp256k1.schnorrVerify(signature: sig, message: message, publicKey: pk), "own signature verifies")304 prop.check(!Secp256k1.schnorrVerify(signature: sig, message: message, publicKey: otherPk), "cross-key")305 prop.check(!Secp256k1.schnorrVerify(signature: sig, message: message + [0], publicKey: pk), "extended message")306 var s2 = sig307 s2[rng.int(0...63)] ^= UInt8(1 << rng.int(0...7))308 prop.check(!Secp256k1.schnorrVerify(signature: s2, message: message, publicKey: pk), "bit flip (BIP-340 signatures are non-malleable)")309 }310 prop.finish()311 }312}313