SPB Git

Repository Public

QRChunks.swift 6.9 KB 160 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraRecovery/QRChunks.swift8// Module           : Qyvora Recovery9// 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 QyvoraStorage43import QyvoraVault4445public enum QRChunkError: Error, Equatable, Sendable {46    case emptyPayload47    /// The chunk size must be between 16 and 2 048 bytes.48    case invalidChunkSize49    /// The payload needs more than 9 999 frames.50    case tooManyFrames51    /// The text is not a QYVORA frame.52    case malformedFrame53    /// The frame belongs to another payload (different total or checksum).54    case mixedSet55    /// A frame with an index already received carries different data.56    case conflictingDuplicate57    /// Frames are missing (1-based indices).58    case incomplete(missing: [Int])59    /// Every frame is present but the reassembled bytes do not match the checksum.60    case checksumMismatch61}6263/// Splits a payload too large for one QR code (a public identity, a transfer package) into numbered text frames:64///65///     qyv1:<index>/<total>:<checksum>:<data>66///67/// - `index` and `total`: decimal without leading zeros, 1 ≤ index ≤ total ≤ 999968/// - `checksum`: 16 lower-case hexadecimal digits = first 8 bytes of SHA-256(total as u32 big-endian ‖ whole payload);69///   identical in every frame of a set, so it also identifies the set70/// - `data`: base64url without padding of this frame's bytes (not empty)71///72/// Frames can be scanned in any order and more than once.73public enum QRChunker {74    public static let prefix = "qyv1"75    public static let defaultChunkSize = 60076    public static let maximumFrames = 99997778    static func checksum(total: Int, payload: Bytes) -> String {79        Bytes(SystemCrypto.sha256(Endian.be32(UInt32(total)) + payload).prefix(8)).hex80    }8182    /// `chunkSize` is the number of payload bytes per frame (600 bytes give frames of about 830 characters,83    /// comfortable for a phone screen at error-correction level M).84    public static func split(_ payload: Bytes, chunkSize: Int = defaultChunkSize) throws(QRChunkError) -> [String] {85        guard !payload.isEmpty else { throw .emptyPayload }86        guard (16...2048).contains(chunkSize) else { throw .invalidChunkSize }87        let total = (payload.count + chunkSize - 1) / chunkSize88        guard total <= maximumFrames else { throw .tooManyFrames }89        let sum = checksum(total: total, payload: payload)90        return (0..<total).map { i in91            let chunk = Bytes(payload[(i * chunkSize)..<min(payload.count, (i + 1) * chunkSize)])92            return "\(prefix):\(i + 1)/\(total):\(sum):\(Base64URL.encode(chunk))"93        }94    }95}9697/// Collects frames until the payload is complete.98public struct QRAssembler: Sendable {99    public private(set) var total: Int?100    private var checksum: String?101    private var chunks: [Int: Bytes] = [:]102103    public init() {}104105    public var receivedCount: Int { chunks.count }106    public var isComplete: Bool { total.map { chunks.count == $0 } ?? false }107108    /// 1-based indices not yet received (empty before the first frame).109    public var missingIndices: [Int] {110        guard let total else { return [] }111        return (1...total).filter { chunks[$0] == nil }112    }113114    static func number(_ text: Substring) -> Int? {115        guard (1...4).contains(text.utf8.count), text.utf8.allSatisfy({ $0 >= 0x30 && $0 <= 0x39 }), text.utf8.first != 0x30 else { return nil }116        return Int(text)117    }118119    /// Adds a scanned frame. Returns true when it was new, false for an identical duplicate.120    @discardableResult121    public mutating func add(_ frame: String) throws(QRChunkError) -> Bool {122        let parts = frame.split(separator: ":", omittingEmptySubsequences: false)123        guard parts.count == 4, parts[0] == QRChunker.prefix else { throw .malformedFrame }124        let position = parts[1].split(separator: "/", omittingEmptySubsequences: false)125        guard position.count == 2, let index = Self.number(position[0]), let frameTotal = Self.number(position[1]), index <= frameTotal,126              parts[2].utf8.count == 16, parts[2].utf8.allSatisfy({ ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x61 && $0 <= 0x66) }),127              let data = Base64URL.decode(String(parts[3])), !data.isEmpty, data.count <= 2048128        else { throw .malformedFrame }129        if let total, let checksum {130            guard total == frameTotal, checksum == parts[2] else { throw .mixedSet }131        }132        if let existing = chunks[index] {133            guard existing == data else { throw .conflictingDuplicate }134            return false135        }136        total = frameTotal137        checksum = String(parts[2])138        chunks[index] = data139        return true140    }141142    /// The original payload, once every frame is present and the checksum matches.143    public func assemble() throws(QRChunkError) -> Bytes {144        guard let total, let checksum else { throw .incomplete(missing: []) }145        let missing = missingIndices146        guard missing.isEmpty else { throw .incomplete(missing: missing) }147        var payload = Bytes()148        for i in 1...total { payload += chunks[i] ?? [] }149        guard QRChunker.checksum(total: total, payload: payload) == checksum else { throw .checksumMismatch }150        return payload151    }152153    /// Convenience for a complete list of frames in any order.154    public static func assemble(_ frames: [String]) throws(QRChunkError) -> Bytes {155        var assembler = QRAssembler()156        for frame in frames { try assembler.add(frame) }157        return try assembler.assemble()158    }159}160
Files main
Menu

Theme