SPB Git

Repository Public

Identity.swift 26.3 KB 586 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraIdentity/Identity.swift8// Module           : Qyvora Identity9// 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 Foundation42import QyvoraKeccak43import QyvoraMLDSA44import QyvoraMLKEM45import QyvoraMath46import QyvoraSLHDSA47import QyvoraStorage48import QyvoraVault4950/// Errors of the identity layer. No case carries key material.51public enum IdentityError: Error, Equatable, Sendable {52    /// Truncated, over-long or structurally invalid encoding.53    case malformed54    /// The text form does not start with the expected prefix or is not strict base64url.55    case invalidText56    case unsupportedVersion(UInt8)57    /// A key has the wrong size, fails its validity check, or the private and public parts do not match.58    case invalidKey59    case invalidPurpose60    case signingFailed61    /// A signature is missing, does not verify, or was made by another identity.62    case invalidSignature63    /// The envelope is addressed to another identity.64    case wrongRecipient65    /// The envelope was not sent by the expected identity.66    case unexpectedSender67    /// Key decapsulation or payload authentication failed.68    case decryptionFailed69    /// A rotation chain does not link, repeats an identity or contains an invalid certificate.70    case brokenChain71    case vault(VaultError)72}7374/// The algorithm suite of an identity. Suite 1:75/// ML-DSA-87 (FIPS 204) + SLH-DSA-SHAKE-256f (FIPS 205) for signatures, ML-KEM-1024 (FIPS 203) + X25519 for key exchange.76public enum IdentitySuite {77    public static let identifier: UInt8 = 178    public static let mldsa = MLDSA.ParameterSet.mldsa8779    public static let slhdsa = SLHDSA.ParameterSet.shake_256f80    public static let mlkem = MLKEM.ParameterSet.mlkem102481    /// Prefix of every signing context and transcript label.82    public static let domain = "QYVORA-IDENTITY-v1"83}8485/// What a signature is for. The name is part of the signing context, so a signature made for one purpose86/// never verifies for another.87public struct SignaturePurpose: Sendable, Hashable {88    /// 1 to 64 characters among `a-z 0-9 - . /`.89    public let name: String9091    public init?(_ name: String) {92        let ok = name.utf8.allSatisfy { ($0 >= 0x61 && $0 <= 0x7a) || ($0 >= 0x30 && $0 <= 0x39) || $0 == 0x2d || $0 == 0x2e || $0 == 0x2f }93        guard (1...64).contains(name.utf8.count), ok else { return nil }94        self.name = name95    }9697    private init(known: String) { name = known }9899    public static let message = SignaturePurpose(known: "message")100    public static let rotation = SignaturePurpose(known: "rotation")101    public static let envelope = SignaturePurpose(known: "envelope")102    public static let backup = SignaturePurpose(known: "backup")103104    /// The context string given to ML-DSA and SLH-DSA: "QYVORA-IDENTITY-v1/" ‖ name.105    public var context: Bytes { Bytes((IdentitySuite.domain + "/" + name).utf8) }106}107108/// The public half of an identity: what a user shows to a peer.109///110/// Binary form (4 278 bytes for suite 1; integers big-endian):111///112///     "QYID" (4) ‖ version (u8 = 1) ‖ suite (u8 = 1) ‖ createdAt (u64, seconds since 1970)113///     ‖ u16 length ‖ ML-DSA-87 public key (2 592)114///     ‖ u16 length ‖ SLH-DSA-SHAKE-256f public key (64)115///     ‖ u16 length ‖ ML-KEM-1024 encapsulation key (1 568)116///     ‖ u16 length ‖ X25519 public key (32)117///118/// Text form: "qyvora-id:" ‖ base64url(binary form), no padding.119///120/// Fingerprint (32 bytes): SHA3-256("QYVORA-IDENTITY-v1/fingerprint" ‖ suite (u8) ‖ the four length-prefixed keys121/// in the order above). The creation time is not part of the fingerprint.122public struct PublicIdentity: Sendable, Equatable, Hashable {123    public static let magic = Bytes("QYID".utf8)124    public static let version: UInt8 = 1125    public static let textPrefix = "qyvora-id:"126127    public let createdAt: UInt64128    public let mldsaPublicKey: Bytes129    public let slhdsaPublicKey: Bytes130    public let mlkemPublicKey: Bytes131    public let x25519PublicKey: Bytes132133    /// Checks sizes and the ML-KEM modulus check of FIPS 203 (section 7.2).134    public init(createdAt: UInt64, mldsaPublicKey: Bytes, slhdsaPublicKey: Bytes, mlkemPublicKey: Bytes, x25519PublicKey: Bytes) throws(IdentityError) {135        guard mldsaPublicKey.count == IdentitySuite.mldsa.publicKeySize, slhdsaPublicKey.count == IdentitySuite.slhdsa.publicKeySize,136              x25519PublicKey.count == X25519.keySize, MLKEM.isValidEncapsulationKey(IdentitySuite.mlkem, mlkemPublicKey)137        else { throw .invalidKey }138        self.createdAt = createdAt139        self.mldsaPublicKey = mldsaPublicKey140        self.slhdsaPublicKey = slhdsaPublicKey141        self.mlkemPublicKey = mlkemPublicKey142        self.x25519PublicKey = x25519PublicKey143    }144145    private func keys(into w: inout ByteWriter) {146        w.prefixed16(mldsaPublicKey)147        w.prefixed16(slhdsaPublicKey)148        w.prefixed16(mlkemPublicKey)149        w.prefixed16(x25519PublicKey)150    }151152    public var fingerprint: Bytes {153        var w = ByteWriter()154        w.raw(Bytes((IdentitySuite.domain + "/fingerprint").utf8))155        w.u8(IdentitySuite.identifier)156        keys(into: &w)157        return SHA3.sha3_256(w.bytes)158    }159160    /// The fingerprint as 16 groups of four upper-case hexadecimal digits, for comparison by eye or by voice.161    public var fingerprintText: String {162        let hex = Array(fingerprint.hex.uppercased())163        return stride(from: 0, to: hex.count, by: 4).map { String(hex[$0..<$0 + 4]) }.joined(separator: " ")164    }165166    public func encoded() -> Bytes {167        var w = ByteWriter()168        w.raw(Self.magic)169        w.u8(Self.version)170        w.u8(IdentitySuite.identifier)171        w.u64(createdAt)172        keys(into: &w)173        return w.bytes174    }175176    /// Strict parser: exact sizes, known version and suite, no trailing byte.177    public init(encoded: Bytes) throws(IdentityError) {178        var r = ByteReader(encoded)179        do {180            guard try r.raw(4) == Self.magic else { throw IdentityError.malformed }181            let version = try r.u8()182            guard version == Self.version else { throw IdentityError.unsupportedVersion(version) }183            guard try r.u8() == IdentitySuite.identifier else { throw IdentityError.malformed }184            let created = try r.u64()185            let a = try r.prefixed16(), b = try r.prefixed16(), c = try r.prefixed16(), d = try r.prefixed16()186            try r.finish()187            try self.init(createdAt: created, mldsaPublicKey: a, slhdsaPublicKey: b, mlkemPublicKey: c, x25519PublicKey: d)188        } catch let error as IdentityError {189            throw error190        } catch {191            throw .malformed192        }193    }194195    public var text: String { Self.textPrefix + Base64URL.encode(encoded()) }196197    public init(text: String) throws(IdentityError) {198        guard text.hasPrefix(Self.textPrefix), let bytes = Base64URL.decode(String(text.dropFirst(Self.textPrefix.count))) else {199            throw .invalidText200        }201        try self.init(encoded: bytes)202    }203}204205/// A detached signature by an identity.206///207/// Binary form:208///209///     "QYSG" (4) ‖ version (u8 = 1) ‖ flags (u8; bit 0 = SLH-DSA signature present, other bits zero)210///     ‖ signer fingerprint (32) ‖ u8 length ‖ purpose name (ASCII)211///     ‖ u16 length ‖ ML-DSA-87 signature (4 627)212///     [ ‖ u16 length ‖ SLH-DSA-SHAKE-256f signature (49 856) ]      only when flags bit 0 is set213///214/// Both algorithms sign the same bytes with the same context string (FIPS 204 / FIPS 205 `ctx`):215///216///     context = "QYVORA-IDENTITY-v1/" ‖ purpose name217///     signed  = "QYVORA-IDENTITY-v1/tbs" ‖ flags (u8) ‖ signer fingerprint (32) ‖ message218///219/// The flags byte is signed, so removing the SLH-DSA half of a dual signature invalidates the ML-DSA half.220/// Verification succeeds only if every signature present is valid.221public struct IdentitySignature: Sendable, Equatable {222    public static let magic = Bytes("QYSG".utf8)223    public static let version: UInt8 = 1224225    public let signerFingerprint: Bytes226    public let purpose: SignaturePurpose227    public let mldsaSignature: Bytes228    public let slhdsaSignature: Bytes?229230    public var isDual: Bool { slhdsaSignature != nil }231232    static func toBeSigned(dual: Bool, fingerprint: Bytes, message: Bytes) -> Bytes {233        Bytes((IdentitySuite.domain + "/tbs").utf8) + [dual ? 1 : 0] + fingerprint + message234    }235236    /// True when the signature was made by `signer` for `purpose` over `message`.237    /// With `requireDual`, a signature without its SLH-DSA half is refused.238    public func verify(message: Bytes, signer: PublicIdentity, purpose: SignaturePurpose, requireDual: Bool = false) -> Bool {239        let fingerprint = signer.fingerprint240        guard ConstantTime.equal(signerFingerprint, fingerprint), self.purpose == purpose, isDual || !requireDual else { return false }241        let tbs = Self.toBeSigned(dual: isDual, fingerprint: fingerprint, message: message)242        guard MLDSA.verify(IdentitySuite.mldsa, publicKey: signer.mldsaPublicKey, message: tbs, signature: mldsaSignature, context: purpose.context)243        else { return false }244        if let slhdsaSignature {245            return SLHDSA.verify(246                IdentitySuite.slhdsa, message: tbs, signature: slhdsaSignature, context: purpose.context, publicKey: signer.slhdsaPublicKey)247        }248        return true249    }250251    public func encoded() -> Bytes {252        var w = ByteWriter()253        w.raw(Self.magic)254        w.u8(Self.version)255        w.u8(isDual ? 1 : 0)256        w.raw(signerFingerprint)257        w.prefixed8(Bytes(purpose.name.utf8))258        w.prefixed16(mldsaSignature)259        if let slhdsaSignature { w.prefixed16(slhdsaSignature) }260        return w.bytes261    }262263    init(signerFingerprint: Bytes, purpose: SignaturePurpose, mldsaSignature: Bytes, slhdsaSignature: Bytes?) {264        self.signerFingerprint = signerFingerprint265        self.purpose = purpose266        self.mldsaSignature = mldsaSignature267        self.slhdsaSignature = slhdsaSignature268    }269270    public init(encoded: Bytes) throws(IdentityError) {271        var r = ByteReader(encoded)272        do {273            guard try r.raw(4) == Self.magic else { throw IdentityError.malformed }274            let version = try r.u8()275            guard version == Self.version else { throw IdentityError.unsupportedVersion(version) }276            let flags = try r.u8()277            guard flags <= 1 else { throw IdentityError.malformed }278            signerFingerprint = try r.raw(32)279            guard let purpose = SignaturePurpose(String(decoding: try r.prefixed8(), as: UTF8.self)) else { throw IdentityError.malformed }280            self.purpose = purpose281            mldsaSignature = try r.prefixed16()282            slhdsaSignature = flags == 1 ? try r.prefixed16() : nil283            try r.finish()284            guard mldsaSignature.count == IdentitySuite.mldsa.signatureSize,285                  slhdsaSignature.map({ $0.count == IdentitySuite.slhdsa.signatureSize }) ?? true286            else { throw IdentityError.malformed }287        } catch let error as IdentityError {288            throw error289        } catch {290            throw .malformed291        }292    }293}294295/// A complete identity: the public part and the four private keys. It is separate from every blockchain key.296///297/// Private encoding (the payload of the `identityKeys` vault record):298///299///     "QYIK" (4) ‖ version (u8 = 1) ‖ u32 length ‖ PublicIdentity (binary form)300///     ‖ u16 length ‖ ML-DSA-87 private key (4 896) ‖ u16 length ‖ SLH-DSA-SHAKE-256f secret key (128)301///     ‖ u16 length ‖ ML-KEM-1024 decapsulation key (3 168) ‖ u16 length ‖ X25519 private key (32)302public struct Identity: Sendable {303    public static let privateMagic = Bytes("QYIK".utf8)304305    public let publicIdentity: PublicIdentity306    let mldsaPrivateKey: Bytes307    let slhdsaSecretKey: Bytes308    let mlkemDecapsulationKey: Bytes309    let x25519PrivateKey: Bytes310311    /// Generates the four key pairs locally from the system random generator.312    public static func generate(createdAt: Date = Date()) -> Identity {313        let dsa = MLDSA.generateKeyPair(IdentitySuite.mldsa)314        let slh = SLHDSA.generateKeyPair(IdentitySuite.slhdsa)315        let kem = MLKEM.generateKeyPair(IdentitySuite.mlkem)316        let x = X25519.generateKeyPair()317        guard let publicIdentity = try? PublicIdentity(318            createdAt: UInt64(max(0, createdAt.timeIntervalSince1970)), mldsaPublicKey: dsa.publicKey, slhdsaPublicKey: slh.publicKey,319            mlkemPublicKey: kem.encapsulationKey, x25519PublicKey: x.publicKey)320        else { preconditionFailure("freshly generated keys must be valid") }321        return Identity(322            publicIdentity: publicIdentity, mldsaPrivateKey: dsa.privateKey, slhdsaSecretKey: slh.secretKey,323            mlkemDecapsulationKey: kem.decapsulationKey, x25519PrivateKey: x.privateKey)324    }325326    init(publicIdentity: PublicIdentity, mldsaPrivateKey: Bytes, slhdsaSecretKey: Bytes, mlkemDecapsulationKey: Bytes, x25519PrivateKey: Bytes) {327        self.publicIdentity = publicIdentity328        self.mldsaPrivateKey = mldsaPrivateKey329        self.slhdsaSecretKey = slhdsaSecretKey330        self.mlkemDecapsulationKey = mlkemDecapsulationKey331        self.x25519PrivateKey = x25519PrivateKey332    }333334    public var fingerprint: Bytes { publicIdentity.fingerprint }335336    /// Secret: store it only inside the vault. Wipe copies with `SecureMemory.zero`.337    public func privateEncoding() -> Bytes {338        var w = ByteWriter()339        w.raw(Self.privateMagic)340        w.u8(1)341        w.prefixed32(publicIdentity.encoded())342        w.prefixed16(mldsaPrivateKey)343        w.prefixed16(slhdsaSecretKey)344        w.prefixed16(mlkemDecapsulationKey)345        w.prefixed16(x25519PrivateKey)346        return w.bytes347    }348349    /// Strict parser. Every private key is checked against the public identity: for ML-DSA the public key recomputed350    /// from the private key (with its t0 and tr components verified, QYV-FUZ-001) and a test signature, the embedded351    /// public key for SLH-DSA, a test encapsulation for ML-KEM, the derived public key for X25519.352    public init(privateEncoding: Bytes) throws(IdentityError) {353        var r = ByteReader(privateEncoding)354        do {355            guard try r.raw(4) == Self.privateMagic else { throw IdentityError.malformed }356            let version = try r.u8()357            guard version == 1 else { throw IdentityError.unsupportedVersion(version) }358            publicIdentity = try PublicIdentity(encoded: try r.prefixed32(max: 1 << 16))359            mldsaPrivateKey = try r.prefixed16()360            slhdsaSecretKey = try r.prefixed16()361            mlkemDecapsulationKey = try r.prefixed16()362            x25519PrivateKey = try r.prefixed16()363            try r.finish()364        } catch let error as IdentityError {365            throw error366        } catch {367            throw .malformed368        }369        let probe = Bytes("QYVORA identity key check".utf8)370        guard MLDSA.isKeyPair(IdentitySuite.mldsa, privateKey: mldsaPrivateKey, publicKey: publicIdentity.mldsaPublicKey),371              let signature = try? MLDSA.sign(IdentitySuite.mldsa, privateKey: mldsaPrivateKey, message: probe, randomness: .deterministic),372              MLDSA.verify(IdentitySuite.mldsa, publicKey: publicIdentity.mldsaPublicKey, message: probe, signature: signature),373              (try? SLHDSA.publicKey(IdentitySuite.slhdsa, fromSecretKey: slhdsaSecretKey)) == publicIdentity.slhdsaPublicKey,374              MLKEM.isValidDecapsulationKey(IdentitySuite.mlkem, mlkemDecapsulationKey),375              let encapsulation = try? MLKEM.encapsulate(IdentitySuite.mlkem, encapsulationKey: publicIdentity.mlkemPublicKey),376              let decapsulated = try? MLKEM.decapsulate(377                IdentitySuite.mlkem, decapsulationKey: mlkemDecapsulationKey, ciphertext: encapsulation.ciphertext),378              ConstantTime.equal(decapsulated, encapsulation.sharedSecret),379              (try? X25519.publicKey(privateKey: x25519PrivateKey)) == publicIdentity.x25519PublicKey380        else { throw .invalidKey }381    }382383    // MARK: Vault storage384385    /// Stores the private encoding as an `identityKeys` record and returns the record identifier.386    @discardableResult387    public func store(in vault: Vault) async throws -> UUID {388        var encoding = privateEncoding()389        defer { SecureMemory.zero(&encoding) }390        do {391            return try await vault.addRecord(type: .identityKeys, payload: encoding)392        } catch let error as VaultError {393            throw IdentityError.vault(error)394        }395    }396397    public static func load(from vault: Vault, record id: UUID) async throws -> Identity {398        do {399            let record = try await vault.record(id)400            guard record.type == .identityKeys else { throw IdentityError.malformed }401            return try Identity(privateEncoding: record.payload)402        } catch let error as VaultError {403            throw IdentityError.vault(error)404        }405    }406407    // MARK: Signing408409    /// Signs `message` for `purpose`. With `dual`, the SLH-DSA signature is added (about 50 kB and much slower:410    /// meant for long-lived statements such as rotation certificates and backups).411    public func sign(_ message: Bytes, purpose: SignaturePurpose = .message, dual: Bool = false) throws(IdentityError) -> IdentitySignature {412        let fingerprint = publicIdentity.fingerprint413        let tbs = IdentitySignature.toBeSigned(dual: dual, fingerprint: fingerprint, message: message)414        guard let first = try? MLDSA.sign(IdentitySuite.mldsa, privateKey: mldsaPrivateKey, message: tbs, context: purpose.context) else {415            throw .signingFailed416        }417        var second: Bytes?418        if dual {419            guard let s = try? SLHDSA.sign(IdentitySuite.slhdsa, message: tbs, context: purpose.context, secretKey: slhdsaSecretKey) else {420                throw .signingFailed421            }422            second = s423        }424        return IdentitySignature(signerFingerprint: fingerprint, purpose: purpose, mldsaSignature: first, slhdsaSignature: second)425    }426427    // MARK: Rotation428429    /// Creates the successor identity and the certificate that links it to this one.430    public func rotate(at date: Date = Date(), dual: Bool = true) throws(IdentityError) -> (identity: Identity, certificate: RotationCertificate) {431        let next = Identity.generate(createdAt: date)432        return (next, try RotationCertificate.issue(previous: self, next: next, at: date, dual: dual))433    }434}435436/// Statement "the owner of `previous` now uses `next`", signed by both identities.437///438/// Binary form:439///440///     "QYRC" (4) ‖ version (u8 = 1) ‖ issuedAt (u64) ‖ u32 length ‖ previous PublicIdentity ‖ u32 length ‖ next PublicIdentity441///     ‖ u32 length ‖ IdentitySignature by previous ‖ u32 length ‖ IdentitySignature by next442///443/// Both signatures use the purpose "rotation" over444///445///     "QYVORA-IDENTITY-v1/rotation" ‖ issuedAt (u64) ‖ u32 length ‖ previous PublicIdentity ‖ u32 length ‖ next PublicIdentity446///447/// The signature by `previous` authorizes the change; the signature by `next` proves possession of the new keys.448public struct RotationCertificate: Sendable, Equatable {449    public static let magic = Bytes("QYRC".utf8)450451    public let issuedAt: UInt64452    public let previous: PublicIdentity453    public let next: PublicIdentity454    public let previousSignature: IdentitySignature455    public let nextSignature: IdentitySignature456457    static func statement(issuedAt: UInt64, previous: PublicIdentity, next: PublicIdentity) -> Bytes {458        var w = ByteWriter()459        w.raw(Bytes((IdentitySuite.domain + "/rotation").utf8))460        w.u64(issuedAt)461        w.prefixed32(previous.encoded())462        w.prefixed32(next.encoded())463        return w.bytes464    }465466    public static func issue(previous: Identity, next: Identity, at date: Date = Date(), dual: Bool = true) throws(IdentityError) -> RotationCertificate {467        let issuedAt = UInt64(max(0, date.timeIntervalSince1970))468        let statement = statement(issuedAt: issuedAt, previous: previous.publicIdentity, next: next.publicIdentity)469        return RotationCertificate(470            issuedAt: issuedAt, previous: previous.publicIdentity, next: next.publicIdentity,471            previousSignature: try previous.sign(statement, purpose: .rotation, dual: dual),472            nextSignature: try next.sign(statement, purpose: .rotation, dual: dual))473    }474475    /// True when both signatures are valid and the two identities differ.476    public func verify(requireDual: Bool = false) -> Bool {477        let statement = Self.statement(issuedAt: issuedAt, previous: previous, next: next)478        return previous.fingerprint != next.fingerprint479            && previousSignature.verify(message: statement, signer: previous, purpose: .rotation, requireDual: requireDual)480            && nextSignature.verify(message: statement, signer: next, purpose: .rotation, requireDual: requireDual)481    }482483    public func encoded() -> Bytes {484        var w = ByteWriter()485        w.raw(Self.magic)486        w.u8(1)487        w.u64(issuedAt)488        w.prefixed32(previous.encoded())489        w.prefixed32(next.encoded())490        w.prefixed32(previousSignature.encoded())491        w.prefixed32(nextSignature.encoded())492        return w.bytes493    }494495    init(issuedAt: UInt64, previous: PublicIdentity, next: PublicIdentity, previousSignature: IdentitySignature, nextSignature: IdentitySignature) {496        self.issuedAt = issuedAt497        self.previous = previous498        self.next = next499        self.previousSignature = previousSignature500        self.nextSignature = nextSignature501    }502503    public init(encoded: Bytes) throws(IdentityError) {504        var r = ByteReader(encoded)505        do {506            guard try r.raw(4) == Self.magic else { throw IdentityError.malformed }507            let version = try r.u8()508            guard version == 1 else { throw IdentityError.unsupportedVersion(version) }509            issuedAt = try r.u64()510            previous = try PublicIdentity(encoded: try r.prefixed32(max: 1 << 16))511            next = try PublicIdentity(encoded: try r.prefixed32(max: 1 << 16))512            previousSignature = try IdentitySignature(encoded: try r.prefixed32(max: 1 << 17))513            nextSignature = try IdentitySignature(encoded: try r.prefixed32(max: 1 << 17))514            try r.finish()515        } catch let error as IdentityError {516            throw error517        } catch {518            throw .malformed519        }520    }521}522523/// The history of an identity: certificates from the first identity a peer trusted to the current one.524///525/// Binary form: "QYCH" (4) ‖ version (u8 = 1) ‖ count (u16) ‖ count × (u32 length ‖ RotationCertificate).526public struct RotationChain: Sendable, Equatable {527    public static let magic = Bytes("QYCH".utf8)528    public static let maximumLength = 64529530    public private(set) var certificates: [RotationCertificate]531532    public init(_ certificates: [RotationCertificate] = []) {533        self.certificates = certificates534    }535536    public mutating func append(_ certificate: RotationCertificate) {537        certificates.append(certificate)538    }539540    /// Walks the chain from `root`, the identity the verifier already trusts, and returns the current identity.541    /// Each certificate must be valid, start where the previous one ended, not go back in time and never return542    /// to an identity already seen. An empty chain returns `root`.543    public func verify(from root: PublicIdentity, requireDual: Bool = false) throws(IdentityError) -> PublicIdentity {544        guard certificates.count <= Self.maximumLength else { throw .brokenChain }545        var current = root546        var seen: Set<Bytes> = [root.fingerprint]547        var lastIssued: UInt64 = 0548        for certificate in certificates {549            guard certificate.previous == current, certificate.issuedAt >= lastIssued, certificate.verify(requireDual: requireDual),550                  seen.insert(certificate.next.fingerprint).inserted551            else { throw .brokenChain }552            current = certificate.next553            lastIssued = certificate.issuedAt554        }555        return current556    }557558    public func encoded() -> Bytes {559        var w = ByteWriter()560        w.raw(Self.magic)561        w.u8(1)562        w.u16(UInt16(min(certificates.count, 0xffff)))563        for c in certificates { w.prefixed32(c.encoded()) }564        return w.bytes565    }566567    public init(encoded: Bytes) throws(IdentityError) {568        var r = ByteReader(encoded)569        do {570            guard try r.raw(4) == Self.magic else { throw IdentityError.malformed }571            let version = try r.u8()572            guard version == 1 else { throw IdentityError.unsupportedVersion(version) }573            let count = Int(try r.u16())574            guard count <= Self.maximumLength else { throw IdentityError.malformed }575            var list: [RotationCertificate] = []576            for _ in 0..<count { list.append(try RotationCertificate(encoded: try r.prefixed32(max: 1 << 19))) }577            try r.finish()578            certificates = list579        } catch let error as IdentityError {580            throw error581        } catch {582            throw .malformed583        }584    }585}586
Files main
Menu

Theme