SPB Git

Repository Public

ExecutionCanonical.swift 12.7 KB 219 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Execution/ExecutionCanonical.swift3// Description: The two serializations the V11 execution layer has approved by passkey, byte for byte the backend's:4//              (1) "stable JSON" — a domain tag, a line feed, then the object as JSON with its keys sorted at every depth5//                  (services/api/src/derivatives/exec.ts `canonicalIntentHash`, services/api/src/trading-api/key-model.ts6//                  `canonicalJson` + `intentChallenge`); (2) the exact decimal form of packages/derivatives/src/decimal.ts7//                  (`D.str(D.from(x))`) used inside the length-prefixed mandates. Plus the strict reading rule of this domain:8//                  a served object is accepted only when re-encoding what this code understood gives back exactly what was served.9//10// Author: Simon-Pierre Boucher11// Contact: contact@spboucher.ai12import Foundation1314/** JavaScript's default string order (UTF-16 code units): `Object.keys(o).sort()` and `cmpStr` of the backend. */15func executionCodeUnitOrder(_ a: String, _ b: String) -> Bool { a.utf16.lexicographicallyPrecedes(b.utf16) }1617/**18 `stableJson` of the backend: `JSON.stringify` of every scalar, arrays in their order, object keys sorted, no white space.19 Anything `JSON.stringify` would not print the way this code can reproduce exactly is refused (`ApprovalError.unsupported`).20 */21public enum ExecutionStableJSON {22    /** 2^53 − 1: above it a JavaScript number is no longer the integer that was written. */23    static let maxSafeInteger: Int64 = 9_007_199_254_740_9912425    public static func encode(_ v: JSONValue) throws -> String {26        var out = ""27        try write(v, into: &out)28        return out29    }3031    /** `<domain>\n<stable JSON>` as UTF-8: the bytes whose SHA-256 is the WebAuthn challenge. */32    public static func bytes(domain: String, _ v: JSONValue) throws -> Data { Data((domain + "\n" + (try encode(v))).utf8) }3334    private static func write(_ v: JSONValue, into out: inout String) throws {35        switch v {36        case .null: out += "null"37        case .bool(let b): out += b ? "true" : "false"38        case .int(let i):39            guard abs(i) <= maxSafeInteger else { throw ApprovalError.unsupported("an integer beyond 2^53 has no exact JSON number") }40            out += String(i)41        case .double(let d): out += try number(d)42        case .string(let s): quote(s, into: &out)43        case .array(let a):44            out += "["45            for (k, x) in a.enumerated() { if k > 0 { out += "," }; try write(x, into: &out) }46            out += "]"47        case .object(let o):48            out += "{"49            for (k, key) in o.keys.sorted(by: executionCodeUnitOrder).enumerated() {50                if k > 0 { out += "," }51                quote(key, into: &out); out += ":"52                try write(o[key]!, into: &out)53            }54            out += "}"55        }56    }5758    /** `JSON.stringify` of a string: `"` and `\` escaped, the short escapes, `\u00xx` (lower-case hex) below U+0020, everything else as is. */59    static func quote(_ s: String, into out: inout String) {60        out += "\""61        for u in s.unicodeScalars {62            switch u.value {63            case 0x22: out += "\\\""64            case 0x5c: out += "\\\\"65            case 0x08: out += "\\b"66            case 0x0c: out += "\\f"67            case 0x0a: out += "\\n"68            case 0x0d: out += "\\r"69            case 0x09: out += "\\t"70            case 0..<0x20: out += "\\u00" + (u.value < 0x10 ? "0" : "") + String(u.value, radix: 16)71            default: out.unicodeScalars.append(u)72            }73        }74        out += "\""75    }7677    /**78     ECMAScript `Number::toString` of a finite double: the shortest digits that read back as the same double (what Swift's79     `description` also produces), laid out by the specification's rule — plain digits between 1e-6 and 1e21, an exponent otherwise.80     */81    static func number(_ d: Double) throws -> String {82        guard d.isFinite else { throw ApprovalError.unsupported("a non-finite number has no JSON form") }83        if d == 0 { return "0" }84        // Swift prints "1500.5", "5.0", "1e-07", "1.5e+16": take the digits and the decimal exponent out of it85        let text = abs(d).description.lowercased()86        let parts = text.split(separator: "e", omittingEmptySubsequences: false)87        guard parts.count <= 2, let mantissa = parts.first, mantissa.utf8.allSatisfy({ ($0 >= 48 && $0 <= 57) || $0 == 46 }) else { throw ApprovalError.unsupported("unreadable number \(text)") }88        var exp10 = 089        if parts.count == 2 { guard let e = Int(parts[1]) else { throw ApprovalError.unsupported("unreadable exponent \(text)") }; exp10 = e }90        let mp = mantissa.split(separator: ".", omittingEmptySubsequences: false)91        guard mp.count <= 2, !mp[0].isEmpty else { throw ApprovalError.unsupported("unreadable number \(text)") }92        var digits = String(mp[0]) + (mp.count == 2 ? String(mp[1]) : "")93        var n = mp[0].count + exp10                      // value = 0.<digits> × 10^n94        while digits.hasPrefix("0") { digits.removeFirst(); n -= 1 }95        while digits.hasSuffix("0") { digits.removeLast() }96        guard !digits.isEmpty else { throw ApprovalError.unsupported("unreadable number \(text)") }97        let k = digits.count, sign = d < 0 ? "-" : ""98        if k <= n, n <= 21 { return sign + digits + String(repeating: "0", count: n - k) }99        if 0 < n, n <= 21 { return sign + String(digits.prefix(n)) + "." + String(digits.dropFirst(n)) }100        if -6 < n, n <= 0 { return sign + "0." + String(repeating: "0", count: -n) + digits }101        let e = n - 1, es = (e < 0 ? "-" : "+") + String(abs(e))102        return sign + (k == 1 ? digits : String(digits.prefix(1)) + "." + String(digits.dropFirst(1))) + "e" + es103    }104}105106/** The strict reading of this domain's approved objects. */107public enum ExecutionStrict {108    /**109     Decode `served` as `T`, then require that encoding the decoded value gives back EXACTLY `served`: an unknown key, a value of110     another type, an explicit `null` where the schema has none, a number this code would print differently — each is a refusal,111     never an omission. This is the `strictObject` rule of the backend's schemas for objects with nested maps, numbers and112     nullable members (which `StrictObject` of Signing/Approval.swift has no readers for).113     */114    public static func decode<T: Codable>(_ type: T.Type = T.self, from served: JSONValue?, path: String) throws -> T {115        guard let served, served.objectValue != nil else { throw ApprovalError.unsupported("\(path) is not an object") }116        let value: T117        do { value = try served.decode(T.self) } catch { throw ApprovalError.unsupported("\(path) cannot be read: \(describe(error))") }118        let back: JSONValue119        do { back = try JSONValue.from(value) } catch { throw ApprovalError.unsupported("\(path) cannot be written back") }120        guard back == served else { throw ApprovalError.unsupported("\(path) carries \(difference(served, back, at: path))") }121        return value122    }123124    private static func describe(_ e: Error) -> String {125        switch e {126        case DecodingError.keyNotFound(let k, let c): return "missing " + (c.codingPath.map(\.stringValue) + [k.stringValue]).joined(separator: ".")127        case DecodingError.typeMismatch(_, let c), DecodingError.valueNotFound(_, let c), DecodingError.dataCorrupted(let c):128            return c.codingPath.map(\.stringValue).joined(separator: ".") + ": " + c.debugDescription129        default: return String(describing: e)130        }131    }132133    /** The first place where what was served and what was understood differ (for the refusal message; never a secret: these objects carry none). */134    static func difference(_ served: JSONValue, _ understood: JSONValue, at path: String) -> String {135        if let a = served.objectValue, let b = understood.objectValue {136            let extra = Set(a.keys).subtracting(b.keys).sorted()137            if !extra.isEmpty { return "a field this version does not know: \(path).\(extra.joined(separator: ", "))" }138            for k in a.keys.sorted() where a[k] != b[k] { return difference(a[k]!, b[k] ?? .null, at: "\(path).\(k)") }139            return "a different set of fields at \(path)"140        }141        if let a = served.arrayValue, let b = understood.arrayValue, a.count == b.count {142            for k in a.indices where a[k] != b[k] { return difference(a[k], b[k], at: "\(path).\(k)") }143        }144        return "a value this version reads differently at \(path)"145    }146}147148/** Exact decimal strings of the backend (`DEC_RE`, at most 60 digits) and their canonical form. No floating point. */149public enum ExecutionDecimal {150    /** `^-?(0|[1-9]\d*)(\.\d+)?$`, at most 60 digits: (negative, integer digits, fraction digits). */151    static func split(_ x: String) -> (negative: Bool, int: Substring, frac: Substring)? {152        guard x.utf8.count <= 62 else { return nil }153        var body = Substring(x)154        let negative = body.hasPrefix("-")155        if negative { body = body.dropFirst() }156        let parts = body.split(separator: ".", omittingEmptySubsequences: false)157        guard parts.count <= 2, let int = parts.first, !int.isEmpty, int.utf8.allSatisfy({ $0 >= 48 && $0 <= 57 }), int == "0" || int.first != "0" else { return nil }158        let frac = parts.count == 2 ? parts[1] : Substring("")159        if parts.count == 2 { guard !frac.isEmpty, frac.utf8.allSatisfy({ $0 >= 48 && $0 <= 57 }) else { return nil } }160        guard int.count + frac.count <= 60 else { return nil }161        return (negative, int, frac)162    }163164    public static func isValid(_ x: String) -> Bool { split(x) != nil }165    /** valid, not negative */166    public static func isNonNegative(_ x: String) -> Bool { split(x).map { !$0.negative } ?? false }167    /** valid, not negative, not zero */168    public static func isPositive(_ x: String) -> Bool { isNonNegative(x) && x.utf8.contains { $0 >= 49 && $0 <= 57 } }169170    /** `D.str(D.from(x))`: no trailing zero in the fraction, no "-0". */171    public static func canon(_ x: String) throws -> String {172        guard let p = split(x) else { throw ApprovalError.unsupported("invalid decimal string") }173        var frac = p.frac174        while frac.last == "0" { frac = frac.dropLast() }175        let zero = p.int == "0" && frac.isEmpty176        return (p.negative && !zero ? "-" : "") + String(p.int) + (frac.isEmpty ? "" : "." + frac)177    }178179    /** x × m, exact, canonical (x not negative). Used to recompute what the backend derives by a multiplication. */180    public static func multiply(_ x: String, by m: UInt32) throws -> String {181        guard let p = split(x), !p.negative else { throw ApprovalError.unsupported("invalid decimal string") }182        var digits = String(p.int) + String(p.frac)183        while digits.count > 1, digits.first == "0" { digits.removeFirst() }184        guard let units = try? BaseUnits(digits) else { throw ApprovalError.unsupported("decimal out of range") }185        return try canon(units.multiplied(by: m).formatted(decimals: p.frac.count))186    }187188    /** a == b as numbers. */189    public static func equal(_ a: String, _ b: String) -> Bool { (try? canon(a)) != nil && (try? canon(a)) == (try? canon(b)) }190191    /** a > b for two non-negative decimals; nil when either is not one. */192    public static func greater(_ a: String, _ b: String) -> Bool? {193        guard let x = split(a), let y = split(b), !x.negative, !y.negative else { return nil }194        if x.int.count != y.int.count { return x.int.count > y.int.count }195        if x.int != y.int { return String(x.int) > String(y.int) }196        let n = max(x.frac.count, y.frac.count)197        let fa = String(x.frac) + String(repeating: "0", count: n - x.frac.count), fb = String(y.frac) + String(repeating: "0", count: n - y.frac.count)198        return fa > fb199    }200}201202/** What every "prepare" of the risk engine stamps on its intent (risk/passkey.ts `Stamped`): a nonce and a 5-minute window, in unix milliseconds. */203public protocol ExecutionStampedIntent: PasskeyApprovable {204    var nonce: String { get }205    var createdAt: Int { get }206    var expiresAt: Int { get }207}208public extension ExecutionStampedIntent {209    var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt) / 1000) }210    func requireCurrent(_ now: Date) throws { guard expiry > now else { throw ApprovalError.expired } }211}212213extension ApprovalBinding {214    /** The server also states the hash in hex next to the intent: it must be the hash this code computed (a second, redundant, reading of the same binding). */215    static func requireStatedHash<O: PasskeyApprovable>(_ stated: String?, of object: O, what: String) throws {216        guard let stated, try object.approvalDigest().hex == stated else { throw ApprovalError.inconsistent("\(what): the stated hash is not the hash of the object") }217    }218}219
Files main
Menu

Theme