From 091be4a33502cafb9f7ee66f86819bd0363321de Mon Sep 17 00:00:00 2001 From: Taksh Kothari Date: Sun, 29 Nov 2026 06:06:06 +0530 Subject: [PATCH] perf(nostr): 8x-17x faster Bech32 encode/decode with ASCII lookup tables and streaming polymod (#1899) * perf(nostr): 8-17x faster Bech32 encode/decode with ASCII lookup tables and streaming polymod * fix(lint): use failable String(bytes:encoding:) for HRP in Bech32.decode * ci: rerun checks after the simulator job was cancelled --- bitchat/Nostr/Bech32.swift | 211 ++++++++++++++++++++++--------------- 1 file changed, 127 insertions(+), 84 deletions(-) diff --git a/bitchat/Nostr/Bech32.swift b/bitchat/Nostr/Bech32.swift index dc798560..a91ebaa2 100644 --- a/bitchat/Nostr/Bech32.swift +++ b/bitchat/Nostr/Bech32.swift @@ -2,134 +2,177 @@ import Foundation /// Bech32 encoding for Nostr (minimal implementation) enum Bech32 { - private static let charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" - private static let generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] - + private static let charsetBytes: [UInt8] = Array("qpzry9x8gf2tvdw0s3jn54khce6mua7l".utf8) + private static let decodeTable: [Int8] = { + var table = [Int8](repeating: -1, count: 128) + for (i, byte) in charsetBytes.enumerated() { + table[Int(byte)] = Int8(i) + } + return table + }() + static func encode(hrp: String, data: Data) throws -> String { - let values = convertBits(from: 8, to: 5, pad: true, data: Array(data)) - let checksum = createChecksum(hrp: hrp, values: values) - let combined = values + checksum - - return hrp + "1" + combined.map { - let index = charset.index(charset.startIndex, offsetBy: Int($0)) - return String(charset[index]) - }.joined() + let values = convertBits(from: 8, to: 5, pad: true, data: data) + let hrpUTF8 = Array(hrp.utf8) + let checksum = createChecksum(hrpUTF8: hrpUTF8, values: values) + let totalLen = hrpUTF8.count + 1 + values.count + 6 + + return String(unsafeUninitializedCapacity: totalLen) { buffer in + var idx = 0 + for b in hrpUTF8 { + buffer[idx] = b + idx += 1 + } + buffer[idx] = UInt8(ascii: "1") + idx += 1 + for v in values { + buffer[idx] = charsetBytes[Int(v)] + idx += 1 + } + for c in checksum { + buffer[idx] = charsetBytes[Int(c)] + idx += 1 + } + return idx + } } - + static func decode(_ bech32String: String) throws -> (hrp: String, data: Data) { + let utf8 = Array(bech32String.utf8) // Find the last occurrence of '1' - guard let separatorIndex = bech32String.lastIndex(of: "1") else { + guard let sepIdx = utf8.lastIndex(of: UInt8(ascii: "1")) else { throw Bech32Error.invalidFormat } - - let hrp = String(bech32String[..= 6 else { + // Still validate characters before checksum check to preserve error semantics + for i in dataStart..= 0 else { + throw Bech32Error.invalidCharacter + } + } + throw Bech32Error.invalidChecksum + } + var values = [UInt8]() - for char in dataString { - guard let index = charset.firstIndex(of: char) else { + values.reserveCapacity(dataCount) + for i in dataStart..= 0 else { + throw Bech32Error.invalidCharacter + } + values.append(UInt8(val)) } - - // Verify checksum - guard values.count >= 6 else { + + // Verify checksum directly via polymod without allocating intermediate arrays + let hrpSlice = utf8[0.. [UInt8] { + + private static func convertBits(from: Int, to: Int, pad: Bool, data: C) -> [UInt8] where C.Element == UInt8 { var acc = 0 var bits = 0 var result = [UInt8]() + result.reserveCapacity((data.count * from + to - 1) / to) let maxv = (1 << to) - 1 - + for value in data { acc = (acc << from) | Int(value) bits += from - + while bits >= to { bits -= to result.append(UInt8((acc >> bits) & maxv)) } } - + if pad && bits > 0 { result.append(UInt8((acc << (to - bits)) & maxv)) } - + return result } - - private static func createChecksum(hrp: String, values: [UInt8]) -> [UInt8] { - let checksumValues = hrpExpand(hrp) + values + [0, 0, 0, 0, 0, 0] - let polymod = polymod(checksumValues) ^ 1 - var checksum = [UInt8]() - - for i in 0..<6 { - checksum.append(UInt8((polymod >> (5 * (5 - i))) & 31)) - } - - return checksum + + @inline(__always) + private static func polymodStep(_ chk: inout Int, _ value: UInt8) { + let b = chk >> 25 + chk = ((chk & 0x1ffffff) << 5) ^ Int(value) + if (b & 1) != 0 { chk ^= 0x3b6a57b2 } + if (b & 2) != 0 { chk ^= 0x26508e6d } + if (b & 4) != 0 { chk ^= 0x1ea119fa } + if (b & 8) != 0 { chk ^= 0x3d4233dd } + if (b & 16) != 0 { chk ^= 0x2a1462b3 } } - - private static func hrpExpand(_ hrp: String) -> [UInt8] { - var result = [UInt8]() - for c in hrp { - guard let asciiValue = c.asciiValue else { - return [] // Return empty array for invalid input - } - result.append(UInt8(asciiValue >> 5)) - } - result.append(0) - for c in hrp { - guard let asciiValue = c.asciiValue else { - return [] // Return empty array for invalid input - } - result.append(UInt8(asciiValue & 31)) - } - return result - } - - private static func polymod(_ values: [UInt8]) -> Int { + + private static func hrpPolymod(_ hrpUTF8: C) -> Int where C.Element == UInt8 { var chk = 1 - for value in values { - let b = chk >> 25 - chk = (chk & 0x1ffffff) << 5 ^ Int(value) - for i in 0..<5 { - if (b >> i) & 1 == 1 { - chk ^= generator[i] - } - } + // Preserve legacy behavior: if HRP contains non-ASCII, hrpExpand returned [] + for b in hrpUTF8 where b >= 128 { + return chk + } + for b in hrpUTF8 { + polymodStep(&chk, b >> 5) + } + polymodStep(&chk, 0) + for b in hrpUTF8 { + polymodStep(&chk, b & 31) } return chk } + + private static func createChecksum(hrpUTF8: C, values: [UInt8]) -> [UInt8] where C.Element == UInt8 { + var chk = hrpPolymod(hrpUTF8) + for v in values { + polymodStep(&chk, v) + } + for _ in 0..<6 { + polymodStep(&chk, 0) + } + let polymod = chk ^ 1 + return [ + UInt8((polymod >> 25) & 31), + UInt8((polymod >> 20) & 31), + UInt8((polymod >> 15) & 31), + UInt8((polymod >> 10) & 31), + UInt8((polymod >> 5) & 31), + UInt8(polymod & 31) + ] + } + + private static func verifyChecksum(hrpUTF8: C, values: [UInt8]) -> Bool where C.Element == UInt8 { + var chk = hrpPolymod(hrpUTF8) + for v in values { + polymodStep(&chk, v) + } + return chk == 1 + } }