SPB Git

Repository Public

Ed25519.swift 11.9 KB 250 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraEd25519/Ed25519.swift8// Module           : Qyvora Ed255199// 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 QyvoraMath42import QyvoraSymmetric4344/// Ed25519 (pure EdDSA over edwards25519, RFC 8032 §5.1), written from scratch.45///46/// Signing is deterministic (RFC 8032 §5.1.6): the same seed and message always give the same 64 bytes.47///48/// **Verification policy** (the one of Solana validators, ed25519-dalek `verify_strict`, made slightly stricter):49///50/// 1. the signature is 64 bytes R ‖ S and the public key 32 bytes;51/// 2. S must be canonical, S < ℓ (otherwise S + ℓ would be a second valid signature: malleability);52/// 3. the public key A must decode strictly (RFC 8032 §5.1.3: y < p, no "x = 0 with sign bit") and must not be one of53///    the eight small-order points (with such a key a signature can be valid for many messages);54/// 4. R must decode and must not be a small-order point;55/// 5. the **cofactorless** equation is checked: the encoding of [S]B − [k]A must equal the 32 bytes of R, with56///    k = SHA-512(R ‖ A ‖ message) mod ℓ. Comparing encodings rejects every non-canonical encoding of R.57///58/// Rules 2, 4 and 5 and the small-order part of rule 3 are exactly `verify_strict`. The canonical-encoding part of59/// rule 3 is stricter than dalek, which accepts the handful of public keys encoded with y ≥ p; no key produced by60/// RFC 8032 key generation has such an encoding, so every signature made by `sign` (and by any conforming signer) is61/// accepted both here and by Solana validators. The converse does not hold for those non-canonical keys: this62/// implementation rejects them where a validator would accept. The cofactored equation of RFC 8032 ([8][S]B = [8]R +63/// [8][k]A) is deliberately not used: a consensus system needs the single-signature and batch answers to agree, and64/// the wallet must reject what the network rejects.65///66/// Secret-dependent work (key expansion, nonce, scalar multiplication of the base point, S = r + k·a) runs under67/// `DataIndependentTiming` and uses branch-free field, scalar and group arithmetic with masked table lookups.68/// Verification and point decoding handle public data only and are variable time.69public enum Ed25519 {70    public enum Error: Swift.Error, Equatable {71        /// The seed (private key) is not 32 bytes.72        case invalidSeedLength73        /// The public key is not 32 bytes, not a canonical encoding of a curve point, or a small-order point.74        case invalidPublicKey75        /// The signature that was just produced did not verify (fault or memory corruption): nothing is returned.76        case signingFailed77        /// SLIP-0010 master seed outside 16…64 bytes.78        case invalidDerivationSeed79        /// SLIP-0010 child index at or above 2^31 (indices are given without the hardened bit).80        case invalidDerivationIndex81    }8283    public static let seedLength = 3284    public static let publicKeyLength = 3285    public static let signatureLength = 648687    /// A new 32-byte seed from the system generator. The seed is the private key of RFC 8032.88    public static func generateSeed() -> Bytes { SystemRandom.bytes(seedLength) }8990    /// SHA-512(seed) split into the clamped secret scalar (32 bytes, little endian) and the nonce prefix (32 bytes).91    static func expand(seed: Bytes) -> (scalar: Bytes, prefix: Bytes) {92        var h = SHA512.hash(seed)93        var scalar = Bytes(h[0..<32])94        let prefix = Bytes(h[32..<64])95        SecureMemory.zero(&h)96        scalar[0] &= 24897        scalar[31] &= 12798        scalar[31] |= 6499        return (scalar, prefix)100    }101102    /// The 32-byte public key of a 32-byte seed (RFC 8032 §5.1.5).103    public static func publicKey(seed: Bytes) throws -> Bytes {104        guard seed.count == seedLength else { throw Error.invalidSeedLength }105        let dit = DataIndependentTiming.enable()106        defer { DataIndependentTiming.restore(dit) }107        var (scalar, prefix) = expand(seed: seed)108        defer {109            SecureMemory.zero(&scalar)110            SecureMemory.zero(&prefix)111        }112        return EdPoint.multiplyBase(scalar: scalar).encode()113    }114115    /// The 64-byte signature R ‖ S of `message` (RFC 8032 §5.1.6). Deterministic.116    ///117    /// The public key is always recomputed from the seed (never taken from the caller: signing with a mismatched118    /// public key reveals the secret scalar), and the signature is verified before it is returned.119    public static func sign(message: Bytes, seed: Bytes) throws -> Bytes {120        guard seed.count == seedLength else { throw Error.invalidSeedLength }121        let dit = DataIndependentTiming.enable()122        defer { DataIndependentTiming.restore(dit) }123        var (scalar, prefix) = expand(seed: seed)124        defer {125            SecureMemory.zero(&scalar)126            SecureMemory.zero(&prefix)127        }128        let publicKey = EdPoint.multiplyBase(scalar: scalar).encode()129130        var nonceHash = SHA512()131        nonceHash.update(prefix)132        nonceHash.update(message)133        var nonceWide = nonceHash.finalize()134        let r = Sc.reduceWide(nonceWide)135        SecureMemory.zero(&nonceWide)136        var rBytes = r.bytes137        defer { SecureMemory.zero(&rBytes) }138        let encodedR = EdPoint.multiplyBase(scalar: rBytes).encode()139140        let k = challenge(encodedR: encodedR, publicKey: publicKey, message: message)141        let s = Sc.mulAdd(k, Sc(littleEndian: scalar), r)142        let signature = encodedR + s.bytes143        guard verify(signature: signature, message: message, publicKey: publicKey) else { throw Error.signingFailed }144        return signature145    }146147    /// k = SHA-512(R ‖ A ‖ M) mod ℓ.148    static func challenge(encodedR: Bytes, publicKey: Bytes, message: Bytes) -> Sc {149        var h = SHA512()150        h.update(encodedR)151        h.update(publicKey)152        h.update(message)153        return Sc.reduceWide(h.finalize())154    }155156    /// Strict verification (see the policy at the top of this type). Never traps; any malformed input is `false`.157    public static func verify(signature: Bytes, message: Bytes, publicKey: Bytes) -> Bool {158        guard signature.count == signatureLength, publicKey.count == publicKeyLength else { return false }159        let encodedR = Bytes(signature[0..<32])160        let s = Sc(littleEndian: Bytes(signature[32..<64]))161        guard s.isCanonical else { return false }162        guard let a = EdPoint.decode(publicKey, strict: true), !a.isSmallOrder else { return false }163        guard let r = EdPoint.decode(encodedR, strict: true), !r.isSmallOrder else { return false }164        let k = challenge(encodedR: encodedR, publicKey: publicKey, message: message)165        // [S]B − [k]A, cofactorless166        let expected = EdPoint.add(EdPoint.multiplyBase(scalar: s.bytes), EdPoint.multiply(scalar: k.bytes, EdPoint.negate(a)))167        return expected.encode() == encodedR168    }169170    /// True for a public key `verify` can accept: 32 bytes, canonical encoding of a curve point, not of small order.171    public static func isValidPublicKey(_ publicKey: Bytes) -> Bool {172        guard let a = EdPoint.decode(publicKey, strict: true) else { return false }173        return !a.isSmallOrder174    }175176    /// True when the 32 bytes are the canonical RFC 8032 encoding of a curve point (small-order points included).177    public static func isCanonicalPoint(_ bytes: Bytes) -> Bool {178        EdPoint.decode(bytes, strict: true) != nil179    }180181    /// True when the 32 bytes decode to one of the eight small-order points; nil when they are not a canonical point.182    public static func isSmallOrder(_ bytes: Bytes) -> Bool? {183        EdPoint.decode(bytes, strict: true)?.isSmallOrder184    }185186    /// Solana's `is_on_curve`: true when the 32 bytes decompress to a curve point with the lenient rules of187    /// curve25519-dalek (y taken modulo p, sign bit of x = 0 ignored). This is the test that defines program-derived188    /// addresses, which are the hashes for which it is **false**. It is not a public-key validity check: use189    /// `isValidPublicKey` for that. False for any input that is not 32 bytes.190    public static func isOnCurve(_ bytes: Bytes) -> Bool {191        EdPoint.decode(bytes, strict: false) != nil192    }193194    /// SLIP-0010 hierarchical derivation for Ed25519: hardened children only, HMAC-SHA512 keyed with "ed25519 seed".195    public enum SLIP10 {196        /// A node of the tree: its 32-byte private key is an Ed25519 seed.197        public struct Node: Equatable, Sendable {198            /// 32-byte Ed25519 seed of this node.199            public private(set) var privateKey: Bytes200            /// 32-byte chain code.201            public private(set) var chainCode: Bytes202203            init(_ i: Bytes) {204                privateKey = Bytes(i[0..<32])205                chainCode = Bytes(i[32..<64])206            }207208            /// The hardened child `index` (0 ≤ index < 2^31; the hardened bit is added here).209            public func deriveHardened(_ index: UInt32) throws -> Node {210                guard index < 0x8000_0000 else { throw Error.invalidDerivationIndex }211                var data: Bytes = [0x00] + privateKey + Endian.be32(index | 0x8000_0000)212                var i = HMAC<SHA512>.authenticate(key: chainCode, message: data)213                defer {214                    SecureMemory.zero(&data)215                    SecureMemory.zero(&i)216                }217                return Node(i)218            }219220            /// The Ed25519 public key of this node.221            public func publicKey() throws -> Bytes { try Ed25519.publicKey(seed: privateKey) }222223            /// Erases the private key and the chain code.224            public mutating func wipe() {225                SecureMemory.zero(&privateKey)226                SecureMemory.zero(&chainCode)227            }228        }229230        /// The master node of a seed of 16 to 64 bytes (a BIP-39 seed is 64 bytes).231        public static func master(seed: Bytes) throws -> Node {232            guard (16...64).contains(seed.count) else { throw Error.invalidDerivationSeed }233            var i = HMAC<SHA512>.authenticate(key: Bytes("ed25519 seed".utf8), message: seed)234            defer { SecureMemory.zero(&i) }235            return Node(i)236        }237238        /// The node at m / path[0]' / path[1]' / … (every index is hardened; give them without the hardened bit).239        public static func derive(seed: Bytes, path: [UInt32]) throws -> Node {240            var node = try master(seed: seed)241            for index in path {242                let child = try node.deriveHardened(index)243                node.wipe()244                node = child245            }246            return node247        }248    }249}250
Files main
Menu

Theme