SPB Git

Repository Public

CashAddr.swift 7.0 KB 128 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraCore/Encoding/CashAddr.swift8// Module           : Qyvora Core9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//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): CashAddr, the address format of Bitcoin Cash.42// Specification: https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/cashaddr.md43import Foundation4445/// CashAddr: `prefix:payload`, where the payload is a version byte (type and hash size), a hash and a 40-bit BCH46/// checksum that also covers the prefix, written with the Bech32 character set.47public enum CashAddr {48    public struct Decoded: Sendable, Equatable {49        /// Lower case, without the colon.50        public let prefix: String51        /// 0 = P2PKH, 1 = P2SH; 2 and 3 are the token-aware forms (CashTokens).52        public let type: UInt853        /// 20, 24, 28, 32, 40, 48, 56 or 64 bytes.54        public let hash: [UInt8]55    }5657    /// Address type bits of the version byte.58    public static let typeP2PKH: UInt8 = 059    public static let typeP2SH: UInt8 = 16061    private static let hashSizes = [20, 24, 28, 32, 40, 48, 56, 64]62    private static let generators: [UInt64] = [0x98_f2bc_8e61, 0x79_b76d_99e2, 0xf3_3e5f_b3c4, 0xae_2eab_e2a8, 0x1e_4f43_e470]6364    private static func polymod(_ values: [UInt8]) -> UInt64 {65        var c: UInt64 = 166        for d in values {67            let c0 = c >> 3568            c = ((c & 0x07_ffff_ffff) << 5) ^ UInt64(d)69            for k in 0..<5 where (c0 >> UInt64(k)) & 1 == 1 { c ^= generators[k] }70        }71        return c ^ 172    }7374    private static func prefixValues(_ prefix: [UInt8]) -> [UInt8] { prefix.map { $0 & 0x1f } + [0] }75    private static func isLowerAlpha(_ prefix: [UInt8]) -> Bool { !prefix.isEmpty && prefix.count <= 40 && prefix.allSatisfy { $0 >= 97 && $0 <= 122 } }7677    /// "prefix:payload" in lower case; nil when the prefix is not lower-case letters, the type is above 15 or the hash78    /// size is not one of the eight CashAddr sizes.79    public static func encode(prefix: String, type: UInt8, hash: [UInt8]) -> String? {80        let p = [UInt8](prefix.utf8)81        guard let size = hashSizes.firstIndex(of: hash.count), type <= 15, isLowerAlpha(p) else { return nil }82        let payload = Bech32.toWords([(type << 3) | UInt8(size)] + hash)83        let mod = polymod(prefixValues(p) + payload + [UInt8](repeating: 0, count: 8))84        let check = (0..<8).map { UInt8((mod >> UInt64(5 * (7 - $0))) & 31) }85        return String(decoding: p + [0x3a] + (payload + check).map { Bech32.charset[Int($0)] }, as: UTF8.self)86    }8788    /// Decodes and verifies the checksum. A string without "prefix:" is checked against `defaultPrefix` (the prefix is89    /// part of the checksum, so the wrong one fails). All-upper-case input is accepted (QR codes); mixed case is not.90    /// nil when: not ASCII, mixed case, more than one colon, a prefix that is not letters, a payload outside 42…11291    /// characters or with a character outside the set, a bad checksum, non-zero padding bits, the reserved version bit,92    /// or a hash whose length is not the one the version byte announces.93    public static func decode(_ text: String, defaultPrefix: String? = nil) -> Decoded? {94        guard text.utf8.count <= 160, text.unicodeScalars.allSatisfy({ $0.isASCII }) else { return nil }95        return decode(ascii: [UInt8](text.utf8), defaultPrefix: defaultPrefix)96    }9798    /// True when "prefix:payload" (single case) carries a valid checksum, whatever the payload encodes: the first99    /// check of `decode`, exposed for the checksum examples of the specification.100    static func hasValidChecksum(_ text: String) -> Bool {101        let ascii = [UInt8](text.utf8)102        let hasUpper = ascii.contains { $0 >= 65 && $0 <= 90 }, hasLower = ascii.contains { $0 >= 97 && $0 <= 122 }103        guard ascii.count <= 160, !(hasUpper && hasLower) else { return false }104        let parts = ascii.map { $0 >= 65 && $0 <= 90 ? $0 + 32 : $0 }.split(separator: 0x3a, omittingEmptySubsequences: false)105        guard parts.count == 2, isLowerAlpha([UInt8](parts[0])), parts[1].count >= 8 else { return false }106        var values = [UInt8]()107        for c in parts[1] { guard let v = Bech32.value(of: c) else { return false }; values.append(v) }108        return polymod(prefixValues([UInt8](parts[0])) + values) == 0109    }110111    static func decode(ascii: [UInt8], defaultPrefix: String?) -> Decoded? {112        let hasUpper = ascii.contains { $0 >= 65 && $0 <= 90 }, hasLower = ascii.contains { $0 >= 97 && $0 <= 122 }113        guard !(hasUpper && hasLower) else { return nil }114        let lower = ascii.map { $0 >= 65 && $0 <= 90 ? $0 + 32 : $0 }115        let parts = lower.split(separator: 0x3a, omittingEmptySubsequences: false)116        guard parts.count <= 2, let last = parts.last else { return nil }117        let prefix: [UInt8]118        if parts.count == 2 { prefix = [UInt8](parts[0]) } else if let d = defaultPrefix { prefix = [UInt8](d.utf8) } else { return nil }119        let body = [UInt8](last)120        guard isLowerAlpha(prefix), body.count >= 42, body.count <= 112 else { return nil }121        var values = [UInt8](); values.reserveCapacity(body.count)122        for c in body { guard let v = Bech32.value(of: c) else { return nil }; values.append(v) }123        guard polymod(prefixValues(prefix) + values) == 0, let bytes = Bech32.fromWords(values.dropLast(8)), let version = bytes.first,124              version & 0x80 == 0, bytes.count - 1 == hashSizes[Int(version & 7)] else { return nil }125        return Decoded(prefix: String(decoding: prefix, as: UTF8.self), type: version >> 3, hash: [UInt8](bytes.dropFirst()))126    }127}128
Files main
Menu

Theme