Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Crypto/Bech32.swift3// Description: Bech32 (BIP-173) and Bech32m (BIP-350) codecs with a configurable length limit (90 by default; Cardano uses 128),4// strict 5↔8 bit regrouping, and the SegWit address rules (witness version and program length, which checksum5// goes with which version). Same acceptance as @scure/base 2.4, which the backend validates with.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011public enum Bech32 {12 public enum Variant: Sendable, Equatable {13 case bech32, bech32m14 var constant: UInt32 { self == .bech32 ? 1 : 0x2bc8_30a3 }15 }1617 public struct Decoded: Sendable, Equatable {18 /** Human-readable part, lower case. */19 public let hrp: String20 /** 5-bit data words without the six checksum words. */21 public let words: [UInt8]22 }2324 static let charset = [UInt8]("qpzry9x8gf2tvdw0s3jn54khce6mua7l".utf8)25 private static let charsetValues: [Int8] = {26 var table = [Int8](repeating: -1, count: 128)27 for (value, code) in charset.enumerated() { table[Int(code)] = Int8(value) }28 return table29 }()30 /** Value of a lower-case data character, nil when it is not in the bech32 character set. */31 static func value(of code: UInt8) -> UInt8? { code < 128 && charsetValues[Int(code)] >= 0 ? UInt8(charsetValues[Int(code)]) : nil }3233 private static func polymodStep(_ pre: UInt32) -> UInt32 {34 let generators: [UInt32] = [0x3b6a_57b2, 0x2650_8e6d, 0x1ea1_19fa, 0x3d42_33dd, 0x2a14_62b3]35 let top = pre >> 2536 var chk = (pre & 0x1ff_ffff) << 537 for i in 0..<5 where (top >> UInt32(i)) & 1 == 1 { chk ^= generators[i] }38 return chk39 }4041 private static func checksum(hrp: [UInt8], words: [UInt8], variant: Variant) -> [UInt8] {42 var chk: UInt32 = 143 for c in hrp { chk = polymodStep(chk) ^ UInt32(c >> 5) }44 chk = polymodStep(chk)45 for c in hrp { chk = polymodStep(chk) ^ UInt32(c & 0x1f) }46 for w in words { chk = polymodStep(chk) ^ UInt32(w) }47 for _ in 0..<6 { chk = polymodStep(chk) }48 chk ^= variant.constant49 return (0..<6).map { UInt8((chk >> UInt32(5 * (5 - $0))) & 31) }50 }5152 /**53 Decode and verify the checksum. nil when: shorter than 8 or longer than `limit` characters, mixed case, no separator,54 an empty or non-printable human-readable part, fewer than six data characters, a character outside the set, a bad checksum.55 An all-upper-case string is accepted (QR codes) and reported in lower case.56 */57 public static func decode(_ text: String, variant: Variant, limit: Int = 90) -> Decoded? {58 guard text.unicodeScalars.allSatisfy({ $0.isASCII }) else { return nil }59 return decode(ascii: [UInt8](text.utf8), variant: variant, limit: limit)60 }6162 static func decode(ascii: [UInt8], variant: Variant, limit: Int = 90) -> Decoded? {63 guard ascii.count >= 8, ascii.count <= limit, ascii.allSatisfy({ $0 >= 33 && $0 <= 126 }) else { return nil }64 let hasUpper = ascii.contains { $0 >= 65 && $0 <= 90 }, hasLower = ascii.contains { $0 >= 97 && $0 <= 122 }65 guard !(hasUpper && hasLower) else { return nil }66 let lower = ascii.map { $0 >= 65 && $0 <= 90 ? $0 + 32 : $0 }67 guard let sep = lower.lastIndex(of: 0x31), sep > 0 else { return nil }68 let hrp = [UInt8](lower[..<sep]), data = lower[(sep + 1)...]69 guard data.count >= 6 else { return nil }70 var values = [UInt8](); values.reserveCapacity(data.count)71 for c in data { guard let v = value(of: c) else { return nil }; values.append(v) }72 let words = [UInt8](values.dropLast(6))73 guard checksum(hrp: hrp, words: words, variant: variant) == [UInt8](values.suffix(6)) else { return nil }74 return Decoded(hrp: String(decoding: hrp, as: UTF8.self), words: words)75 }7677 /** nil when the human-readable part is empty or not printable ASCII, a word is ≥ 32, or the result exceeds `limit`. */78 public static func encode(hrp: String, words: [UInt8], variant: Variant, limit: Int = 90) -> String? {79 let prefix = [UInt8](hrp.utf8).map { $0 >= 65 && $0 <= 90 ? $0 + 32 : $0 }80 guard !prefix.isEmpty, hrp.unicodeScalars.allSatisfy({ $0.isASCII }), prefix.allSatisfy({ $0 >= 33 && $0 <= 126 }),81 words.allSatisfy({ $0 < 32 }), prefix.count + 7 + words.count <= limit else { return nil }82 let all = words + checksum(hrp: prefix, words: words, variant: variant)83 return String(decoding: prefix + [0x31] + all.map { charset[Int($0)] }, as: UTF8.self)84 }8586 /** 8-bit bytes → 5-bit words, the last word padded with zero bits. */87 public static func toWords(_ bytes: [UInt8]) -> [UInt8] {88 var out = [UInt8](), acc: UInt32 = 0, bits = 089 for b in bytes {90 acc = (acc << 8) | UInt32(b); bits += 891 while bits >= 5 { bits -= 5; out.append(UInt8((acc >> UInt32(bits)) & 31)) }92 acc &= (1 << UInt32(bits)) - 193 }94 if bits > 0 { out.append(UInt8((acc << UInt32(5 - bits)) & 31)) }95 return out96 }9798 /** 5-bit words → bytes, strict: nil when a whole word is left over or when the padding bits are not zero. */99 public static func fromWords(_ words: some Sequence<UInt8>) -> [UInt8]? {100 var out = [UInt8](), acc: UInt32 = 0, bits = 0101 for w in words {102 guard w < 32 else { return nil }103 acc = (acc << 5) | UInt32(w); bits += 5104 if bits >= 8 { bits -= 8; out.append(UInt8((acc >> UInt32(bits)) & 0xff)) }105 acc &= (1 << UInt32(bits)) - 1106 }107 guard bits < 5, acc == 0 else { return nil }108 return out109 }110}111112/** Native SegWit addresses (BIP-173, BIP-350). */113public enum SegWitAddress {114 public struct Decoded: Sendable, Equatable {115 public let hrp: String116 /** Witness version 0…16. */117 public let version: UInt8118 /** Witness program, 2…40 bytes (20 or 32 for version 0). */119 public let program: [UInt8]120 }121122 /**123 Decode a SegWit address for the expected human-readable part ("bc", "ltc"…). Version 0 must use Bech32 and versions 1–16124 Bech32m; the program is 2–40 bytes, exactly 20 or 32 for version 0. nil on anything else.125 */126 public static func decode(_ text: String, hrp: String) -> Decoded? {127 guard text.unicodeScalars.allSatisfy({ $0.isASCII }) else { return nil }128 return decode(ascii: [UInt8](text.utf8), hrp: hrp)129 }130131 static func decode(ascii: [UInt8], hrp: String) -> Decoded? {132 let decoded: Bech32.Decoded133 if let d = Bech32.decode(ascii: ascii, variant: .bech32), d.words.first == 0 { decoded = d }134 else if let d = Bech32.decode(ascii: ascii, variant: .bech32m), let v = d.words.first, v != 0 { decoded = d }135 else { return nil }136 guard decoded.hrp == hrp, let version = decoded.words.first, version <= 16,137 let program = Bech32.fromWords(decoded.words.dropFirst()), (2...40).contains(program.count),138 version != 0 || program.count == 20 || program.count == 32 else { return nil }139 return Decoded(hrp: decoded.hrp, version: version, program: program)140 }141142 /** nil when the version / program pair is not a valid witness program. */143 public static func encode(hrp: String, version: UInt8, program: [UInt8]) -> String? {144 guard version <= 16, (2...40).contains(program.count), version != 0 || program.count == 20 || program.count == 32 else { return nil }145 return Bech32.encode(hrp: hrp, words: [version] + Bech32.toWords(program), variant: version == 0 ? .bech32 : .bech32m)146 }147}148