Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Sources/FuzzTargets/Targets+Storage.swift8// Module : Tests9// 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 AuditSupport42import Foundation43import QyvoraIdentity44import QyvoraMath45@testable import QyvoraRecovery46import QyvoraStorage47@testable import QyvoraVault4849// Files and packages read from disk or received from another device: the vault file, the backup50// file, public identities, identity signatures, rotation certificates and chains, hybrid envelopes51// (transfer packages), private identity encodings, QR frame sets.5253let fuzzPassword = "fuzz-password"5455/// Small enough to run the password KDF inside a fuzz iteration.56func isCheap(_ kdf: KDFParameters) -> Bool {57 kdf.argon2MemoryKiB <= 64 && kdf.argon2Iterations <= 2 && kdf.argon2Parallelism <= 2 && kdf.pbkdf2Iterations <= 6458}5960/// The input with its trailing 32 bytes replaced by SHA-256 of what precedes them: both file formats end with61/// such a checksum, which a blind mutation would never satisfy.62func withFixedChecksum(_ input: Bytes) -> Bytes? {63 guard input.count >= 32 else { return nil }64 let body = Bytes(input[0..<(input.count - 32)])65 return body + SystemCrypto.sha256(body)66}6768/// One throw-away identity per process (generated from the system generator, never written to the committed corpus).69let processIdentity = Identity.generate(createdAt: Date(timeIntervalSince1970: 1_800_000_000))70let processPeer = Identity.generate(createdAt: Date(timeIntervalSince1970: 1_800_000_001))7172func sampleRecords() -> [VaultRecord] {73 let t = Date(timeIntervalSince1970: 1_800_000_000)74 return [75 VaultRecord(id: UUID(bytes16: fixtureBytes("rec1", 16)) ?? UUID(), type: .custom, createdAt: t, updatedAt: t, payload: Bytes("first".utf8)),76 VaultRecord(id: UUID(bytes16: fixtureBytes("rec2", 16)) ?? UUID(), type: .setting, createdAt: t, updatedAt: t, payload: fixtureBytes("payload", 70)),77 ]78}7980func vaultFileSeeds() -> [Bytes] {81 func slot(_ label: String) -> VaultFile.WrapSlot {82 VaultFile.WrapSlot(83 kdf: .insecureForTesting, argon2Salt: fixtureBytes(label + "a", 16), pbkdf2Salt: fixtureBytes(label + "p", 16), nonce: fixtureBytes(label + "n", 12),84 wrapped: fixtureBytes(label + "w", 48))85 }86 func record(_ label: String, _ type: RecordType, _ size: Int) -> VaultFile.SealedRecord {87 VaultFile.SealedRecord(88 id: fixtureBytes(label, 16), type: type, createdAt: 1_800_000_000, updatedAt: 1_800_000_100, epoch: 1, nonce: fixtureBytes(label + "n", 12),89 sealed: fixtureBytes(label + "s", size))90 }91 let macKey = fixtureBytes("mac", 32)92 let minimal = VaultFile(vaultID: fixtureBytes("vault", 16), createdAt: 1_800_000_000, epoch: 1, generation: 0, password: slot("pw"), device: nil, pin: nil, records: [])93 let full = VaultFile(94 vaultID: fixtureBytes("vault2", 16), createdAt: 1_800_000_000, epoch: 3, generation: 17, password: slot("pw2"),95 device: VaultFile.DeviceSlot(usesSecureEnclave: false, blob: fixtureBytes("dev", 60)), pin: slot("pin"),96 records: [record("r1", .custom, 16), record("r2", .setting, 80)])97 let enclave = VaultFile(98 vaultID: fixtureBytes("vault3", 16), createdAt: 1, epoch: 1, generation: 1, password: slot("pw3"),99 device: VaultFile.DeviceSlot(usesSecureEnclave: true, blob: fixtureBytes("se", 140)), pin: nil, records: [record("r3", .custom, 33)])100 return [minimal, full, enclave].map { $0.encoded(macKey: macKey) }101}102103/// A real vault created with tiny KDF parameters and the fuzz password: the bytes of its file.104func realVaultSeeds() -> [Bytes] {105 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("qyfuzz-seed-\(getpid())-\(UInt64.random(in: 0...UInt64.max))")106 defer { try? FileManager.default.removeItem(at: dir) }107 guard let store = try? FileStore(root: dir) else { return [] }108 let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting))109 nonisolated(unsafe) var out = [Bytes]()110 fuzzAwait {111 do {112 try await vault.create(password: fuzzPassword)113 if let b = try? store.read("vault.qyv") { out.append(b) }114 fuzzUse(try await vault.addRecord(type: .custom, payload: Bytes("seed record".utf8)))115 fuzzUse(try await vault.addRecord(type: .setting, payload: fixtureBytes("vault-seed", 90)))116 if let b = try? store.read("vault.qyv") { out.append(b) }117 } catch {}118 }119 return out120}121122func backupSeeds() -> [Bytes] {123 var out = [Bytes]()124 let id = fixtureBytes("backup-vault", 16)125 if let b = try? BackupFile.create(records: sampleRecords(), vaultID: id, password: fuzzPassword, kdf: .insecureForTesting) { out.append(b) }126 if let b = try? BackupFile.create(records: [], vaultID: id, password: fuzzPassword, kdf: .insecureForTesting) { out.append(b) }127 if let b = try? BackupFile.create(128 records: sampleRecords(), vaultID: id, password: fuzzPassword, kdf: .insecureForTesting, signer: IdentityDetachedSigner(processIdentity))129 {130 out.append(b)131 }132 return out133}134135// A backup that authenticates under the password but whose content is hostile: the realistic case of a file (or a136// device-to-device transfer) prepared by an attacker who also tells the victim the password. Blind mutation never137// passes AES-GCM, so the harness seals the fuzz input itself.138let hostileBackupSalts = (argon2: fixtureBytes("hostile-backup/a", 16), pbkdf2: fixtureBytes("hostile-backup/p", 16))139let hostileBackupKey: Bytes? = {140 let secret = KeyStretching.passwordBytes(fuzzPassword)141 return try? KeyStretching.deriveKey(142 secret: secret, argon2Salt: hostileBackupSalts.argon2, pbkdf2Salt: hostileBackupSalts.pbkdf2, parameters: .insecureForTesting, info: VaultLabels.backup)143}()144145func hostileBackup(createdAt: UInt64, declaredCount: UInt32, plaintext: Bytes) -> Bytes? {146 guard let key = hostileBackupKey else { return nil }147 var header = ByteWriter()148 header.u64(createdAt)149 header.raw(fixtureBytes("hostile-backup/vault", 16))150 KDFParameters.insecureForTesting.encode(into: &header)151 header.raw(hostileBackupSalts.argon2)152 header.raw(hostileBackupSalts.pbkdf2)153 header.u32(declaredCount)154 header.prefixed32([])155 var out = ByteWriter()156 out.raw(BackupFile.magic)157 out.u16(BackupFile.version)158 out.prefixed32(header.bytes)159 let nonce = fixtureBytes("hostile-backup/nonce", 12) // fixed: a test key that protects nothing160 guard let sealed = try? SystemAEAD().seal(key: key, nonce: nonce, plaintext: plaintext, associatedData: out.bytes) else { return nil }161 out.raw(nonce)162 out.prefixed32(sealed)163 out.u32(0)164 out.raw(SystemCrypto.sha256(out.bytes))165 return out.bytes166}167168/// Fuzz input of `backup-authenticated`: mode ‖ header time (8) ‖ then, in structured mode, records169/// (type ‖ createdAt (8) ‖ updatedAt (8) ‖ id (16) ‖ length-prefixed payload); in raw mode, the plaintext itself.170func hostileBackupSeed(_ records: [(UInt8, UInt64, UInt64, String, Bytes)], mode: UInt8 = 0) -> Bytes {171 var out: Bytes = [mode] + Endian.be64(1_800_000_000)172 for r in records { out += [r.0] + Endian.be64(r.1) + Endian.be64(r.2) + fixtureBytes(r.3, 16) + fuzzFields(r.4) }173 return out174}175176final class FuzzVaultDirectory: @unchecked Sendable {177 static let shared = FuzzVaultDirectory()178 let store: FileStore?179 init() {180 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("qyfuzz-vault-\(getpid())")181 store = try? FileStore(root: dir)182 }183}184185let storageTargets: [FuzzTarget] = [186 FuzzTarget(187 "vault-file", "Vault file parser (as given, and with the trailing checksum recomputed), canonical re-encoding", maxLength: 4096,188 tokens: [Bytes("QYVORAVF".utf8), [0, 1], [0, 0, 0, 0], [0xff, 0xff, 0xff, 0xff]], seeds: vaultFileSeeds189 ) { input in190 attempt("raw:") { try VaultFile.parse(input) }191 guard let fixed = withFixedChecksum(input), let parsed = attempt("fixed:", { () throws -> VaultFile.Parsed in try VaultFile.parse(fixed) }) else { return }192 // the parser is strict: what it accepts re-encodes to the same authenticated bytes193 fuzzCheck(parsed.file.authenticatedBytes() == parsed.authenticated, "vault file re-encodes differently")194 fuzzCheck(parsed.mac.count == 32, "MAC length")195 fuzzCheck(parsed.authenticated + parsed.mac == Bytes(fixed[0..<(fixed.count - 32)]), "authenticated bytes and MAC do not cover the file")196 },197198 FuzzTarget(199 "vault-open", "Vault opened from an arbitrary file on disk: state queries, password unlock, record access", maxLength: 4096,200 tokens: [Bytes("QYVORAVF".utf8)], seeds: realVaultSeeds201 ) { input in202 guard let store = FuzzVaultDirectory.shared.store else { return }203 let candidate = withFixedChecksum(input) ?? input204 // run the password KDF only when the file asks for a small one (the limits accept up to 2 GiB of Argon2 memory)205 let parsed = try? VaultFile.parse(candidate)206 let cheap = parsed?.file.password.map { isCheap($0.kdf) } ?? true207 try? store.remove("vault.qyv")208 try? store.removePrevious("vault.qyv")209 guard (try? store.write(candidate, to: "vault.qyv", keepPrevious: false)) != nil else { return }210 let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting))211 fuzzAwait {212 fuzzUse(await vault.exists)213 fuzzUse(await vault.isPINEnabled)214 fuzzUse(await vault.isDeviceSlotEnabled)215 if (try? await vault.vaultID()) != nil { FuzzOutcome.note("id") }216 if (try? await vault.report()) != nil { FuzzOutcome.note("report") }217 guard cheap else { return }218 do {219 try await vault.unlock(password: fuzzPassword)220 FuzzOutcome.note("unlocked")221 let records = try await vault.records()222 let summaries = try await vault.recordSummaries()223 fuzzCheck(records.count == summaries.count, "record list and summaries disagree")224 fuzzUse(try await vault.verifyIntegrity())225 } catch {226 FuzzOutcome.note(String(describing: error))227 }228 if (try? await vault.unlockWithDevice()) != nil { FuzzOutcome.note("device") }229 await vault.lock()230 }231 },232233 FuzzTarget(234 "backup-file", "Backup file parser and opening (as given, and with the trailing checksum recomputed)", maxLength: 16_384,235 tokens: [Bytes("QYVORABK".utf8), [0, 1], [0, 0, 0, 0]], seeds: { [] }, runtimeSeeds: backupSeeds236 ) { input in237 attempt("raw:") { () throws -> BackupHeader in try BackupFile.inspect(input) }238 guard let fixed = withFixedChecksum(input), let parsed = attempt("fixed:", { () throws -> BackupFile.Parsed in try BackupFile.parse(fixed) }) else { return }239 fuzzCheck(parsed.header.isSigned == !parsed.signature.isEmpty, "signer and signature presence disagree")240 guard isCheap(parsed.header.kdf) else { return }241 do {242 let contents = try BackupFile.open(fixed, password: fuzzPassword, verifier: IdentityDetachedVerifier())243 FuzzOutcome.note("opened")244 fuzzCheck(contents.records.count == parsed.header.recordCount, "record count differs from the authenticated header")245 fuzzCheck(contents.signatureVerified == parsed.header.isSigned, "signature state")246 } catch {247 FuzzOutcome.note(String(describing: error))248 }249 attempt("nosig:") { () throws -> BackupContents in try BackupFile.open(fixed, password: fuzzPassword) }250 attempt("req:") { () throws -> BackupContents in try BackupFile.open(fixed, password: fuzzPassword, verifier: IdentityDetachedVerifier(), requireSignature: true) }251 },252253 FuzzTarget(254 "backup-authenticated", "Backup that decrypts under the password but carries hostile records: opening, then restoration into a new vault",255 maxLength: 2048,256 seeds: {257 [258 hostileBackupSeed([(6, 1_800_000_000, 1_800_000_100, "ha1", Bytes("first".utf8)), (5, 1_700_000_000, 1_700_000_000, "ha2", fixtureBytes("hp", 40))]),259 hostileBackupSeed([(1, 1, 2, "ha3", Bytes("abandon abandon".utf8))]), hostileBackupSeed([]),260 hostileBackupSeed([(6, 1_800_000_000, 1_800_000_000, "ha4", [1, 2, 3])], mode: 2),261 [3] + Endian.be64(5) + Endian.be32(1) + fixtureBytes("ha5", 16) + [6] + Endian.be64(7) + Endian.be64(8) + Endian.be32(2) + [9, 9] + Bytes(repeating: 0, count: 32),262 ]263 }264 ) { input in265 var f = FuzzInput(input)266 let mode = f.byte()267 let headerTime = f.take(8).reduce(UInt64(0)) { $0 << 8 | UInt64($1) }268 var plaintext = ByteWriter()269 var count: UInt32 = 0270 var expected = [(id: Bytes, payload: Bytes)]()271 if mode & 1 == 1 {272 plaintext.raw(f.rest()) // raw: the record parser sees arbitrary authenticated bytes273 } else {274 var bodies = Bytes()275 while f.remaining > 0, count < 6 {276 let type = f.byte()277 let created = f.take(8), updated = f.take(8), id = f.take(16), payload = f.field()278 var body = ByteWriter()279 body.raw(id)280 body.u8(type)281 body.raw(created)282 body.raw(updated)283 body.prefixed32(payload)284 bodies += body.bytes + SystemCrypto.sha256(body.bytes)285 expected.append((id, payload))286 count += 1287 }288 plaintext.u32(mode & 2 == 2 ? count &+ 1 : count)289 plaintext.raw(bodies)290 }291 let declared = mode & 4 == 4 ? count &+ UInt32(mode >> 3) : count292 guard let file = hostileBackup(createdAt: headerTime, declaredCount: mode & 1 == 1 ? UInt32(mode >> 1) : declared, plaintext: plaintext.bytes) else { return }293 guard let contents = attempt({ () throws -> BackupContents in try BackupFile.open(file, password: fuzzPassword) }) else { return }294 if mode & 1 == 0 {295 fuzzCheck(contents.records.count == expected.count, "opened record count differs from what was sealed")296 for (r, e) in zip(contents.records, expected) { fuzzCheck(r.id.bytes16 == e.id && r.payload == e.payload, "opened record differs from what was sealed") }297 }298 // restoration into a new vault, as on a new device299 guard let store = FuzzVaultDirectory.shared.store else { return }300 try? store.remove("restore.qyv")301 try? store.removePrevious("restore.qyv")302 let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(fileName: "restore.qyv", kdf: .insecureForTesting))303 let opened = contents.records304 fuzzAwait {305 do {306 try await vault.create(password: fuzzPassword)307 fuzzUse(try await BackupFile.restore(file, password: fuzzPassword, into: vault))308 FuzzOutcome.note("restored")309 let restored = try await vault.records()310 fuzzCheck(restored.count == opened.count, "restored record count differs from the backup")311 for r in opened {312 guard let twin = restored.first(where: { $0.id == r.id }) else { fuzzFail("a record of the backup is missing after restoration") }313 fuzzCheck(twin.payload == r.payload && twin.type == r.type, "restored record differs from the backup")314 }315 fuzzUse(try await vault.verifyIntegrity())316 } catch {317 FuzzOutcome.note("restore:" + String(describing: error))318 }319 }320 },321322 FuzzTarget(323 "identity-public", "PublicIdentity binary and text decoding, canonical re-encoding", maxLength: 6000, tokens: [Bytes("QYID".utf8), Bytes("qyvora-id:".utf8)],324 seeds: { [] }, runtimeSeeds: { [processIdentity.publicIdentity.encoded(), Bytes(processIdentity.publicIdentity.text.utf8)] }325 ) { input in326 if let p = attempt("bin:", { () throws -> PublicIdentity in try PublicIdentity(encoded: input) }) {327 fuzzCheck(p.encoded() == input, "public identity re-encodes differently")328 fuzzCheck(p.fingerprint.count == 32, "fingerprint length")329 fuzzUse(p.fingerprintText)330 guard let fromText = try? PublicIdentity(text: p.text) else { fuzzFail("text form of a public identity does not parse") }331 fuzzCheck(fromText == p, "public identity text round trip")332 }333 attempt("text:") { () throws -> PublicIdentity in try PublicIdentity(text: fuzzString(input)) }334 },335336 FuzzTarget(337 "identity-signature", "IdentitySignature decoding and verification; only this process's own signatures may verify", maxLength: 56_000, acceptOnlySeeds: true,338 seeds: { [] },339 runtimeSeeds: {340 let message = Bytes("fuzz message".utf8)341 var out = [Bytes]()342 if let s = try? processIdentity.sign(message, purpose: .message, dual: false) { out.append(s.encoded()) }343 if let s = try? processIdentity.sign(message, purpose: .message, dual: true) { out.append(s.encoded()) }344 return out345 }346 ) { input in347 guard let signature = attempt({ () throws -> IdentitySignature in try IdentitySignature(encoded: input) }) else { return }348 fuzzCheck(signature.encoded() == input, "identity signature re-encodes differently")349 if signature.verify(message: Bytes("fuzz message".utf8), signer: processIdentity.publicIdentity, purpose: .message) { FuzzOutcome.accept() }350 fuzzCheck(!signature.verify(message: Bytes("another message".utf8), signer: processIdentity.publicIdentity, purpose: .message), "signature verifies for another message")351 fuzzCheck(!signature.verify(message: Bytes("fuzz message".utf8), signer: processPeer.publicIdentity, purpose: .message), "signature verifies for another signer")352 fuzzUse(signature.verify(message: [], signer: processIdentity.publicIdentity, purpose: .message, requireDual: true))353 },354355 FuzzTarget(356 "identity-rotation", "RotationCertificate and RotationChain decoding and verification", maxLength: 120_000, seeds: { [] },357 runtimeSeeds: {358 var out = [Bytes]()359 if let r = try? processIdentity.rotate(dual: false) {360 out.append([0] + r.certificate.encoded())361 out.append([1] + RotationChain([r.certificate]).encoded())362 }363 out.append([1] + RotationChain([]).encoded())364 return out365 }366 ) { input in367 guard let selector = input.first else { return }368 let body = Bytes(input.dropFirst())369 if selector & 1 == 0 {370 guard let c = attempt("cert:", { () throws -> RotationCertificate in try RotationCertificate(encoded: body) }) else { return }371 fuzzCheck(c.encoded() == body, "rotation certificate re-encodes differently")372 if c.verify() { FuzzOutcome.note("valid") }373 fuzzUse(c.verify(requireDual: true))374 } else {375 guard let chain = attempt("chain:", { () throws -> RotationChain in try RotationChain(encoded: body) }) else { return }376 fuzzCheck(chain.encoded() == body, "rotation chain re-encodes differently")377 attempt("walk:") { () throws -> PublicIdentity in try chain.verify(from: processIdentity.publicIdentity) }378 attempt("walk2:") { () throws -> PublicIdentity in try chain.verify(from: processPeer.publicIdentity, requireDual: true) }379 }380 },381382 FuzzTarget(383 "hybrid-envelope", "HybridEnvelope / transfer package decoding, signature check and opening by the recipient", maxLength: 24_000, acceptOnlySeeds: true,384 seeds: { [] },385 runtimeSeeds: {386 var out = [Bytes]()387 if let e = try? HybridEnvelope.seal(Bytes("transfer payload".utf8), contentType: TransferPackage.contentType, to: processIdentity.publicIdentity, from: processPeer) {388 out.append(e.encoded())389 }390 if let e = try? HybridEnvelope.seal([], contentType: "qyvora/test-v1", to: processIdentity.publicIdentity, from: processIdentity) { out.append(e.encoded()) }391 return out392 }393 ) { input in394 guard let envelope = attempt({ () throws -> HybridEnvelope in try HybridEnvelope(encoded: input) }) else { return }395 fuzzCheck(envelope.encoded() == input, "envelope re-encodes differently")396 let signed = envelope.verifySignature()397 fuzzUse(envelope.verifySignature(requireDual: true))398 if let payload = attempt("open:", { () throws -> Bytes in try envelope.open(with: processIdentity) }) {399 fuzzCheck(signed, "envelope opened although its signature does not verify")400 FuzzOutcome.accept()401 fuzzUse(payload.count)402 }403 attempt("wrong:") { () throws -> Bytes in try envelope.open(with: processPeer, expectedSender: processIdentity.publicIdentity) }404 attempt("transfer:") { () throws -> Int in try TransferPackage.open(input, receiver: processIdentity).backup.count }405 },406407 FuzzTarget(408 "identity-private", "Private identity encoding parser (vault record content)", maxLength: 16_000, tokens: [Bytes("QYIK".utf8)], seeds: { [] },409 runtimeSeeds: { [processIdentity.privateEncoding()] }410 ) { input in411 guard let identity = attempt({ () throws -> Identity in try Identity(privateEncoding: input) }) else { return }412 fuzzCheck(identity.privateEncoding() == input, "private identity re-encodes differently")413 // an accepted private identity signs for its own public half414 // signing is hedged (fresh randomness each time): a damaged key fails for some signatures only, so several are made415 var consistent = true416 for round in UInt8(0)..<16 {417 guard let s = try? identity.sign([1, 2, 3, round]) else { fuzzFail("accepted private identity cannot sign") }418 if !s.verify(message: [1, 2, 3, round], signer: identity.publicIdentity, purpose: .message) {419 consistent = false420 break421 }422 }423 if !consistent {424 // say which part of the encoding differs from this process's own identity425 let reference = processIdentity.privateEncoding()426 var location = "unknown"427 if reference.count == input.count, let offset = zip(reference, input).enumerated().first(where: { $0.element.0 != $0.element.1 })?.offset {428 let start = 4 + 1 + 4 + processIdentity.publicIdentity.encoded().count + 2 // first byte of the ML-DSA-87 private key429 let regions: [(String, Int)] = [("rho", 32), ("K", 32), ("tr", 64), ("s1", 672), ("s2", 768), ("t0", 3328)]430 location = "offset \(offset)"431 var at = start432 for (name, size) in regions {433 if offset >= at && offset < at + size { location += " (ML-DSA private key, component \(name))" }434 at += size435 }436 }437 // QYV-FUZ-001 (fixed): the parser recomputes the ML-DSA public key from the private key and checks t0 and tr,438 // so an accepted identity always signs validly. The invariant is enforced on every run.439 fuzzFail("accepted private identity signs invalidly; first difference at \(location)")440 }441 },442443 FuzzTarget(444 "qr-frames", "QR frame assembler: frames separated by line feeds, any order, duplicates, conflicting sets", maxLength: 4096, text: true,445 dictionary: ["qyv1:", "1/1:", "1/2:", "2/2:", "9999/9999:", "0/1:", "\n", ":", "/", "0000000000000000"],446 seeds: {447 var out = [Bytes]()448 for (label, size, chunk) in [("qr1", 40, 600), ("qr2", 100, 32), ("qr3", 300, 100)] {449 if let frames = try? QRChunker.split(fixtureBytes(label, size), chunkSize: chunk) {450 out.append(Bytes(frames.joined(separator: "\n").utf8))451 out.append(Bytes(frames.reversed().joined(separator: "\n").utf8))452 }453 }454 return out455 }456 ) { input in457 let frames = fuzzString(input).split(separator: "\n", omittingEmptySubsequences: false).map(String.init)458 var assembler = QRAssembler()459 for frame in frames {460 do {461 fuzzUse(try assembler.add(frame))462 } catch {463 FuzzOutcome.note(String(describing: error))464 }465 fuzzCheck(assembler.receivedCount <= (assembler.total ?? 0), "more frames than the announced total")466 }467 fuzzCheck(assembler.missingIndices.count == (assembler.total ?? 0) - assembler.receivedCount, "missing-frame accounting")468 do {469 let payload = try assembler.assemble()470 FuzzOutcome.note("assembled")471 fuzzCheck(assembler.isComplete && !payload.isEmpty, "assembled an incomplete or empty payload")472 } catch {473 FuzzOutcome.note(String(describing: error))474 }475 fuzzUse(try? QRAssembler.assemble(frames))476 },477]478