Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraCore/Encoding/Bech32.swift8// Module : Qyvora Core9// 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// =============================================================================4041// Adapted from SP Wallet Core (same author): Bech32 / Bech32m and native SegWit addresses (BIP-173, BIP-350).42import Foundation4344public enum Bech32 {45 public enum Variant: Sendable, Equatable {46 case bech32, bech32m47 var constant: UInt32 { self == .bech32 ? 1 : 0x2bc8_30a3 }48 }4950 public struct Decoded: Sendable, Equatable {51 /** Human-readable part, lower case. */52 public let hrp: String53 /** 5-bit data words without the six checksum words. */54 public let words: [UInt8]55 }5657 static let charset = [UInt8]("qpzry9x8gf2tvdw0s3jn54khce6mua7l".utf8)58 private static let charsetValues: [Int8] = {59 var table = [Int8](repeating: -1, count: 128)60 for (value, code) in charset.enumerated() { table[Int(code)] = Int8(value) }61 return table62 }()63 /** Value of a lower-case data character, nil when it is not in the bech32 character set. */64 static func value(of code: UInt8) -> UInt8? { code < 128 && charsetValues[Int(code)] >= 0 ? UInt8(charsetValues[Int(code)]) : nil }6566 private static func polymodStep(_ pre: UInt32) -> UInt32 {67 let generators: [UInt32] = [0x3b6a_57b2, 0x2650_8e6d, 0x1ea1_19fa, 0x3d42_33dd, 0x2a14_62b3]68 let top = pre >> 2569 var chk = (pre & 0x1ff_ffff) << 570 for i in 0..<5 where (top >> UInt32(i)) & 1 == 1 { chk ^= generators[i] }71 return chk72 }7374 private static func checksum(hrp: [UInt8], words: [UInt8], variant: Variant) -> [UInt8] {75 var chk: UInt32 = 176 for c in hrp { chk = polymodStep(chk) ^ UInt32(c >> 5) }77 chk = polymodStep(chk)78 for c in hrp { chk = polymodStep(chk) ^ UInt32(c & 0x1f) }79 for w in words { chk = polymodStep(chk) ^ UInt32(w) }80 for _ in 0..<6 { chk = polymodStep(chk) }81 chk ^= variant.constant82 return (0..<6).map { UInt8((chk >> UInt32(5 * (5 - $0))) & 31) }83 }8485 /**86 Decode and verify the checksum. nil when: shorter than 8 or longer than `limit` characters, mixed case, no separator,87 an empty or non-printable human-readable part, fewer than six data characters, a character outside the set, a bad checksum.88 An all-upper-case string is accepted (QR codes) and reported in lower case.89 */90 public static func decode(_ text: String, variant: Variant, limit: Int = 90) -> Decoded? {91 guard text.unicodeScalars.allSatisfy({ $0.isASCII }) else { return nil }92 return decode(ascii: [UInt8](text.utf8), variant: variant, limit: limit)93 }9495 static func decode(ascii: [UInt8], variant: Variant, limit: Int = 90) -> Decoded? {96 guard ascii.count >= 8, ascii.count <= limit, ascii.allSatisfy({ $0 >= 33 && $0 <= 126 }) else { return nil }97 let hasUpper = ascii.contains { $0 >= 65 && $0 <= 90 }, hasLower = ascii.contains { $0 >= 97 && $0 <= 122 }98 guard !(hasUpper && hasLower) else { return nil }99 let lower = ascii.map { $0 >= 65 && $0 <= 90 ? $0 + 32 : $0 }100 guard let sep = lower.lastIndex(of: 0x31), sep > 0 else { return nil }101 let hrp = [UInt8](lower[..<sep]), data = lower[(sep + 1)...]102 guard data.count >= 6 else { return nil }103 var values = [UInt8](); values.reserveCapacity(data.count)104 for c in data { guard let v = value(of: c) else { return nil }; values.append(v) }105 let words = [UInt8](values.dropLast(6))106 guard checksum(hrp: hrp, words: words, variant: variant) == [UInt8](values.suffix(6)) else { return nil }107 return Decoded(hrp: String(decoding: hrp, as: UTF8.self), words: words)108 }109110 /** nil when the human-readable part is empty or not printable ASCII, a word is ≥ 32, or the result exceeds `limit`. */111 public static func encode(hrp: String, words: [UInt8], variant: Variant, limit: Int = 90) -> String? {112 let prefix = [UInt8](hrp.utf8).map { $0 >= 65 && $0 <= 90 ? $0 + 32 : $0 }113 guard !prefix.isEmpty, hrp.unicodeScalars.allSatisfy({ $0.isASCII }), prefix.allSatisfy({ $0 >= 33 && $0 <= 126 }),114 words.allSatisfy({ $0 < 32 }), prefix.count + 7 + words.count <= limit else { return nil }115 let all = words + checksum(hrp: prefix, words: words, variant: variant)116 return String(decoding: prefix + [0x31] + all.map { charset[Int($0)] }, as: UTF8.self)117 }118119 /** 8-bit bytes → 5-bit words, the last word padded with zero bits. */120 public static func toWords(_ bytes: [UInt8]) -> [UInt8] {121 var out = [UInt8](), acc: UInt32 = 0, bits = 0122 for b in bytes {123 acc = (acc << 8) | UInt32(b); bits += 8124 while bits >= 5 { bits -= 5; out.append(UInt8((acc >> UInt32(bits)) & 31)) }125 acc &= (1 << UInt32(bits)) - 1126 }127 if bits > 0 { out.append(UInt8((acc << UInt32(5 - bits)) & 31)) }128 return out129 }130131 /** 5-bit words → bytes, strict: nil when a whole word is left over or when the padding bits are not zero. */132 public static func fromWords(_ words: some Sequence<UInt8>) -> [UInt8]? {133 var out = [UInt8](), acc: UInt32 = 0, bits = 0134 for w in words {135 guard w < 32 else { return nil }136 acc = (acc << 5) | UInt32(w); bits += 5137 if bits >= 8 { bits -= 8; out.append(UInt8((acc >> UInt32(bits)) & 0xff)) }138 acc &= (1 << UInt32(bits)) - 1139 }140 guard bits < 5, acc == 0 else { return nil }141 return out142 }143}144145/** Native SegWit addresses (BIP-173, BIP-350). */146public enum SegWitAddress {147 public struct Decoded: Sendable, Equatable {148 public let hrp: String149 /** Witness version 0…16. */150 public let version: UInt8151 /** Witness program, 2…40 bytes (20 or 32 for version 0). */152 public let program: [UInt8]153 }154155 /**156 Decode a SegWit address for the expected human-readable part ("bc", "ltc"…). Version 0 must use Bech32 and versions 1–16157 Bech32m; the program is 2–40 bytes, exactly 20 or 32 for version 0. nil on anything else.158 */159 public static func decode(_ text: String, hrp: String) -> Decoded? {160 guard text.unicodeScalars.allSatisfy({ $0.isASCII }) else { return nil }161 return decode(ascii: [UInt8](text.utf8), hrp: hrp)162 }163164 static func decode(ascii: [UInt8], hrp: String) -> Decoded? {165 let decoded: Bech32.Decoded166 if let d = Bech32.decode(ascii: ascii, variant: .bech32), d.words.first == 0 { decoded = d }167 else if let d = Bech32.decode(ascii: ascii, variant: .bech32m), let v = d.words.first, v != 0 { decoded = d }168 else { return nil }169 guard decoded.hrp == hrp, let version = decoded.words.first, version <= 16,170 let program = Bech32.fromWords(decoded.words.dropFirst()), (2...40).contains(program.count),171 version != 0 || program.count == 20 || program.count == 32 else { return nil }172 return Decoded(hrp: decoded.hrp, version: version, program: program)173 }174175 /** nil when the version / program pair is not a valid witness program. */176 public static func encode(hrp: String, version: UInt8, program: [UInt8]) -> String? {177 guard version <= 16, (2...40).contains(program.count), version != 0 || program.count == 20 || program.count == 32 else { return nil }178 return Bech32.encode(hrp: hrp, words: [version] + Bech32.toWords(program), variant: version == 0 ? .bech32 : .bech32m)179 }180}181