Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Blockchain/AddressValidator.swift3// Description: Client-side destination check, a port of `normalizeAddress` (packages/core/src/address.ts and the family4// plugins) with the same acceptance set and the same normalized output for every network of the backend5// registry. The backend stays the authority: it re-validates every destination. This layer exists so that the6// apps never call an address valid for a network when it is not, and never alter one: the only text an app may7// send or display as "the destination" is the `normalized` string of a `.valid` result, or the owner's own input.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213/** Why an address was refused. Informative only (the verdict is what matters); the wording shown to the owner is the app's. */14public enum AddressRejection: String, Error, Sendable, Equatable, CaseIterable {15 /** Not the shape of an address of this network (length, characters, prefix). */16 case malformed17 /** Right shape, wrong checksum: usually one mistyped character. */18 case badChecksum19 /** Mixed upper and lower case where the encoding forbids it (bech32, CashAddr). */20 case mixedCase21 /** A well-formed address of another network (test network, another chain's prefix or version byte, another workchain). */22 case wrongNetwork23 /** A real address form of this network that the wallet does not send to (X-address, muxed account, script address…). */24 case unsupportedType25 /** Zero / burn / system address: funds sent there are lost. */26 case reserved27 /** Decodes, but is not the single canonical spelling the backend accepts. */28 case nonCanonical29}3031public enum AddressCheck: Sendable, Equatable {32 /** Accepted by the same rules as the backend. `normalized` is exactly what the backend would store and sign. */33 case valid(normalized: String)34 case invalid(reason: AddressRejection)35 /** This build has no rules for the network (or the served network differs from the embedded one): the server will validate. Never treated as valid. */36 case unverifiable3738 public var normalized: String? { if case .valid(let n) = self { n } else { nil } }39 public var isValid: Bool { normalized != nil }40}4142public struct AddressValidator: Sendable {43 typealias Verdict = Result<String, AddressRejection>4445 /**46 Check `input` as a destination on `network`. Surrounding white space is ignored, as the backend does; nothing else is47 repaired. `.unverifiable` when the network id is unknown to this build, or when its family / chain reference differ from48 the embedded registry copy (the rules below would then be those of another chain).49 */50 public static func check(_ input: String, network: Network) -> AddressCheck {51 guard let p = AddressParameters.find(id: network.id), JSText.same(p.family, network.family), JSText.same(p.chainRef, network.chainRef) else { return .unverifiable }52 return check(input, parameters: p)53 }5455 static func check(_ input: String, parameters p: AddressParameters) -> AddressCheck {56 guard let verdict = verdict(JSText.trim(JSText.scalars(input)), p) else { return .unverifiable }57 switch verdict {58 case .success(let normalized): return .valid(normalized: normalized)59 case .failure(let reason): return .invalid(reason: reason)60 }61 }6263 /**64 The networks of `among` on which `input` is a valid destination, in the order given (used after a QR scan or a paste to warn65 that an address belongs to another network). NEAR named accounts accept almost any short lower-case text, so a NEAR match66 that is not a 64-hex implicit account is listed last: it is a weak signal next to a checksummed match.67 */68 public static func plausibleNetworks(for input: String, among networks: [Network]) -> [Network] {69 var strong: [Network] = [], weak: [Network] = []70 for n in networks {71 guard case .valid(let normalized) = check(input, network: n) else { continue }72 let isHex64 = normalized.utf8.count == 64 && normalized.utf8.allSatisfy(isLowerHex)73 if JSText.same(n.family, "near") && !isHex64 { weak.append(n) } else { strong.append(n) }74 }75 return strong + weak76 }7778 /**79 Address-poisoning pattern, as the server's `destinationWarnings`: two DIFFERENT addresses that share their first six and80 last four characters (case-insensitively). An attacker sends dust from such a look-alike so that it is copied from history.81 */82 public static func sameEndsDifferentMiddle(_ a: String, _ b: String) -> Bool {83 let x = Array(a.utf16), y = Array(b.utf16)84 guard x != y else { return false }85 func signature(_ u: [UInt16]) -> [Unicode.Scalar] {86 JSText.lower(JSText.scalars(String(decoding: u.prefix(6), as: UTF16.self))) + JSText.lower(JSText.scalars(String(decoding: u.suffix(4), as: UTF16.self)))87 }88 return signature(x) == signature(y)89 }9091 // MARK: dispatch (address.ts)9293 private static func verdict(_ s: [Unicode.Scalar], _ p: AddressParameters) -> Verdict? {94 switch p.family {95 case "evm": return evm(s)96 case "btc": return p.utxo.map { utxo(s, $0) }97 case "sol": return solana(s)98 case "bch": return p.utxo.flatMap { u in u.cashaddr.map { bitcoinCash(s, prefix: $0, pubKeyHash: u.pubKeyHash) } }99 case "tron": return tron(s)100 case "xrpl": return xrpl(s)101 case "stellar": return stellar(s)102 case "cosmos": return p.cosmos.map { cosmos(s, prefix: $0.bech32) }103 case "sui": return sui(s)104 case "aptos": return aptos(s)105 case "near": return near(s)106 case "ton": return ton(s)107 case "cardano": return cardano(s)108 case "polkadot": return polkadot(s)109 default: return nil110 }111 }112113 // MARK: character classes114115 private static func isHex(_ c: UInt8) -> Bool { (48...57).contains(c) || (97...102).contains(c) || (65...70).contains(c) }116 private static func isLowerHex(_ c: UInt8) -> Bool { (48...57).contains(c) || (97...102).contains(c) }117 private static func isDigit(_ c: UInt8) -> Bool { (48...57).contains(c) }118 private static func lowered(_ a: some Sequence<UInt8>) -> [UInt8] { a.map { (65...90).contains($0) ? $0 + 32 : $0 } }119 private static func uppered(_ a: some Sequence<UInt8>) -> [UInt8] { a.map { (97...122).contains($0) ? $0 - 32 : $0 } }120 private static func isMixedCase(_ a: [UInt8]) -> Bool { a.contains { (65...90).contains($0) } && a.contains { (97...122).contains($0) } }121 private static func hexBytes(_ a: some Collection<UInt8>) -> [UInt8] {122 func nibble(_ c: UInt8) -> UInt8 { c <= 57 ? c - 48 : (c | 0x20) - 87 }123 var out = [UInt8](), it = a.makeIterator()124 while let h = it.next(), let l = it.next() { out.append(nibble(h) << 4 | nibble(l)) }125 return out126 }127 /** `"0x"` followed by exactly `digits` hexadecimal digits of either case. */128 private static func isPrefixedHex(_ a: [UInt8], digits: Int) -> Bool { a.count == digits + 2 && a[0] == 0x30 && a[1] == 0x78 && a[2...].allSatisfy(isHex) }129130 // MARK: EVM (EIP-55)131132 /** EIP-55 spelling of 40 lower-case hex digits: a letter is upper case when the matching nibble of keccak256(text) is ≥ 8. */133 static func eip55(lowerHex: [UInt8]) -> [UInt8] {134 let hash = Keccak.keccak256(lowerHex)135 return lowerHex.enumerated().map { i, c in136 let nibble = i % 2 == 0 ? hash[i / 2] >> 4 : hash[i / 2] & 0x0f137 return c >= 97 && nibble >= 8 ? c - 32 : c138 }139 }140141 private static func evm(_ s: [Unicode.Scalar]) -> Verdict {142 guard let a = JSText.ascii(s), isPrefixedHex(a, digits: 40) else { return .failure(.malformed) }143 let body = [UInt8](a[2...]), lower = lowered(body), checksummed = eip55(lowerHex: lower)144 // mixed case must carry a valid checksum; all-lower and all-upper carry none and are checksummed145 if body != lower, body != uppered(body), body != checksummed { return .failure(.badChecksum) }146 if lower.allSatisfy({ $0 == 48 }) { return .failure(.reserved) }147 return .success("0x" + JSText.text(checksummed))148 }149150 // MARK: Bitcoin-style chains (bitcoin, litecoin, dogecoin)151152 private static func utxo(_ s: [Unicode.Scalar], _ u: AddressParameters.UTXO) -> Verdict {153 guard let a = JSText.ascii(s), (14...74).contains(a.count) else { return .failure(.malformed) }154 let hrp = u.bech32 ?? "none" // what the backend hands to its decoder when the chain has no SegWit prefix155 let lower = lowered(a)156 if lower.starts(with: Array((hrp + "1").utf8)) {157 guard let d = SegWitAddress.decode(ascii: a, hrp: hrp) else { return .failure(isMixedCase(a) ? .mixedCase : .badChecksum) }158 // P2WPKH, P2WSH and P2TR only: other witness versions / program sizes (and pay-to-anchor) are refused159 guard (d.version == 0 && (d.program.count == 20 || d.program.count == 32)) || (d.version == 1 && d.program.count == 32) else { return .failure(.unsupportedType) }160 guard u.kind != "pkh" else { return .failure(.unsupportedType) }161 return .success(JSText.text(u.bech32 == nil ? a : lower))162 }163 guard let payload = Base58Check.decode(ascii: a) else {164 if Bech32.decode(ascii: a, variant: .bech32) != nil || Bech32.decode(ascii: a, variant: .bech32m) != nil { return .failure(.wrongNetwork) }165 return .failure(Base58.bitcoin.decode(ascii: a) != nil ? .badChecksum : .malformed)166 }167 guard payload.count == 21 else { return .failure(.malformed) }168 guard payload[0] == u.pubKeyHash || payload[0] == u.scriptHash else { return .failure(.wrongNetwork) }169 return .success(JSText.text(a))170 }171172 // MARK: Bitcoin Cash (plugins/bch.ts)173174 private static func bitcoinCash(_ s: [Unicode.Scalar], prefix: String, pubKeyHash: UInt8) -> Verdict {175 if let a = JSText.ascii(s), !a.contains(0x3a), (25...35).contains(a.count), a[0] == 0x31 || a[0] == 0x33, a.dropFirst().allSatisfy(Base58.isBase58) {176 // Legacy Base58: only pay-to-public-key-hash, re-expressed as CashAddr. A "3…" address is refused by the backend177 // (on Bitcoin it is usually a SegWit script that cannot be spent on Bitcoin Cash).178 guard let payload = Base58Check.decode(ascii: a) else { return .failure(.badChecksum) }179 guard payload.count == 21 else { return .failure(.malformed) }180 guard payload[0] == pubKeyHash, let out = CashAddr.encode(prefix: prefix, type: 0, hash: [UInt8](payload.dropFirst())) else { return .failure(.unsupportedType) }181 return .success(out)182 }183 let lowerScalars = JSText.lower(s)184 if s != lowerScalars && s != JSText.upper(s) { return .failure(.mixedCase) }185 guard let lower = JSText.ascii(lowerScalars) else { return .failure(.malformed) }186 guard let d = CashAddr.decode(ascii: lower, defaultPrefix: prefix) else {187 let parts = lower.split(separator: 0x3a, omittingEmptySubsequences: false)188 let wellFormed = parts.count <= 2 && (42...112).contains(parts.last?.count ?? 0) && (parts.last ?? []).allSatisfy { Bech32.value(of: $0) != nil }189 return .failure(wellFormed ? .badChecksum : .malformed)190 }191 guard JSText.same(d.prefix, prefix) else { return .failure(.wrongNetwork) }192 guard d.type <= 1, d.hash.count == 20, let out = CashAddr.encode(prefix: prefix, type: d.type, hash: d.hash) else { return .failure(.unsupportedType) }193 return .success(out)194 }195196 // MARK: Solana197198 private static func solana(_ s: [Unicode.Scalar]) -> Verdict {199 guard let a = JSText.ascii(s), let raw = Base58.bitcoin.decode(ascii: a), raw.count == 32 else { return .failure(.malformed) }200 guard Base58.bitcoin.encode(raw) == JSText.text(a) else { return .failure(.nonCanonical) }201 return .success(JSText.text(a))202 }203204 // MARK: TRON205206 private static func tron(_ s: [Unicode.Scalar]) -> Verdict {207 guard let a = JSText.ascii(s), a.count == 34, a[0] == 0x54, a.dropFirst().allSatisfy(Base58.isBase58) else { return .failure(.malformed) }208 guard let raw = Base58Check.decode(ascii: a) else { return .failure(.badChecksum) }209 guard raw.count == 21, raw[0] == 0x41 else { return .failure(.wrongNetwork) }210 guard Base58Check.encode(raw) == JSText.text(a) else { return .failure(.nonCanonical) }211 guard raw.dropFirst().contains(where: { $0 != 0 }) else { return .failure(.reserved) }212 return .success(JSText.text(a))213 }214215 // MARK: XRP Ledger216217 private static func xrpl(_ s: [Unicode.Scalar]) -> Verdict {218 guard let a = JSText.ascii(s) else { return .failure(.malformed) }219 guard (25...35).contains(a.count), a[0] == 0x72, a.dropFirst().allSatisfy(Base58.isBase58) else {220 // X-address (address + tag packed together): the backend wants the classic address and a separate destination tag221 if a.count == 47, a[0] == 0x58 || a[0] == 0x54, a.dropFirst().allSatisfy(Base58.isBase58) { return .failure(.unsupportedType) }222 return .failure(.malformed)223 }224 guard let raw = Base58.ripple.decode(ascii: a), raw.count == 25, raw[0] == 0x00 else { return .failure(.malformed) }225 guard [UInt8](SHA2.doubleSHA256([UInt8](raw[..<21])).prefix(4)) == [UInt8](raw[21...]) else { return .failure(.badChecksum) }226 guard Base58.ripple.encode(raw) == JSText.text(a) else { return .failure(.nonCanonical) }227 return .success(JSText.text(a))228 }229230 // MARK: Stellar231232 private static func stellar(_ s: [Unicode.Scalar]) -> Verdict {233 guard let a = JSText.ascii(s) else { return .failure(.malformed) }234 func isBase32(_ c: UInt8) -> Bool { (65...90).contains(c) || (50...55).contains(c) }235 if a.count == 69, a[0] == 0x4d, a.dropFirst().allSatisfy(isBase32) { return .failure(.unsupportedType) } // muxed M… account236 guard a.count == 56, a[0] == 0x47, a.dropFirst().allSatisfy(isBase32) else { return .failure(.malformed) }237 guard let raw = Base32.decode(ascii: a), raw.count == 35, raw[0] == 6 << 3 else { return .failure(.malformed) }238 let crc = CRC16.xmodem(raw[..<33])239 guard raw[33] == UInt8(crc & 0xff), raw[34] == UInt8(crc >> 8) else { return .failure(.badChecksum) }240 guard Base32.encode(raw) == JSText.text(a) else { return .failure(.nonCanonical) }241 return .success(JSText.text(a))242 }243244 // MARK: Cosmos SDK245246 private static func cosmos(_ s: [Unicode.Scalar], prefix: String) -> Verdict {247 guard let a = JSText.ascii(s) else { return .failure(.malformed) }248 // /^[a-z0-9]+1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{38}$/ : the separator is the 39th character from the end249 let shape = a.count >= 40 && a[a.count - 39] == 0x31 && a[(a.count - 38)...].allSatisfy({ Bech32.value(of: $0) != nil })250 && a[..<(a.count - 39)].allSatisfy({ (97...122).contains($0) || isDigit($0) })251 guard shape else { return .failure(.malformed) }252 guard a.starts(with: Array((prefix + "1").utf8)) else { return .failure(Bech32.decode(ascii: a, variant: .bech32) != nil ? .wrongNetwork : .malformed) }253 guard let d = Bech32.decode(ascii: a, variant: .bech32), let bytes = Bech32.fromWords(d.words) else { return .failure(.badChecksum) }254 guard JSText.same(d.hrp, prefix) else { return .failure(.wrongNetwork) }255 guard bytes.count == 20 else { return .failure(.unsupportedType) }256 guard let again = Bech32.encode(hrp: prefix, words: Bech32.toWords(bytes), variant: .bech32), again == JSText.text(a) else { return .failure(.nonCanonical) }257 return .success(JSText.text(a))258 }259260 // MARK: Sui, Aptos261262 private static func sui(_ s: [Unicode.Scalar]) -> Verdict {263 guard let a = JSText.ascii(s), isPrefixedHex(a, digits: 64) else { return .failure(.malformed) }264 let lower = lowered(a)265 // below 2^16: the zero address and the protocol's own packages and system objects266 guard hexBytes(lower[2...]).prefix(30).contains(where: { $0 != 0 }) else { return .failure(.reserved) }267 return .success(JSText.text(lower))268 }269270 private static func aptos(_ s: [Unicode.Scalar]) -> Verdict {271 guard let a = JSText.ascii(s), isPrefixedHex(a, digits: 64) else { return .failure(.malformed) }272 let lower = lowered(a), raw = hexBytes(lower[2...])273 // 0x0–0xf are the framework's special addresses274 guard raw.prefix(31).contains(where: { $0 != 0 }) || raw[31] >= 0x10 else { return .failure(.reserved) }275 return .success(JSText.text(lower))276 }277278 // MARK: NEAR279280 private static func near(_ s: [Unicode.Scalar]) -> Verdict {281 guard let a = JSText.ascii(s), (2...64).contains(a.count) else { return .failure(.malformed) }282 var afterSeparator = true // at the start and right after a separator an alphanumeric must follow283 for c in a {284 if (97...122).contains(c) || isDigit(c) { afterSeparator = false; continue }285 if (c == 0x2e || c == 0x2d || c == 0x5f) && !afterSeparator { afterSeparator = true; continue }286 return .failure((65...90).contains(c) ? .mixedCase : .malformed)287 }288 guard !afterSeparator else { return .failure(.malformed) }289 if a.count == 64, a.allSatisfy(isLowerHex) { return .success(JSText.text(a)) } // implicit account290 if a == Array("system".utf8) { return .failure(.reserved) }291 // Ethereum-style "0x…" and the other derived "0s…" / "0u…" accounts292 if a.count == 42, a[0] == 0x30, (97...122).contains(a[1]), a[2...].allSatisfy(isLowerHex) { return .failure(.unsupportedType) }293 return .success(JSText.text(a))294 }295296 // MARK: TON297298 private static func ton(_ s: [Unicode.Scalar]) -> Verdict {299 guard let a = JSText.ascii(s) else { return .failure(.malformed) }300 var id: [UInt8]301 if a.count >= 66, a[a.count - 65] == 0x3a, a[(a.count - 64)...].allSatisfy(isHex), isSignedDecimal(a[..<(a.count - 65)]) {302 // raw form "<workchain>:<64 hex>"303 guard a[..<(a.count - 65)].elementsEqual([0x30]) else { return .failure(.wrongNetwork) }304 id = hexBytes(a[(a.count - 64)...])305 } else {306 func isBase64(_ c: UInt8) -> Bool { (65...90).contains(c) || (97...122).contains(c) || isDigit(c) || c == 0x2d || c == 0x5f || c == 0x2b || c == 0x2f }307 guard a.count == 48, a.allSatisfy(isBase64) else { return .failure(.malformed) }308 let urlSafe = a.contains { $0 == 0x2d || $0 == 0x5f }, standard = a.contains { $0 == 0x2b || $0 == 0x2f }309 guard !(urlSafe && standard) else { return .failure(.malformed) }310 let std = a.map { $0 == 0x2d ? UInt8(0x2b) : $0 == 0x5f ? UInt8(0x2f) : $0 }311 guard let data = Data(base64Encoded: Data(std)), data.count == 36 else { return .failure(.malformed) }312 let b = [UInt8](data), crc = CRC16.xmodem(b[..<34])313 guard b[34] == UInt8(crc >> 8), b[35] == UInt8(crc & 0xff) else { return .failure(.badChecksum) }314 guard b[0] & 0x80 == 0 else { return .failure(.wrongNetwork) } // testnet-only flag315 guard b[0] == 0x11 || b[0] == 0x51 else { return .failure(.malformed) } // bounceable / non-bounceable316 guard b[1] == 0 else { return .failure(.wrongNetwork) } // workchain 0 only317 id = [UInt8](b[2..<34])318 }319 guard id.contains(where: { $0 != 0 }) else { return .failure(.reserved) }320 return .success(tonFriendly(accountId: id))321 }322323 private static func isSignedDecimal(_ a: ArraySlice<UInt8>) -> Bool {324 let digits = a.first == 0x2d ? a.dropFirst() : a325 return !digits.isEmpty && digits.allSatisfy(isDigit)326 }327328 /** The backend's canonical TON form: non-bounceable (0x51), workchain 0, URL-safe base64 ("UQ…"). */329 static func tonFriendly(accountId: [UInt8]) -> String {330 var body: [UInt8] = [0x51, 0x00] + accountId331 let crc = CRC16.xmodem(body)332 body.append(UInt8(crc >> 8)); body.append(UInt8(crc & 0xff))333 return JSText.text(Data(body).base64EncodedString().utf8.map { $0 == 0x2b ? UInt8(0x2d) : $0 == 0x2f ? UInt8(0x5f) : $0 })334 }335336 // MARK: Cardano (Shelley, CIP-19)337338 private static func cardano(_ s: [Unicode.Scalar]) -> Verdict {339 // bech32 is case-insensitive as a whole: an all-upper-case address (QR codes) is lowered; mixed case is refused340 let folded = s == JSText.upper(s) ? JSText.lower(s) : s341 guard let a = JSText.ascii(folded) else { return .failure(.malformed) }342 let head = Array("addr1".utf8)343 guard a.starts(with: head), (53...98).contains(a.count - 5), a[5...].allSatisfy({ Bech32.value(of: $0) != nil }) else {344 if isMixedCase(a), lowered(a).starts(with: head) { return .failure(.mixedCase) }345 if a.starts(with: Array("addr_test1".utf8)) { return .failure(.wrongNetwork) }346 if a.starts(with: Array("stake1".utf8)) { return .failure(.unsupportedType) }347 return .failure(.malformed)348 }349 guard let d = Bech32.decode(ascii: a, variant: .bech32, limit: 128), let b = Bech32.fromWords(d.words), let header = b.first else { return .failure(.badChecksum) }350 guard d.hrp == "addr" else { return .failure(.malformed) }351 let type = header >> 4352 guard header & 0x0f == 1 else { return .failure(.wrongNetwork) }353 // base / pointer-free types 0–3 are 57 bytes, enterprise types 6–7 are 29; pointer (4–5), Byron (8) and reward (14–15) are refused354 guard type <= 3 ? b.count == 57 : (type == 6 || type == 7) && b.count == 29 else { return .failure(.unsupportedType) }355 guard let again = Bech32.encode(hrp: "addr", words: Bech32.toWords(b), variant: .bech32, limit: 128), again == JSText.text(a) else { return .failure(.nonCanonical) }356 // the payment part must be a key: ADA sent to a script address without its datum can be locked for ever357 guard type == 0 || type == 2 || type == 6 else { return .failure(.unsupportedType) }358 return .success(JSText.text(a))359 }360361 // MARK: Polkadot (SS58, prefix 0)362363 private static func polkadot(_ s: [Unicode.Scalar]) -> Verdict {364 guard let a = JSText.ascii(s), (35...48).contains(a.count), a[0] == 0x31, a.dropFirst().allSatisfy(Base58.isBase58) else {365 // another network's form of an account (Kusama, generic Substrate "5…")366 if let a = JSText.ascii(s), SS58.decode(JSText.text(a)) != nil { return .failure(.wrongNetwork) }367 return .failure(.malformed)368 }369 guard let raw = Base58.bitcoin.decode(ascii: a), raw.count == 35, raw[0] == 0 else { return .failure(.malformed) }370 let account = [UInt8](raw[1..<33])371 guard SS58.encode(prefix: 0, account: account) == JSText.text(a) else { return .failure(.badChecksum) }372 guard account.contains(where: { $0 != 0 }) else { return .failure(.reserved) }373 return .success(JSText.text(a))374 }375}376