Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraSecp256k1/Secp256k1.swift8// Module : Qyvora Secp256k19// 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 QyvoraMath42import QyvoraSymmetric4344/// The curve secp256k1 (SEC 2): y² = x³ + 7 over F_p, prime order n, cofactor 1.45public enum Secp256k1 {46 static let p = U256(hex: "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f")47 static let n = U256(hex: "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141")48 static let halfN = U256(hex: "7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0")49 static let gx = U256(hex: "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")50 static let gy = U256(hex: "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")5152 static let field = Modulus(p)53 static let order = Modulus(n)5455 /// 3·b = 21 in Montgomery form.56 static let b3 = field.toMont(U256(21, 0, 0, 0))57 static let b7 = field.toMont(U256(7, 0, 0, 0))58 /// (p + 1) / 4, the square-root exponent (p ≡ 3 mod 4).59 static let sqrtExponent = U256(hex: "3fffffffffffffffffffffffffffffffffffffffffffffffffffffffbfffff0c")6061 static let generator = Point(x: field.toMont(gx), y: field.toMont(gy), z: field.r1)6263 public enum Error: Swift.Error, Equatable {64 case invalidPrivateKey65 case invalidPublicKey66 case invalidSignature67 case invalidLength68 }6970 /// Point in homogeneous projective coordinates (X : Y : Z), Montgomery-form field elements.71 /// The identity is (0 : 1 : 0). The addition and doubling are the complete formulas of72 /// Renes, Costello and Batina (2016, algorithms 7 and 9, a = 0): no exceptional case, no branch.73 struct Point: Sendable {74 var x: U25675 var y: U25676 var z: U2567778 static let identity = Point(x: .zero, y: Secp256k1.field.r1, z: .zero)7980 var isIdentity: Bool { z.isZero }8182 static func add(_ p: Point, _ q: Point) -> Point {83 let f = Secp256k1.field84 let b3 = Secp256k1.b385 var t0 = f.montMul(p.x, q.x)86 var t1 = f.montMul(p.y, q.y)87 var t2 = f.montMul(p.z, q.z)88 var t3 = f.add(p.x, p.y)89 var t4 = f.add(q.x, q.y)90 t3 = f.montMul(t3, t4)91 t4 = f.add(t0, t1)92 t3 = f.sub(t3, t4)93 t4 = f.add(p.y, p.z)94 var x3 = f.add(q.y, q.z)95 t4 = f.montMul(t4, x3)96 x3 = f.add(t1, t2)97 t4 = f.sub(t4, x3)98 x3 = f.add(p.x, p.z)99 var y3 = f.add(q.x, q.z)100 x3 = f.montMul(x3, y3)101 y3 = f.add(t0, t2)102 y3 = f.sub(x3, y3)103 x3 = f.add(t0, t0)104 t0 = f.add(x3, t0)105 t2 = f.montMul(b3, t2)106 var z3 = f.add(t1, t2)107 t1 = f.sub(t1, t2)108 y3 = f.montMul(b3, y3)109 x3 = f.montMul(t4, y3)110 t2 = f.montMul(t3, t1)111 x3 = f.sub(t2, x3)112 y3 = f.montMul(y3, t0)113 t1 = f.montMul(t1, z3)114 y3 = f.add(t1, y3)115 t0 = f.montMul(t0, t3)116 z3 = f.montMul(z3, t4)117 z3 = f.add(z3, t0)118 return Point(x: x3, y: y3, z: z3)119 }120121 static func double(_ p: Point) -> Point {122 let f = Secp256k1.field123 var t0 = f.montMul(p.y, p.y)124 var z3 = f.add(t0, t0)125 z3 = f.add(z3, z3)126 z3 = f.add(z3, z3)127 var t1 = f.montMul(p.y, p.z)128 var t2 = f.montMul(p.z, p.z)129 t2 = f.montMul(Secp256k1.b3, t2)130 var x3 = f.montMul(t2, z3)131 var y3 = f.add(t0, t2)132 z3 = f.montMul(t1, z3)133 t1 = f.add(t2, t2)134 t2 = f.add(t1, t2)135 t0 = f.sub(t0, t2)136 y3 = f.montMul(t0, y3)137 y3 = f.add(x3, y3)138 t1 = f.montMul(p.x, p.y)139 x3 = f.montMul(t0, t1)140 x3 = f.add(x3, x3)141 return Point(x: x3, y: y3, z: z3)142 }143144 static func select(_ mask: UInt64, _ a: Point, _ b: Point) -> Point {145 Point(x: U256.select(mask, a.x, b.x), y: U256.select(mask, a.y, b.y), z: U256.select(mask, a.z, b.z))146 }147148 func negated() -> Point {149 Point(x: x, y: Secp256k1.field.neg(y), z: z)150 }151152 /// k·P by double-and-add-always with a branch-free selection: the sequence of field153 /// operations does not depend on the scalar.154 static func multiply(_ k: U256, _ p: Point) -> Point {155 var r = Point.identity156 for i in stride(from: 255, through: 0, by: -1) {157 r = double(r)158 let t = add(r, p)159 r = select(0 &- k.bit(i), t, r)160 }161 return r162 }163164 /// Affine coordinates in normal form; nil for the identity.165 func affine() -> (x: U256, y: U256)? {166 if isIdentity { return nil }167 let f = Secp256k1.field168 let e = U256.sub(Secp256k1.p, U256(2, 0, 0, 0)).0169 let zInv = f.montPow(z, e)170 return (f.fromMont(f.montMul(x, zInv)), f.fromMont(f.montMul(y, zInv)))171 }172173 /// Builds the point (x, y) after checking the curve equation. Coordinates in normal form, below p.174 static func fromAffine(x: U256, y: U256) -> Point? {175 let f = Secp256k1.field176 guard U256.lessThan(x, Secp256k1.p), U256.lessThan(y, Secp256k1.p) else { return nil }177 let xm = f.toMont(x), ym = f.toMont(y)178 let rhs = f.add(f.montMul(f.montMul(xm, xm), xm), Secp256k1.b7)179 guard f.montMul(ym, ym) == rhs else { return nil }180 return Point(x: xm, y: ym, z: f.r1)181 }182183 /// The point with abscissa x and the requested parity of y, if x is on the curve.184 static func lift(x: U256, oddY: Bool) -> Point? {185 let f = Secp256k1.field186 guard U256.lessThan(x, Secp256k1.p) else { return nil }187 let xm = f.toMont(x)188 let rhs = f.add(f.montMul(f.montMul(xm, xm), xm), Secp256k1.b7)189 let ym = f.montPow(rhs, Secp256k1.sqrtExponent)190 guard f.montMul(ym, ym) == rhs else { return nil }191 var y = f.fromMont(ym)192 if y.isOdd != oddY { y = U256.sub(Secp256k1.p, y).0 }193 return Point(x: xm, y: f.toMont(y), z: f.r1)194 }195 }196197 // MARK: - Keys198199 /// A private key is valid when 1 ≤ d < n.200 public static func isValidPrivateKey(_ key: Bytes) -> Bool {201 guard let d = U256(bigEndian: key) else { return false }202 return !d.isZero && U256.lessThan(d, n)203 }204205 static func scalar(_ key: Bytes) throws -> U256 {206 guard let d = U256(bigEndian: key), !d.isZero, U256.lessThan(d, n) else { throw Error.invalidPrivateKey }207 return d208 }209210 /// SEC 1 public key: 33 bytes compressed (02/03 ‖ X) or 65 bytes uncompressed (04 ‖ X ‖ Y).211 public static func publicKey(privateKey: Bytes, compressed: Bool = true) throws -> Bytes {212 let dit = DataIndependentTiming.enable()213 defer { DataIndependentTiming.restore(dit) }214 let d = try scalar(privateKey)215 return serialize(Point.multiply(d, generator), compressed: compressed)216 }217218 static func serialize(_ point: Point, compressed: Bool) -> Bytes {219 guard let a = point.affine() else { return [0] }220 if compressed { return [a.y.isOdd ? 0x03 : 0x02] + a.x.bytes }221 return [0x04] + a.x.bytes + a.y.bytes222 }223224 static func parse(publicKey: Bytes) throws -> Point {225 if publicKey.count == 33, publicKey[0] == 0x02 || publicKey[0] == 0x03 {226 guard let x = U256(bigEndian: Bytes(publicKey[1...])),227 let pt = Point.lift(x: x, oddY: publicKey[0] == 0x03) else { throw Error.invalidPublicKey }228 return pt229 }230 if publicKey.count == 65, publicKey[0] == 0x04 {231 guard let x = U256(bigEndian: Bytes(publicKey[1..<33])), let y = U256(bigEndian: Bytes(publicKey[33...])),232 let pt = Point.fromAffine(x: x, y: y) else { throw Error.invalidPublicKey }233 return pt234 }235 throw Error.invalidPublicKey236 }237238 /// Checks that the bytes encode a point of the curve (compressed or uncompressed SEC 1).239 public static func isValidPublicKey(_ publicKey: Bytes) -> Bool {240 (try? parse(publicKey: publicKey)) != nil241 }242243 /// Re-encodes a public key in the requested form.244 public static func convert(publicKey: Bytes, compressed: Bool) throws -> Bytes {245 serialize(try parse(publicKey: publicKey), compressed: compressed)246 }247248 /// (key + tweak) mod n, as used by BIP-32 private derivation. Fails when the tweak is ≥ n or the result is zero.249 public static func privateKeyAdd(_ key: Bytes, tweak: Bytes) throws -> Bytes {250 let dit = DataIndependentTiming.enable()251 defer { DataIndependentTiming.restore(dit) }252 let d = try scalar(key)253 guard let t = U256(bigEndian: tweak), U256.lessThan(t, n) else { throw Error.invalidPrivateKey }254 let r = order.add(d, t)255 guard !r.isZero else { throw Error.invalidPrivateKey }256 return r.bytes257 }258259 /// P + tweak·G, as used by BIP-32 public derivation. Returns a compressed key.260 public static func publicKeyAdd(_ publicKey: Bytes, tweak: Bytes) throws -> Bytes {261 let pt = try parse(publicKey: publicKey)262 guard let t = U256(bigEndian: tweak), U256.lessThan(t, n) else { throw Error.invalidPrivateKey }263 let r = Point.add(pt, Point.multiply(t, generator))264 guard !r.isIdentity else { throw Error.invalidPublicKey }265 return serialize(r, compressed: true)266 }267268 // MARK: - ECDSA269270 public struct ECDSASignature: Equatable, Sendable {271 /// r ‖ s, 64 bytes, big endian, with s in the lower half of the order.272 public let compact: Bytes273 /// Recovery identifier 0…3 (bit 0: parity of R.y, bit 1: R.x ≥ n).274 public let recoveryID: UInt8275276 public var r: Bytes { Bytes(compact[0..<32]) }277 public var s: Bytes { Bytes(compact[32..<64]) }278279 /// Strict DER encoding (BIP-66).280 public var der: Bytes {281 func integer(_ v: Bytes) -> Bytes {282 var b = Bytes(v.drop(while: { $0 == 0 }))283 if b.isEmpty { b = [0] }284 if b[0] & 0x80 != 0 { b.insert(0, at: 0) }285 return [0x02, UInt8(b.count)] + b286 }287 let body = integer(r) + integer(s)288 return [0x30, UInt8(body.count)] + body289 }290 }291292 /// Deterministic nonce of RFC 6979 (HMAC-SHA256), section 3.2. `digest` is the 32-byte message hash.293 static func rfc6979Nonce(key: Bytes, digest: Bytes, attempt: Int) -> U256 {294 let h1 = order.reduce(U256(bigEndian: digest)!).bytes295 var v = Bytes(repeating: 0x01, count: 32)296 var k = Bytes(repeating: 0x00, count: 32)297 // Every intermediate K and V, and every HMAC message holding the private key, is erased before298 // its buffer is released (a reassignment alone would free the old buffer with its content).299 func updateK(_ message: inout Bytes) {300 let next = HMAC<SHA256>.authenticate(key: k, message: message)301 SecureMemory.zero(&message)302 SecureMemory.zero(&k)303 k = next304 }305 func updateV() {306 let next = HMAC<SHA256>.authenticate(key: k, message: v)307 SecureMemory.zero(&v)308 v = next309 }310 func seeded(_ separator: UInt8) -> Bytes {311 var m = Bytes()312 m.reserveCapacity(97)313 m += v314 m.append(separator)315 m += key316 m += h1317 return m318 }319 var m0 = seeded(0x00)320 updateK(&m0)321 updateV()322 var m1 = seeded(0x01)323 updateK(&m1)324 updateV()325 var remaining = attempt326 while true {327 updateV()328 if let candidate = U256(bigEndian: v), !candidate.isZero, U256.lessThan(candidate, n) {329 if remaining == 0 {330 SecureMemory.zero(&k)331 SecureMemory.zero(&v)332 return candidate333 }334 remaining -= 1335 }336 var retry = v + [0x00]337 updateK(&retry)338 updateV()339 }340 }341342 /// ECDSA signature of a 32-byte digest with a deterministic nonce (RFC 6979) and low s (BIP-62 / EIP-2).343 public static func sign(digest: Bytes, privateKey: Bytes) throws -> ECDSASignature {344 let dit = DataIndependentTiming.enable()345 defer { DataIndependentTiming.restore(dit) }346 guard digest.count == 32 else { throw Error.invalidLength }347 let d = try scalar(privateKey)348 let z = order.reduce(U256(bigEndian: digest)!)349 var attempt = 0350 while true {351 let k = rfc6979Nonce(key: privateKey, digest: digest, attempt: attempt)352 attempt += 1353 guard let rPoint = Point.multiply(k, generator).affine() else { continue }354 let r = order.reduce(rPoint.x)355 if r.isZero { continue }356 let kInv = order.inverse(k)357 var s = order.mul(kInv, order.add(z, order.mul(r, d)))358 if s.isZero { continue }359 var recovery: UInt8 = rPoint.y.isOdd ? 1 : 0360 if !U256.lessThan(rPoint.x, n) { recovery |= 2 }361 if U256.lessThan(halfN, s) {362 s = order.neg(s)363 recovery ^= 1364 }365 let signature = ECDSASignature(compact: r.bytes + s.bytes, recoveryID: recovery)366 // Verify what leaves (QYV-CRY-004, QYV-APP-007): a faulty computation must not release a signature, which367 // could expose the key, nor an unusable one. The public key comes from an independent multiplication.368 guard verify(compactSignature: signature.compact, digest: digest, publicKey: serialize(Point.multiply(d, generator), compressed: true)) else {369 throw Error.invalidSignature370 }371 return signature372 }373 }374375 /// Verifies r ‖ s (64 bytes) on a 32-byte digest. High-s signatures are rejected when `requireLowS` is true.376 public static func verify(compactSignature: Bytes, digest: Bytes, publicKey: Bytes, requireLowS: Bool = true) -> Bool {377 guard compactSignature.count == 64, digest.count == 32,378 let r = U256(bigEndian: Bytes(compactSignature[0..<32])),379 let s = U256(bigEndian: Bytes(compactSignature[32..<64])),380 !r.isZero, !s.isZero, U256.lessThan(r, n), U256.lessThan(s, n),381 let q = try? parse(publicKey: publicKey) else { return false }382 if requireLowS && U256.lessThan(halfN, s) { return false }383 let z = order.reduce(U256(bigEndian: digest)!)384 let w = order.inverse(s)385 let u1 = order.mul(z, w)386 let u2 = order.mul(r, w)387 let pt = Point.add(Point.multiply(u1, generator), Point.multiply(u2, q))388 guard let a = pt.affine() else { return false }389 return order.reduce(a.x) == r390 }391392 /// Recovers the public key (compressed by default) that produced the signature on the digest.393 public static func recoverPublicKey(compactSignature: Bytes, recoveryID: UInt8, digest: Bytes, compressed: Bool = true) throws -> Bytes {394 guard compactSignature.count == 64, digest.count == 32, recoveryID < 4,395 let r = U256(bigEndian: Bytes(compactSignature[0..<32])),396 let s = U256(bigEndian: Bytes(compactSignature[32..<64])),397 !r.isZero, !s.isZero, U256.lessThan(r, n), U256.lessThan(s, n) else { throw Error.invalidSignature }398 var x = r399 if recoveryID & 2 != 0 {400 let (sum, carry) = U256.add(r, n)401 guard carry == 0, U256.lessThan(sum, p) else { throw Error.invalidSignature }402 x = sum403 }404 guard let rPoint = Point.lift(x: x, oddY: recoveryID & 1 == 1) else { throw Error.invalidSignature }405 let z = order.reduce(U256(bigEndian: digest)!)406 let rInv = order.inverse(r)407 let u1 = order.neg(order.mul(z, rInv))408 let u2 = order.mul(s, rInv)409 let q = Point.add(Point.multiply(u1, generator), Point.multiply(u2, rPoint))410 guard !q.isIdentity else { throw Error.invalidSignature }411 return serialize(q, compressed: compressed)412 }413414 /// Parses a strict DER signature (BIP-66) into r ‖ s.415 public static func parseDER(_ der: Bytes) throws -> Bytes {416 guard der.count >= 8, der.count <= 72, der[0] == 0x30, Int(der[1]) == der.count - 2 else { throw Error.invalidSignature }417 var i = 2418 func integer() throws -> Bytes {419 guard i + 2 <= der.count, der[i] == 0x02 else { throw Error.invalidSignature }420 let len = Int(der[i + 1])421 guard len >= 1, len <= 33, i + 2 + len <= der.count else { throw Error.invalidSignature }422 let v = Bytes(der[(i + 2)..<(i + 2 + len)])423 guard v[0] & 0x80 == 0 else { throw Error.invalidSignature }424 if v.count > 1, v[0] == 0, v[1] & 0x80 == 0 { throw Error.invalidSignature }425 i += 2 + len426 let stripped = Bytes(v.drop(while: { $0 == 0 }))427 guard stripped.count <= 32 else { throw Error.invalidSignature }428 return Bytes(repeating: 0, count: 32 - stripped.count) + stripped429 }430 let r = try integer()431 let s = try integer()432 guard i == der.count else { throw Error.invalidSignature }433 return r + s434 }435436 // MARK: - Schnorr (BIP-340)437438 static func taggedHash(_ tag: String, _ data: Bytes) -> Bytes {439 let t = SHA256.hash(Bytes(tag.utf8))440 return SHA256.hash(t + t + data)441 }442443 /// 32-byte x-only public key of BIP-340.444 public static func xOnlyPublicKey(privateKey: Bytes) throws -> Bytes {445 Bytes(try publicKey(privateKey: privateKey, compressed: true)[1...])446 }447448 /// BIP-340 signature (64 bytes) of a message of any length; `auxRand` is 32 bytes of fresh randomness (or zeros).449 public static func schnorrSign(message: Bytes, privateKey: Bytes, auxRand: Bytes) throws -> Bytes {450 let dit = DataIndependentTiming.enable()451 defer { DataIndependentTiming.restore(dit) }452 guard auxRand.count == 32 else { throw Error.invalidLength }453 let d0 = try scalar(privateKey)454 guard let pPoint = Point.multiply(d0, generator).affine() else { throw Error.invalidPrivateKey }455 let d = U256.select(0 &- (pPoint.y.a0 & 1), order.neg(d0), d0)456 let px = pPoint.x.bytes457 let mask = taggedHash("BIP0340/aux", auxRand)458 var t = d.bytes459 for i in 0..<32 { t[i] ^= mask[i] }460 let rand = taggedHash("BIP0340/nonce", t + px + message)461 SecureMemory.zero(&t)462 let k0 = order.reduce(U256(bigEndian: rand)!)463 guard !k0.isZero, let rPoint = Point.multiply(k0, generator).affine() else { throw Error.invalidPrivateKey }464 let k = U256.select(0 &- (rPoint.y.a0 & 1), order.neg(k0), k0)465 let rx = rPoint.x.bytes466 let e = order.reduce(U256(bigEndian: taggedHash("BIP0340/challenge", rx + px + message))!)467 let s = order.add(k, order.mul(e, d))468 let signature = rx + s.bytes469 guard schnorrVerify(signature: signature, message: message, publicKey: px) else { throw Error.invalidSignature }470 return signature471 }472473 /// BIP-340 verification with a 32-byte x-only public key.474 public static func schnorrVerify(signature: Bytes, message: Bytes, publicKey: Bytes) -> Bool {475 guard signature.count == 64, publicKey.count == 32,476 let px = U256(bigEndian: publicKey), let pPoint = Point.lift(x: px, oddY: false),477 let r = U256(bigEndian: Bytes(signature[0..<32])), U256.lessThan(r, p),478 let s = U256(bigEndian: Bytes(signature[32..<64])), U256.lessThan(s, n) else { return false }479 let e = order.reduce(U256(bigEndian: taggedHash("BIP0340/challenge", Bytes(signature[0..<32]) + publicKey + message))!)480 let pt = Point.add(Point.multiply(s, generator), Point.multiply(order.neg(e), pPoint))481 guard let a = pt.affine(), !a.y.isOdd else { return false }482 return a.x == r483 }484}485