Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Sources/FuzzTargets/Targets+Encoding.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 QyvoraCore44import QyvoraMath45import QyvoraStorage4647// Text and binary encodings: Hex, Base58(Check), Bech32/Bech32m, SegWit addresses, Base64URL,48// UInt256 and unit parsing, BIP-39, BIP-32 extended keys, the binary reader of the storage layer.4950let abandon = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"5152func bip32Seeds() -> [Bytes] {53 var out = [Bytes]()54 if let master = try? ExtendedKey.master(seed: fixtureBytes("bip32", 32)) {55 for v in ExtendedKey.Version.allCases {56 if let s = try? master.serialized(v) { out.append(Bytes(s.utf8)) }57 }58 if let child = try? master.derive(StandardPaths.bip84Account(.testnet)), let s = try? child.serialized(.vpub) {59 out.append(Bytes(s.utf8))60 }61 }62 return out63}6465let encodingTargets: [FuzzTarget] = [66 FuzzTarget(67 "hex", "Hex.decode + re-encode", maxLength: 512, text: true,68 seeds: { [Bytes("00ff10".utf8), Bytes("DEADbeef".utf8), Bytes("0".utf8)] }69 ) { input in70 let s = fuzzString(input)71 if let b = Hex.decode(s) {72 FuzzOutcome.note("ok")73 fuzzCheck(Hex.encode(b) == s.lowercased(), "hex round trip")74 } else {75 FuzzOutcome.note("nil")76 }77 },7879 FuzzTarget(80 "base58check", "Base58 and Base58Check decode, round trip", maxLength: 256, text: true,81 seeds: {82 [83 Bytes(Base58Check.encode(fixtureBytes("b58", 21)).utf8), Bytes(Base58.bitcoin.encode([0, 0, 1, 2, 3]).utf8),84 Bytes("1111111111111111111114oLvT2".utf8), Bytes("3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy".utf8),85 ]86 }87 ) { input in88 let s = fuzzString(input)89 if let raw = Base58.bitcoin.decode(s) {90 FuzzOutcome.note("raw-ok")91 fuzzCheck(Base58.bitcoin.encode(raw) == s, "base58 round trip")92 }93 if let payload = Base58Check.decode(s) {94 FuzzOutcome.note("check-ok")95 fuzzCheck(Base58Check.encode(payload) == s, "base58check round trip")96 }97 },9899 FuzzTarget(100 "bech32", "Bech32/Bech32m decode and SegWit address decode for every HRP", maxLength: 128, text: true,101 dictionary: ["bc1", "tb1", "bcrt1", "1q", "1p", "qqqqqq"],102 seeds: {103 var out = [Bytes]()104 for hrp in ["bc", "tb", "bcrt"] {105 if let a = SegWitAddress.encode(hrp: hrp, version: 0, program: fixtureBytes("wpkh", 20)) { out.append(Bytes(a.utf8)) }106 if let a = SegWitAddress.encode(hrp: hrp, version: 0, program: fixtureBytes("wsh", 32)) { out.append(Bytes(a.utf8)) }107 if let a = SegWitAddress.encode(hrp: hrp, version: 1, program: fixtureBytes("tr", 32)) { out.append(Bytes(a.utf8)) }108 }109 out.append(Bytes("A12UEL5L".utf8))110 out.append(Bytes("abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx".utf8))111 return out112 }113 ) { input in114 let s = fuzzString(input)115 for variant in [Bech32.Variant.bech32, .bech32m] {116 if let d = Bech32.decode(s, variant: variant) {117 FuzzOutcome.note("decoded")118 // re-encoding gives the same string up to case119 if let again = Bech32.encode(hrp: d.hrp, words: d.words, variant: variant) {120 fuzzCheck(again.lowercased() == s.lowercased(), "bech32 round trip")121 }122 fuzzUse(Bech32.fromWords(d.words))123 }124 }125 for hrp in ["bc", "tb", "bcrt"] {126 if let d = SegWitAddress.decode(s, hrp: hrp) {127 FuzzOutcome.note("segwit")128 guard let again = SegWitAddress.encode(hrp: hrp, version: d.version, program: d.program) else {129 fuzzFail("decoded SegWit address does not re-encode")130 }131 fuzzCheck(again == s.lowercased(), "segwit round trip")132 }133 }134 },135136 FuzzTarget(137 "base64url", "Base64URL decode + re-encode", maxLength: 512, text: true,138 seeds: { [Bytes(Base64URL.encode(fixtureBytes("b64", 33)).utf8), Bytes("AA".utf8), Bytes("-_-_".utf8)] }139 ) { input in140 let s = fuzzString(input)141 if let b = Base64URL.decode(s) {142 FuzzOutcome.note("ok")143 fuzzCheck(Base64URL.decode(Base64URL.encode(b)) == b, "base64url round trip")144 }145 },146147 FuzzTarget(148 "uint256", "UInt256 decimal/hex parsing, formatting, unit parsing and checked arithmetic", maxLength: 200, text: true,149 dictionary: ["0x", ".", "115792089237316195423570985008687907853269984665640564039457584007913129639935", "ffffffffffffffff"],150 seeds: {151 [152 Bytes("0|0".utf8), Bytes("0xff|18".utf8), Bytes("1.000000000000000001|18".utf8),153 Bytes("115792089237316195423570985008687907853269984665640564039457584007913129639935|8".utf8),154 Bytes("0x00000001|6".utf8), Bytes("21000000.00000001|8".utf8),155 ]156 }157 ) { input in158 let parts = fuzzString(input).split(separator: "|", maxSplits: 1, omittingEmptySubsequences: false)159 let text = String(parts.first ?? "")160 let decimals = parts.count > 1 ? (Int(parts[1]) ?? 18) : 18161 if let d = UInt256(decimal: text) {162 FuzzOutcome.note("dec")163 fuzzCheck(UInt256(decimal: d.description) == d, "decimal round trip")164 fuzzCheck(UInt256(hex: d.hexQuantity) == d, "hex quantity round trip")165 fuzzCheck(UInt256(bigEndian: d.bytes32) == d, "bytes32 round trip")166 fuzzCheck(UInt256(bigEndian: d.minimalBytes) == d || d.isZero, "minimal bytes round trip")167 let (sum, o1) = d.addingReportingOverflow(d)168 let (diff, o2) = sum.subtractingReportingOverflow(d)169 if !o1 { fuzzCheck(!o2 && diff == d, "add/sub inverse") }170 let (prod, o3) = d.multipliedReportingOverflow(by: 3)171 if !o3 {172 let (q, r) = prod.quotientAndRemainder(dividingBy: 3)173 fuzzCheck(q == d && r == 0, "mul/div inverse")174 }175 fuzzUse(d.multipliedReportingOverflow(by: d))176 fuzzUse(d.uint64)177 }178 if let h = UInt256(hex: text) {179 FuzzOutcome.note("hex")180 fuzzCheck(UInt256(hex: h.hexQuantity) == h, "hex round trip")181 }182 if (0...80).contains(decimals), let v = BaseUnits.parse(text, decimals: decimals) {183 FuzzOutcome.note("units")184 let shown = BaseUnits.format(v, decimals: decimals)185 fuzzCheck(BaseUnits.parse(shown, decimals: decimals) == v, "unit format/parse round trip")186 fuzzUse(BaseUnits.format(v, decimals: decimals, maxFractionDigits: 4))187 }188 fuzzUse(BaseUnits.parse(text, decimals: decimals))189 },190191 FuzzTarget(192 "bip39", "BIP-39 words to entropy, validity, normalisation", maxLength: 400, text: true,193 dictionary: ["abandon", "about", "zoo", "wrong", "legal", "winner", "thank", "year", "wave", "sausage", "worth", "useful", " "],194 seeds: {195 [196 Bytes(abandon.utf8), Bytes("legal winner thank year wave sausage worth useful legal winner thank yellow".utf8),197 Bytes("zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote".utf8),198 ]199 }200 ) { input in201 let words = BIP39.words(from: fuzzString(input))202 do {203 let entropy = try BIP39.entropy(mnemonic: words)204 FuzzOutcome.note("ok")205 fuzzCheck(BIP39.isValid(words), "isValid disagrees with entropy()")206 guard let again = try? BIP39.mnemonic(entropy: entropy) else { fuzzFail("entropy does not re-encode") }207 fuzzCheck(again == words, "mnemonic round trip")208 } catch {209 FuzzOutcome.note(error: error)210 fuzzCheck(!BIP39.isValid(words), "isValid accepts what entropy() rejects")211 }212 },213214 FuzzTarget(215 "extended-key", "ExtendedKey.parse (xpub/xprv and SLIP-132 variants), re-serialisation, one derivation",216 maxLength: 160, text: true, dictionary: ["xpub", "xprv", "tpub", "tprv", "zpub", "vpub"], seeds: bip32Seeds217 ) { input in218 let s = fuzzString(input)219 do {220 let (key, version) = try ExtendedKey.parse(s)221 FuzzOutcome.note("ok")222 guard let again = try? key.serialized(version) else { fuzzFail("parsed extended key does not serialise") }223 fuzzCheck(again == s, "extended key round trip")224 fuzzUse(try? key.derive(.normal(0)))225 fuzzUse(try? key.derive(.hardened(0)))226 } catch {227 FuzzOutcome.note(error: error)228 }229 },230231 FuzzTarget(232 "byte-reader", "Storage ByteReader driven by an opcode stream", maxLength: 512,233 seeds: { [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], Bytes(repeating: 0xff, count: 40), [5, 0, 3, 1, 2, 3, 6, 0, 0, 0, 1, 9]] }234 ) { input in235 guard input.count >= 2 else { return }236 let split = 1 + Int(input[0]) % (input.count - 1)237 let program = Bytes(input[1..<split])238 var r = ByteReader(Bytes(input[split...]))239 do {240 for op in program {241 switch op % 9 {242 case 0: fuzzUse(try r.u8())243 case 1: fuzzUse(try r.u16())244 case 2: fuzzUse(try r.u32())245 case 3: fuzzUse(try r.u64())246 case 4: fuzzUse(try r.prefixed8())247 case 5: fuzzUse(try r.prefixed16(max: Int(op)))248 case 6: fuzzUse(try r.prefixed32(max: Int(op) * 4))249 case 7: fuzzUse(try r.raw(Int(op)))250 default: fuzzUse(try r.raw(r.remaining))251 }252 fuzzCheck(r.remaining >= 0, "reader ran past the end")253 }254 try r.finish()255 FuzzOutcome.note("ok")256 } catch {257 FuzzOutcome.note(error: error)258 }259 },260]261