Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Crypto/Base58.swift3// Description: Base58 with the Bitcoin and the XRP Ledger ("Ripple") alphabets, and Base58Check (payload ‖ first four bytes of4// SHA-256(SHA-256(payload)), SHA-256 from CryptoKit). Decoding is exact: every leading zero digit is one zero byte,5// so a byte string has one encoding and `encode(decode(s)) == s` for every string that decodes.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011public struct Base58: Sendable {12 /** Bitcoin alphabet: also Litecoin, Dogecoin, legacy Bitcoin Cash, TRON, Solana, NEAR hashes, Polkadot SS58. */13 public static let bitcoin = Base58(alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")14 /** XRP Ledger alphabet (same 58 characters in another order; "r" is the zero digit). */15 public static let ripple = Base58(alphabet: "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz")1617 private let letters: [UInt8]18 private let values: [Int8] // ASCII code -> digit, −1 when the character is not in the alphabet1920 private init(alphabet: String) {21 letters = [UInt8](alphabet.utf8)22 precondition(letters.count == 58)23 var table = [Int8](repeating: -1, count: 128)24 for (digit, code) in letters.enumerated() { table[Int(code)] = Int8(digit) }25 values = table26 }2728 /** True when `code` is one of the 58 characters (both alphabets use the same set). */29 static func isBase58(_ code: UInt8) -> Bool { code < 128 && Base58.bitcoin.values[Int(code)] >= 0 }3031 public func encode(_ bytes: [UInt8]) -> String {32 let zeros = bytes.prefix { $0 == 0 }.count33 var digits = [UInt8]() // little-endian base-58 digits34 for byte in bytes.dropFirst(zeros) {35 var carry = Int(byte)36 for k in digits.indices { carry += Int(digits[k]) << 8; digits[k] = UInt8(carry % 58); carry /= 58 }37 while carry > 0 { digits.append(UInt8(carry % 58)); carry /= 58 }38 }39 var out = [UInt8](repeating: letters[0], count: zeros)40 for d in digits.reversed() { out.append(letters[Int(d)]) }41 return String(decoding: out, as: UTF8.self)42 }4344 /** nil when a character is outside the alphabet (white space, "0", "O", "I", "l", non-ASCII…). The empty string is no bytes. */45 public func decode(_ text: String) -> [UInt8]? { decode(ascii: [UInt8](text.utf8)) }4647 func decode(ascii: [UInt8]) -> [UInt8]? {48 var zeros = 0, leading = true49 var bytes = [UInt8]() // little-endian base-25650 for c in ascii {51 guard c < 128, values[Int(c)] >= 0 else { return nil }52 let digit = Int(values[Int(c)])53 if leading && digit == 0 { zeros += 1; continue }54 leading = false55 var carry = digit56 for k in bytes.indices { carry += Int(bytes[k]) * 58; bytes[k] = UInt8(carry & 0xff); carry >>= 8 }57 while carry > 0 { bytes.append(UInt8(carry & 0xff)); carry >>= 8 }58 }59 return [UInt8](repeating: 0, count: zeros) + bytes.reversed()60 }61}6263public enum Base58Check {64 public static func encode(_ payload: [UInt8], alphabet: Base58 = .bitcoin) -> String {65 alphabet.encode(payload + SHA2.doubleSHA256(payload).prefix(4))66 }6768 /** The payload without its four checksum bytes; nil on a bad character, fewer than four bytes or a wrong checksum. */69 public static func decode(_ text: String, alphabet: Base58 = .bitcoin) -> [UInt8]? { decode(ascii: [UInt8](text.utf8), alphabet: alphabet) }7071 static func decode(ascii: [UInt8], alphabet: Base58 = .bitcoin) -> [UInt8]? {72 guard let raw = alphabet.decode(ascii: ascii), raw.count >= 4 else { return nil }73 let payload = [UInt8](raw.dropLast(4))74 guard [UInt8](SHA2.doubleSHA256(payload).prefix(4)) == [UInt8](raw.suffix(4)) else { return nil }75 return payload76 }77}7879/** SS58 (Substrate / Polkadot) account addresses with a one-byte network prefix (0–63) and a 32-byte account id. */80public enum SS58 {81 private static let context = [UInt8]("SS58PRE".utf8)8283 /** base58(prefix ‖ account ‖ first two bytes of BLAKE2b-512("SS58PRE" ‖ prefix ‖ account)); nil outside the supported shape. */84 public static func encode(prefix: UInt8, account: [UInt8]) -> String? {85 guard prefix <= 63, account.count == 32 else { return nil }86 let body = [prefix] + account87 return Base58.bitcoin.encode(body + Blake2b.hash(context + body, outputLength: 64).prefix(2))88 }8990 /** Prefix and 32-byte account id of a canonical one-byte-prefix address; nil on any other length, prefix form or checksum. */91 public static func decode(_ text: String) -> (prefix: UInt8, account: [UInt8])? {92 guard let raw = Base58.bitcoin.decode(text), raw.count == 35, raw[0] <= 63 else { return nil }93 let account = [UInt8](raw[1..<33])94 guard encode(prefix: raw[0], account: account) == text else { return nil }95 return (raw[0], account)96 }97}98