SPB Git

Repository Public

Base58.swift 4.8 KB 110 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraCore/Encoding/Base58.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): Base58 and Base58Check.42import Foundation43import QyvoraSymmetric4445public struct Base58: Sendable {46    /** Bitcoin alphabet. */47    public static let bitcoin = Base58(alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")4849    private let letters: [UInt8]50    private let values: [Int8] // ASCII code -> digit, −1 when the character is not in the alphabet5152    private init(alphabet: String) {53        letters = [UInt8](alphabet.utf8)54        precondition(letters.count == 58)55        var table = [Int8](repeating: -1, count: 128)56        for (digit, code) in letters.enumerated() { table[Int(code)] = Int8(digit) }57        values = table58    }5960    /** True when `code` is one of the 58 characters. */61    static func isBase58(_ code: UInt8) -> Bool { code < 128 && Base58.bitcoin.values[Int(code)] >= 0 }6263    public func encode(_ bytes: [UInt8]) -> String {64        let zeros = bytes.prefix { $0 == 0 }.count65        var digits = [UInt8]() // little-endian base-58 digits66        for byte in bytes.dropFirst(zeros) {67            var carry = Int(byte)68            for k in digits.indices { carry += Int(digits[k]) << 8; digits[k] = UInt8(carry % 58); carry /= 58 }69            while carry > 0 { digits.append(UInt8(carry % 58)); carry /= 58 }70        }71        var out = [UInt8](repeating: letters[0], count: zeros)72        for d in digits.reversed() { out.append(letters[Int(d)]) }73        return String(decoding: out, as: UTF8.self)74    }7576    /** nil when a character is outside the alphabet (white space, "0", "O", "I", "l", non-ASCII…). The empty string is no bytes. */77    public func decode(_ text: String) -> [UInt8]? { decode(ascii: [UInt8](text.utf8)) }7879    func decode(ascii: [UInt8]) -> [UInt8]? {80        var zeros = 0, leading = true81        var bytes = [UInt8]() // little-endian base-25682        for c in ascii {83            guard c < 128, values[Int(c)] >= 0 else { return nil }84            let digit = Int(values[Int(c)])85            if leading && digit == 0 { zeros += 1; continue }86            leading = false87            var carry = digit88            for k in bytes.indices { carry += Int(bytes[k]) * 58; bytes[k] = UInt8(carry & 0xff); carry >>= 8 }89            while carry > 0 { bytes.append(UInt8(carry & 0xff)); carry >>= 8 }90        }91        return [UInt8](repeating: 0, count: zeros) + bytes.reversed()92    }93}9495public enum Base58Check {96    public static func encode(_ payload: [UInt8], alphabet: Base58 = .bitcoin) -> String {97        alphabet.encode(payload + SHA256.double(payload).prefix(4))98    }99100    /** The payload without its four checksum bytes; nil on a bad character, fewer than four bytes or a wrong checksum. */101    public static func decode(_ text: String, alphabet: Base58 = .bitcoin) -> [UInt8]? { decode(ascii: [UInt8](text.utf8), alphabet: alphabet) }102103    static func decode(ascii: [UInt8], alphabet: Base58 = .bitcoin) -> [UInt8]? {104        guard let raw = alphabet.decode(ascii: ascii), raw.count >= 4 else { return nil }105        let payload = [UInt8](raw.dropLast(4))106        guard [UInt8](SHA256.double(payload).prefix(4)) == [UInt8](raw.suffix(4)) else { return nil }107        return payload108    }109}110
Files main
Menu

Theme