SPB Git

Repository Public

U256.swift 9.6 KB 256 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSecp256k1/U256.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 QyvoraMath4243/// 256-bit unsigned integer, four 64-bit limbs, least significant first.44public struct U256: Equatable, Sendable {45    public var a0: UInt6446    public var a1: UInt6447    public var a2: UInt6448    public var a3: UInt644950    public static let zero = U256(0, 0, 0, 0)51    public static let one = U256(1, 0, 0, 0)5253    @inlinable public init(_ a0: UInt64, _ a1: UInt64, _ a2: UInt64, _ a3: UInt64) {54        self.a0 = a0; self.a1 = a1; self.a2 = a2; self.a3 = a355    }5657    /// Big-endian decoding of exactly 32 bytes.58    public init?(bigEndian b: Bytes) {59        guard b.count == 32 else { return nil }60        self = b.withUnsafeBufferPointer { p in61            U256(Endian.loadBE64(p.baseAddress! + 24), Endian.loadBE64(p.baseAddress! + 16),62                 Endian.loadBE64(p.baseAddress! + 8), Endian.loadBE64(p.baseAddress!))63        }64    }6566    init(hex: String) {67        self.init(bigEndian: Bytes(hex: hex)!)!68    }6970    /// 32 bytes, big endian.71    public var bytes: Bytes {72        Endian.be64(a3) + Endian.be64(a2) + Endian.be64(a1) + Endian.be64(a0)73    }7475    @inlinable func limb(_ i: Int) -> UInt64 {76        switch i {77        case 0: return a078        case 1: return a179        case 2: return a280        default: return a381        }82    }8384    /// Bit `i` (0 = least significant) as 0 or 1.85    @inlinable func bit(_ i: Int) -> UInt64 {86        (limb(i >> 6) >> UInt64(i & 63)) & 187    }8889    /// All-ones when the value is zero, zero otherwise (no branch on the value).90    @inlinable var zeroMask: UInt64 {91        let v = a0 | a1 | a2 | a392        // (v | -v) has its top bit set exactly when v != 093        return ((v | (0 &- v)) >> 63) &- 194    }9596    public var isZero: Bool { zeroMask != 0 }97    public var isOdd: Bool { a0 & 1 == 1 }9899    // Carries and borrows are computed with bit arithmetic only. The earlier form100    // (`addingReportingOverflow` followed by `flag ? 1 : 0`) was compiled by Swift 6.3 / 6.4 into101    // conditional branches on the carry, that is on secret limbs (finding QYV-AUD-002): a Boolean102    // never appears here, so there is nothing for the optimiser to branch on.103104    /// x + y + carryIn (0 or 1) as (sum, carryOut). carryOut = top bit of majority(x, y, ¬sum).105    @inlinable @inline(__always)106    static func adc(_ x: UInt64, _ y: UInt64, _ carryIn: UInt64) -> (UInt64, UInt64) {107        let s = x &+ y &+ carryIn108        return (s, ((x & y) | ((x | y) & ~s)) >> 63)109    }110111    /// x − y − borrowIn (0 or 1) as (difference, borrowOut). borrowOut = top bit of majority(¬x, y, difference).112    @inlinable @inline(__always)113    static func sbb(_ x: UInt64, _ y: UInt64, _ borrowIn: UInt64) -> (UInt64, UInt64) {114        let d = x &- y &- borrowIn115        return (d, ((~x & y) | ((~x | y) & d)) >> 63)116    }117118    /// a + b, with the carry out (0 or 1).119    @inlinable static func add(_ a: U256, _ b: U256) -> (U256, UInt64) {120        let (s0, c0) = adc(a.a0, b.a0, 0)121        let (s1, c1) = adc(a.a1, b.a1, c0)122        let (s2, c2) = adc(a.a2, b.a2, c1)123        let (s3, c3) = adc(a.a3, b.a3, c2)124        return (U256(s0, s1, s2, s3), c3)125    }126127    /// a − b, with the borrow out (0 or 1).128    @inlinable static func sub(_ a: U256, _ b: U256) -> (U256, UInt64) {129        let (s0, b0) = sbb(a.a0, b.a0, 0)130        let (s1, b1) = sbb(a.a1, b.a1, b0)131        let (s2, b2) = sbb(a.a2, b.a2, b1)132        let (s3, b3) = sbb(a.a3, b.a3, b2)133        return (U256(s0, s1, s2, s3), b3)134    }135136    /// `a` when `mask` is all ones, `b` when it is zero.137    @inlinable static func select(_ mask: UInt64, _ a: U256, _ b: U256) -> U256 {138        U256((a.a0 & mask) | (b.a0 & ~mask), (a.a1 & mask) | (b.a1 & ~mask),139             (a.a2 & mask) | (b.a2 & ~mask), (a.a3 & mask) | (b.a3 & ~mask))140    }141142    /// True when a < b (variable time: public values only).143    static func lessThan(_ a: U256, _ b: U256) -> Bool {144        sub(a, b).1 == 1145    }146}147148/// Arithmetic modulo an odd 256-bit modulus greater than 2^255, by Montgomery multiplication (R = 2^256).149/// Additions, subtractions and multiplications run in time independent of their operands;150/// exponentiation branches on the exponent, which is always a public constant here.151struct Modulus: Sendable {152    let m: U256153    /// −m⁻¹ mod 2^64154    let mInv: UInt64155    /// R mod m (Montgomery form of 1)156    let r1: U256157    /// R² mod m158    let r2: U256159160    init(_ m: U256) {161        self.m = m162        var inv: UInt64 = 1163        for _ in 0..<6 { inv = inv &* (2 &- m.a0 &* inv) }164        mInv = 0 &- inv165        // R mod m = 2^256 − m because 2^255 < m < 2^256166        let r = U256.sub(.zero, m).0167        r1 = r168        var x = r169        for _ in 0..<256 { x = Modulus.addMod(x, x, m) }170        r2 = x171    }172173    @inline(__always) static func addMod(_ a: U256, _ b: U256, _ m: U256) -> U256 {174        let (s, carry) = U256.add(a, b)175        let (d, borrow) = U256.sub(s, m)176        // keep s only when there was no carry and s < m177        let keepS = (0 &- borrow) & ~(0 &- carry)178        return U256.select(keepS, s, d)179    }180181    @inline(__always) func add(_ a: U256, _ b: U256) -> U256 { Modulus.addMod(a, b, m) }182183    @inline(__always) func sub(_ a: U256, _ b: U256) -> U256 {184        let (d, borrow) = U256.sub(a, b)185        let (e, _) = U256.add(d, m)186        return U256.select(0 &- borrow, e, d)187    }188189    @inline(__always) func neg(_ a: U256) -> U256 { sub(.zero, a) }190191    /// Reduces a value below 2^256 (one conditional subtraction is enough because m > 2^255).192    @inline(__always) func reduce(_ a: U256) -> U256 {193        let (d, borrow) = U256.sub(a, m)194        return U256.select(0 &- borrow, a, d)195    }196197    /// t + b·c + carry as (low, high).198    @inline(__always) private static func mac(_ t: UInt64, _ b: UInt64, _ c: UInt64, _ carry: UInt64) -> (UInt64, UInt64) {199        let p = b.multipliedFullWidth(by: c)200        let (l1, c1) = U256.adc(p.low, t, 0)201        let (l2, c2) = U256.adc(l1, carry, 0)202        // p.high ≤ 2^64 − 2, and the two carries cannot both be set past it: no overflow203        return (l2, p.high &+ c1 &+ c2)204    }205206    /// Montgomery product a·b·R⁻¹ mod m (coarsely integrated operand scanning).207    func montMul(_ a: U256, _ b: U256) -> U256 {208        var t0: UInt64 = 0, t1: UInt64 = 0, t2: UInt64 = 0, t3: UInt64 = 0, t4: UInt64 = 0209        for i in 0..<4 {210            let bi = b.limb(i)211            var c: UInt64 = 0212            (t0, c) = Modulus.mac(t0, a.a0, bi, c)213            (t1, c) = Modulus.mac(t1, a.a1, bi, c)214            (t2, c) = Modulus.mac(t2, a.a2, bi, c)215            (t3, c) = Modulus.mac(t3, a.a3, bi, c)216            let (s4, t5) = U256.adc(t4, c, 0)217            let q = t0 &* mInv218            var d: UInt64219            (_, d) = Modulus.mac(t0, q, m.a0, 0)220            (t0, d) = Modulus.mac(t1, q, m.a1, d)221            (t1, d) = Modulus.mac(t2, q, m.a2, d)222            (t2, d) = Modulus.mac(t3, q, m.a3, d)223            let (s3, c3) = U256.adc(s4, d, 0)224            t3 = s3225            t4 = t5 &+ c3226        }227        let t = U256(t0, t1, t2, t3)228        let (d, borrow) = U256.sub(t, m)229        // keep t only when t4 == 0 and t < m230        let keepT = (0 &- borrow) & ((t4 & 1) &- 1)231        return U256.select(keepT, t, d)232    }233234    @inline(__always) func toMont(_ a: U256) -> U256 { montMul(a, r2) }235    @inline(__always) func fromMont(_ a: U256) -> U256 { montMul(a, .one) }236237    /// Plain product a·b mod m of two values in normal form.238    func mul(_ a: U256, _ b: U256) -> U256 { montMul(montMul(a, b), r2) }239240    /// a^e in Montgomery form (a in Montgomery form). The exponent is public (fixed constants only).241    func montPow(_ a: U256, _ e: U256) -> U256 {242        var result = r1243        for i in stride(from: 255, through: 0, by: -1) {244            result = montMul(result, result)245            if e.bit(i) == 1 { result = montMul(result, a) }246        }247        return result248    }249250    /// Modular inverse by Fermat (m prime), normal form in and out; inverse(0) = 0.251    func inverse(_ a: U256) -> U256 {252        let e = U256.sub(m, U256(2, 0, 0, 0)).0253        return fromMont(montPow(toMont(a), e))254    }255}256
Files main
Menu

Theme