Auditoria
O cliente HTTP
Kit/Sources/EscaliburNetwork/HTTPClient.swift
if canImport(FoundationNetworking) endif
| 1 | import EscaliburChains |
| 2 | import Foundation |
| 3 | #if canImport(FoundationNetworking) |
| 4 | import FoundationNetworking |
| 5 | #endif |
| 6 | |
| 7 | /// O unico ponto do app que fala com a internet. |
| 8 | /// |
| 9 | /// Configuracao de docs/seguranca.md §5.1: sessao efemera sem cache, sem cookies e |
| 10 | /// sem credenciais guardadas (nada de `Cache.db` revelando quais tokens o dono olha), |
| 11 | /// sem seguir redirecionamento, resposta limitada a 4 MB, timeouts curtos, e um |
| 12 | /// User-Agent constante que nao entrega versao do app nem do iOS. |
| 13 | public final class HTTPClient: NSObject, @unchecked Sendable { |
| 14 | public enum Failure: Error, Equatable, Sendable { |
| 15 | case offline |
| 16 | case timeout |
| 17 | case status(Int) |
| 18 | case tooLarge |
| 19 | case redirectRefused |
| 20 | case invalidResponse |
| 21 | /// Host fora do hosts.lock, ou esquema diferente de https. |
| 22 | case hostNotAllowed |
| 23 | case decoding(String) |
| 24 | } |
| 25 | |
| 26 | /// Uma recusa 4xx com o corpo, para quem precisa do motivo exato: a CoW diz por que nao aceitou |
| 27 | /// a ordem (`postKeepingRefusal`). O corpo vem limitado a 16 KB. |
| 28 | public struct Refusal: Error, Equatable, Sendable { |
| 29 | public let status: Int |
| 30 | public let body: Data |
| 31 | } |
| 32 | |
| 33 | static let maxRefusalBytes = 16 * 1024 |
| 34 | |
| 35 | public static let shared = HTTPClient() |
| 36 | |
| 37 | static let maxResponseBytes = 4 * 1024 * 1024 |
| 38 | static let resourceTimeout: TimeInterval = 30 |
| 39 | static let userAgent = "EscaliburWallet" |
| 40 | |
| 41 | /// So para os testes: um `URLProtocol` no lugar da rede. |
| 42 | private let protocolClasses: [AnyClass]? |
| 43 | /// Os unicos hosts com que o cliente fala: gerados do hosts.lock |
| 44 | /// (`AllowedHosts.swift`, conferido pelo verificar.sh). Um endereco montado em tempo |
| 45 | /// de execucao, ou vindo de uma resposta, nao sai do aparelho. |
| 46 | private let allowedHosts: Set<String> |
| 47 | |
| 48 | /// A rede de verdade (sem o `URLProtocol` dos testes): os leitores sorteiam a ordem dos donos a cada consenso. |
| 49 | public var drawsProviders: Bool { protocolClasses == nil } |
| 50 | |
| 51 | public override convenience init() { self.init(protocolClasses: nil, allowedHosts: AllowedHosts.all) } |
| 52 | |
| 53 | init(protocolClasses: [AnyClass]?, allowedHosts: Set<String> = AllowedHosts.all) { |
| 54 | self.protocolClasses = protocolClasses |
| 55 | self.allowedHosts = allowedHosts |
| 56 | super.init() |
| 57 | } |
| 58 | |
| 59 | /// Criada uma vez so, sob a trava: `lazy var` nao e seguro entre threads, e duas |
| 60 | /// sessoes repetiriam `taskIdentifier`, trocando a leitura de uma pela de outra. |
| 61 | private var session: URLSession { |
| 62 | lock.withLock { |
| 63 | if let existing = sessionStorage { return existing } |
| 64 | let made = makeSession() |
| 65 | sessionStorage = made |
| 66 | return made |
| 67 | } |
| 68 | } |
| 69 | private var sessionStorage: URLSession? |
| 70 | |
| 71 | private func makeSession() -> URLSession { |
| 72 | let configuration = URLSessionConfiguration.ephemeral |
| 73 | #if os(Android) |
| 74 | // No Android a requisicao sai pelo transporte do sistema, nunca pela libcurl do Swift |
| 75 | // SDK (AndroidTransport.swift). |
| 76 | configuration.protocolClasses = protocolClasses ?? [AndroidURLProtocol.self] |
| 77 | #else |
| 78 | if let protocolClasses { configuration.protocolClasses = protocolClasses } |
| 79 | #endif |
| 80 | configuration.urlCache = nil |
| 81 | configuration.httpCookieStorage = nil |
| 82 | configuration.urlCredentialStorage = nil |
| 83 | configuration.httpShouldSetCookies = false |
| 84 | configuration.requestCachePolicy = .reloadIgnoringLocalCacheData |
| 85 | #if canImport(Darwin) |
| 86 | configuration.waitsForConnectivity = false |
| 87 | #endif |
| 88 | configuration.timeoutIntervalForRequest = 10 |
| 89 | configuration.timeoutIntervalForResource = Self.resourceTimeout |
| 90 | #if canImport(Darwin) |
| 91 | configuration.tlsMinimumSupportedProtocolVersion = .TLSv12 |
| 92 | #endif |
| 93 | // O URLSession do Android nao tem essas duas opcoes. La o TLS 1.2 minimo e do transporte |
| 94 | // do sistema (AndroidTransport.swift). |
| 95 | configuration.httpAdditionalHeaders = ["User-Agent": Self.userAgent, "Accept-Language": "en"] |
| 96 | return URLSession(configuration: configuration, delegate: self, delegateQueue: nil) |
| 97 | } |
| 98 | |
| 99 | // MARK: Requisicoes |
| 100 | |
| 101 | /// `limit`: o teto de bytes da resposta, conferido enquanto ela chega (o `Content-Length` maior, ou o corpo que passa dele, |
| 102 | /// cortam a transferencia com `tooLarge`). |
| 103 | public func get(_ url: URL, headers: [String: String] = [:], timeout: TimeInterval = 10, |
| 104 | limit: Int? = nil) async throws -> Data { |
| 105 | var request = URLRequest(url: url, timeoutInterval: timeout) |
| 106 | request.httpMethod = "GET" |
| 107 | headers.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) } |
| 108 | return try await perform(request, limit: min(limit ?? HTTPClient.maxResponseBytes, HTTPClient.maxResponseBytes)) |
| 109 | } |
| 110 | |
| 111 | public func post(_ url: URL, json body: Data, headers: [String: String] = [:], timeout: TimeInterval = 10) async throws -> Data { |
| 112 | var request = URLRequest(url: url, timeoutInterval: timeout) |
| 113 | request.httpMethod = "POST" |
| 114 | request.httpBody = body |
| 115 | request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 116 | headers.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) } |
| 117 | return try await perform(request) |
| 118 | } |
| 119 | |
| 120 | /// O `post`, mas uma recusa 4xx vem como `Refusal`, com o corpo dela: o motivo que o servidor deu |
| 121 | /// (01/11/2026, a ordem limite que a CoW recusou mostrava so "a transmissao nao foi concluida"). |
| 122 | public func postKeepingRefusal(_ url: URL, json body: Data, headers: [String: String] = [:], timeout: TimeInterval = 10) async throws -> Data { |
| 123 | var request = URLRequest(url: url, timeoutInterval: timeout) |
| 124 | request.httpMethod = "POST" |
| 125 | request.httpBody = body |
| 126 | request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 127 | headers.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) } |
| 128 | return try await perform(request, keepsRefusal: true) |
| 129 | } |
| 130 | |
| 131 | /// PUT e DELETE com corpo JSON, pelas mesmas regras de `get`/`post`. A CoW so aceita |
| 132 | /// cancelamento em `DELETE /api/v1/orders` e registro de appData em `PUT`. |
| 133 | /// PUT que, numa recusa 4xx, devolve o corpo (ate 16 KB) em `Refusal`, como o `postKeepingRefusal`: |
| 134 | /// o registro do appData da CoW diz por que recusou (segunda passada da auditoria de 03/11/2026). |
| 135 | public func putKeepingRefusal(_ url: URL, json body: Data, timeout: TimeInterval = 10) async throws -> Data { |
| 136 | var request = URLRequest(url: url, timeoutInterval: timeout) |
| 137 | request.httpMethod = "PUT" |
| 138 | request.httpBody = body |
| 139 | request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 140 | return try await perform(request, keepsRefusal: true) |
| 141 | } |
| 142 | |
| 143 | public func send(_ method: String, _ url: URL, json body: Data?, headers: [String: String] = [:], timeout: TimeInterval = 10) async throws -> Data { |
| 144 | guard ["PUT", "DELETE"].contains(method) else { throw Failure.invalidResponse } |
| 145 | var request = URLRequest(url: url, timeoutInterval: timeout) |
| 146 | request.httpMethod = method |
| 147 | if let body { |
| 148 | request.httpBody = body |
| 149 | request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 150 | } |
| 151 | headers.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) } |
| 152 | return try await perform(request) |
| 153 | } |
| 154 | |
| 155 | public func getJSON<T: Decodable>(_ type: T.Type, from url: URL, headers: [String: String] = [:]) async throws -> T { |
| 156 | let data = try await get(url, headers: headers) |
| 157 | do { |
| 158 | return try JSONDecoder().decode(T.self, from: data) |
| 159 | } catch { |
| 160 | throw Failure.decoding(String(describing: type)) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | /// Hosts que servem muita coisa alem do que o app pede: so este caminho (auditoria 6). O |
| 165 | /// GitHub serve qualquer repositorio por `raw.githubusercontent.com`, e o app so le as |
| 166 | /// logos da Trust Wallet. O site da Escalibur (escalibur-wallet.github.io) e da org da |
| 167 | /// Escalibur inteiro e nao precisa de caminho. A Ankr atende dezenas de redes no mesmo host |
| 168 | /// (`rpc.ankr.com/eth`, `/solana`): o app so fala com ela no XRP Ledger, e um endereco de outra |
| 169 | /// rede nao chega la nem por engano. |
| 170 | static let pathPrefixes: [String: String] = [ |
| 171 | "raw.githubusercontent.com": "/trustwallet/assets/", |
| 172 | "rpc.ankr.com": "/xrp_mainnet", |
| 173 | ] |
| 174 | |
| 175 | /// Porta alem da 443, por host. Os servidores publicos da Ripple atendem JSON-RPC na |
| 176 | /// 51234, a porta da documentacao deles: a trava da auditoria 6 sem esta excecao deixou |
| 177 | /// a XRP Ledger com um servidor so, e a leitura por dois parou (build 9, 19/10/2026). |
| 178 | static let extraPorts: [String: Int] = [ |
| 179 | "s1.ripple.com": 51234, |
| 180 | "s2.ripple.com": 51234, |
| 181 | ] |
| 182 | |
| 183 | /// A regra de todo endereco: https, sem usuario nem senha, host da lista, a porta 443 (ou a do |
| 184 | /// host, acima) e, quando o host tem, so o caminho dele. O caminho conferido e o cru, como sai no |
| 185 | /// pedido: o `url.path` decodificado lia `%2e%2e` como `..` e o escape passava pelo prefixo |
| 186 | /// (auditoria de 23/11/2026). O unico produtor de endereco com prefixo (TokenLogos) nunca gera `%` |
| 187 | /// nem `..` (`TokenLogos.isSafe`). |
| 188 | static func permits(_ url: URL, allowedHosts: Set<String>) -> Bool { |
| 189 | guard url.scheme == "https", url.user == nil, url.password == nil, let host = url.host, allowedHosts.contains(host) else { return false } |
| 190 | guard url.port == nil || url.port == 443 || url.port == extraPorts[host] else { return false } |
| 191 | guard let prefix = pathPrefixes[host] else { return true } |
| 192 | let cru = url.path(percentEncoded: true) |
| 193 | return cru.hasPrefix(prefix) && !cru.contains("..") && !cru.contains("%") |
| 194 | } |
| 195 | |
| 196 | /// O corpo e lido em fluxo e cortado ao passar do limite. Resposta sem |
| 197 | /// Content-Length (chunked) nao chega inteira na memoria antes de ser medida. |
| 198 | /// |
| 199 | /// Uma tarefa de dados com o delegado da sessao, e nao `bytes(for:)`: em algumas |
| 200 | /// versoes do macOS (a do runner do CI) o fluxo de `bytes(for:)` parava de entregar |
| 201 | /// o corpo, e o delegado classico mede cada pedaco igual em todas. |
| 202 | private func perform(_ request: URLRequest, limit: Int = HTTPClient.maxResponseBytes, keepsRefusal: Bool = false) async throws -> Data { |
| 203 | guard let url = request.url, Self.permits(url, allowedHosts: allowedHosts) else { throw Failure.hostNotAllowed } |
| 204 | guard !isQuiet else { throw Failure.offline } |
| 205 | let task = session.dataTask(with: request) |
| 206 | do { |
| 207 | return try await withTaskCancellationHandler { |
| 208 | try await withCheckedThrowingContinuation { continuation in |
| 209 | // A conferencia do silencio e o registro sob a mesma trava: uma tela de |
| 210 | // segredo que abre agora cancela esta tarefa, ou ela nem comeca. |
| 211 | let paused = lock.withLock { () -> Bool in |
| 212 | guard quietHolds == 0 else { return true } |
| 213 | transfers[ObjectIdentifier(task)] = Transfer(continuation, task: task, limit: limit, keepsRefusal: keepsRefusal) |
| 214 | return false |
| 215 | } |
| 216 | if paused { |
| 217 | continuation.resume(throwing: Failure.offline) |
| 218 | return |
| 219 | } |
| 220 | task.resume() |
| 221 | } |
| 222 | } onCancel: { |
| 223 | task.cancel() |
| 224 | } |
| 225 | } catch { |
| 226 | throw error |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | /// Uma leitura em andamento: o corpo que ja chegou, a recusa (se houve) e quem espera. |
| 231 | private final class Transfer { |
| 232 | var data = Data() |
| 233 | var failure: Failure? |
| 234 | let continuation: CheckedContinuation<Data, Error> |
| 235 | let task: URLSessionTask |
| 236 | let limit: Int |
| 237 | /// Uma recusa 4xx traz o corpo (`postKeepingRefusal`): o status fica aqui, e o corpo e lido. |
| 238 | let keepsRefusal: Bool |
| 239 | var refusedStatus: Int? |
| 240 | |
| 241 | init(_ continuation: CheckedContinuation<Data, Error>, task: URLSessionTask, limit: Int, keepsRefusal: Bool = false) { |
| 242 | self.continuation = continuation |
| 243 | self.task = task |
| 244 | self.limit = limit |
| 245 | self.keepsRefusal = keepsRefusal |
| 246 | } |
| 247 | |
| 248 | var currentLimit: Int { refusedStatus == nil ? limit : HTTPClient.maxRefusalBytes } |
| 249 | } |
| 250 | |
| 251 | // MARK: Silencio |
| 252 | |
| 253 | /// Quantas telas de segredo estao abertas agora (`beginQuiet`). Com alguma aberta, |
| 254 | /// nenhuma requisicao sai do aparelho, e as que estavam no ar sao canceladas: a tela |
| 255 | /// de digitar as palavras nao divide o momento com conexao nenhuma (pedido do dono, |
| 256 | /// 16/10/2026). As palavras nunca vao para a rede de qualquer jeito; isto garante que |
| 257 | /// nem saldo, nem preco, nem logo saem enquanto elas estao na tela. |
| 258 | private var quietHolds = 0 |
| 259 | |
| 260 | public var isQuiet: Bool { lock.withLock { quietHolds > 0 } } |
| 261 | |
| 262 | /// Abre o silencio e cancela o que estava no ar. Cada `beginQuiet` pede um `endQuiet`. |
| 263 | public func beginQuiet() { |
| 264 | let live = lock.withLock { () -> [URLSessionTask] in |
| 265 | quietHolds += 1 |
| 266 | return transfers.values.map(\.task) |
| 267 | } |
| 268 | live.forEach { $0.cancel() } |
| 269 | } |
| 270 | |
| 271 | public func endQuiet() { |
| 272 | lock.withLock { |
| 273 | quietHolds = max(0, quietHolds - 1) |
| 274 | if quietHolds == 0 { audibleSince = ProcessInfo.processInfo.systemUptime } |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | /// Quando o ultimo silencio acabou (tempo desde o boot). |
| 279 | private var audibleSince: TimeInterval = 0 |
| 280 | |
| 281 | /// Espera o silencio acabar (a tela de segredo fechou), e mais 2 s, ou o cancelamento. A conferencia que sai com ele ligado |
| 282 | /// volta sem resposta nenhuma: a das palavras escolhidas, gravada com a tela de digitar ainda montada, nao lia nada (rodada |
| 283 | /// 7 da auditoria 8). Os 2 s dao a vez a tela seguinte (a previa da importacao pausa as conferencias antes de elas sairem; |
| 284 | /// rodada 8). |
| 285 | public func whenAudible() async { |
| 286 | while !Task.isCancelled { |
| 287 | let (quiet, since) = lock.withLock { (quietHolds > 0, audibleSince) } |
| 288 | if !quiet, ProcessInfo.processInfo.systemUptime - since >= 2 { return } |
| 289 | try? await Task.sleep(nanoseconds: 200_000_000) |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | private let lock = NSLock() |
| 294 | /// Pela identidade da tarefa, viva ate `didCompleteWithError` tirar a entrada daqui. |
| 295 | private var transfers: [ObjectIdentifier: Transfer] = [:] |
| 296 | |
| 297 | private func transfer(_ task: URLSessionTask) -> Transfer? { |
| 298 | lock.withLock { transfers[ObjectIdentifier(task)] } |
| 299 | } |
| 300 | |
| 301 | static func failure(for error: Error) -> Failure { |
| 302 | switch (error as? URLError)?.code { |
| 303 | case .notConnectedToInternet, .networkConnectionLost, .dataNotAllowed: return .offline |
| 304 | case .timedOut: return .timeout |
| 305 | default: return .invalidResponse |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | extension HTTPClient: URLSessionDataDelegate { |
| 311 | /// Redirecionamento nunca e seguido: um provedor comprometido nao manda o app |
| 312 | /// buscar dado em outro host. |
| 313 | public func urlSession( |
| 314 | _ session: URLSession, task: URLSessionTask, |
| 315 | willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, |
| 316 | completionHandler: @escaping @Sendable (URLRequest?) -> Void |
| 317 | ) { |
| 318 | completionHandler(nil) |
| 319 | } |
| 320 | |
| 321 | /// Status e tamanho anunciado sao conferidos antes de qualquer byte do corpo. |
| 322 | public func urlSession( |
| 323 | _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, |
| 324 | completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void |
| 325 | ) { |
| 326 | guard let transfer = transfer(dataTask) else { return completionHandler(.cancel) } |
| 327 | let refusal: Failure? |
| 328 | if let http = response as? HTTPURLResponse { |
| 329 | if (300..<400).contains(http.statusCode) { refusal = .redirectRefused } |
| 330 | else if transfer.keepsRefusal, (400..<500).contains(http.statusCode) { |
| 331 | // O corpo da recusa e lido, ate 16 KB, para quem pediu o motivo. Anunciado maior, |
| 332 | // nem chega: fica a recusa sem o motivo (auditoria de 03/11/2026). |
| 333 | lock.withLock { transfer.refusedStatus = http.statusCode } |
| 334 | refusal = http.expectedContentLength > Int64(HTTPClient.maxRefusalBytes) ? .status(http.statusCode) : nil |
| 335 | } |
| 336 | else if !(200..<300).contains(http.statusCode) { refusal = .status(http.statusCode) } |
| 337 | else if http.expectedContentLength > Int64(transfer.limit) { refusal = .tooLarge } |
| 338 | else { refusal = nil } |
| 339 | } else { |
| 340 | refusal = .invalidResponse |
| 341 | } |
| 342 | lock.withLock { |
| 343 | transfer.failure = refusal |
| 344 | // Nunca reserva mais que o teto desta resposta: o tamanho anunciado vem de fora. |
| 345 | if refusal == nil, response.expectedContentLength > 0 { |
| 346 | transfer.data.reserveCapacity(min(Int(clamping: response.expectedContentLength), transfer.currentLimit)) |
| 347 | } |
| 348 | } |
| 349 | completionHandler(refusal == nil ? .allow : .cancel) |
| 350 | } |
| 351 | |
| 352 | public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { |
| 353 | guard let transfer = transfer(dataTask) else { return } |
| 354 | let over = lock.withLock { () -> Bool in |
| 355 | guard transfer.failure == nil else { return false } |
| 356 | transfer.data.append(data) |
| 357 | guard transfer.data.count > transfer.currentLimit else { return false } |
| 358 | transfer.failure = .tooLarge |
| 359 | transfer.data = Data() |
| 360 | return true |
| 361 | } |
| 362 | if over { dataTask.cancel() } |
| 363 | } |
| 364 | |
| 365 | public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { |
| 366 | guard let transfer = lock.withLock({ transfers.removeValue(forKey: ObjectIdentifier(task)) }) else { return } |
| 367 | #if DEBUG |
| 368 | NetworkDiagnostics.shared.record(host: task.originalRequest?.url?.host ?? "?", failure: transfer.failure, error: error) |
| 369 | #endif |
| 370 | if let failure = transfer.failure { |
| 371 | transfer.continuation.resume(throwing: failure) |
| 372 | } else if error == nil, let status = transfer.refusedStatus { |
| 373 | transfer.continuation.resume(throwing: Refusal(status: status, body: transfer.data)) |
| 374 | } else if let error { |
| 375 | transfer.continuation.resume(throwing: Self.failure(for: error)) |
| 376 | } else { |
| 377 | transfer.continuation.resume(returning: transfer.data) |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | /// Um conjunto de provedores equivalentes para o mesmo servico, com contingencia. |
| 383 | /// |
| 384 | /// Circuit breaker simples: tres falhas seguidas tiram o provedor por 60 segundos. |
| 385 | /// A ordem de preferencia e fixa no codigo (o consenso a sorteia, `consensusOrder`); |
| 386 | /// nenhuma resposta de rede acrescenta provedor. |
| 387 | public actor ProviderPool { |
| 388 | public struct Provider: Sendable, Hashable { |
| 389 | public let name: String |
| 390 | public let baseURL: URL |
| 391 | /// A empresa que opera o no. Dois enderecos do mesmo dono (os dois servidores da |
| 392 | /// Ripple) contam como um so no consenso: um dono que mente, mente nos dois. |
| 393 | public let operatorName: String |
| 394 | |
| 395 | public init(name: String, baseURL: URL) { |
| 396 | self.init(name: name, baseURL: baseURL, operatorName: name) |
| 397 | } |
| 398 | |
| 399 | public init(name: String, baseURL: URL, operatorName: String) { |
| 400 | self.name = name |
| 401 | self.baseURL = baseURL |
| 402 | self.operatorName = operatorName |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | public let providers: [Provider] |
| 407 | private var failures: [String: Int] = [:] |
| 408 | private var benchedUntil: [String: Date] = [:] |
| 409 | |
| 410 | /// Sorteia a ordem dos donos a cada consenso (`consensusOrder`). Os leitores de rede ligam pelo transporte |
| 411 | /// (`ReaderTransport.drawsProviders`): no app sim, nos testes com transporte de mentira nao. |
| 412 | public let draws: Bool |
| 413 | |
| 414 | public init(_ providers: [Provider], draws: Bool = false) { |
| 415 | self.providers = Self.spreadingOperators(providers) |
| 416 | self.draws = draws |
| 417 | } |
| 418 | |
| 419 | /// Os provedores disponiveis agora, na ordem de preferencia, com donos diferentes na |
| 420 | /// frente: quem pega os dois primeiros para um consenso pega dois donos. |
| 421 | public func available(now: Date = .now) -> [Provider] { |
| 422 | let live = providers.filter { (benchedUntil[$0.name] ?? .distantPast) <= now } |
| 423 | return Self.spreadingOperators(live.isEmpty ? providers : live) |
| 424 | } |
| 425 | |
| 426 | /// A ordem de um consenso (`Quorum.gather`): os donos diferentes na frente, sorteados a cada pergunta pelo gerador do |
| 427 | /// sistema (o CSPRNG do aparelho), e as repeticoes depois. Na ordem fixa, quem quisesse forjar um recibo, um saldo |
| 428 | /// ou um nonce sabia de antemao quais duas empresas pressionar: as duas primeiras da lista decidiam sozinhas toda |
| 429 | /// vez. Sorteado, o par pressionado so responde sozinho uma vez em tres (tres donos) ou em seis (quatro), e no resto |
| 430 | /// um honesto entra na primeira onda (auditoria 8, 14/11/2026). |
| 431 | public nonisolated func consensusOrder(_ list: [Provider]) -> [Provider] { |
| 432 | let spread = Self.spreadingOperators(list) |
| 433 | guard draws else { return spread } |
| 434 | var seen = Set<String>() |
| 435 | let distinct = spread.filter { seen.insert($0.operatorName).inserted } |
| 436 | var generator = SystemRandomNumberGenerator() |
| 437 | return distinct.shuffled(using: &generator) + spread.dropFirst(distinct.count) |
| 438 | } |
| 439 | |
| 440 | /// A mesma ordem, mas cada dono aparece uma vez antes de qualquer repeticao. |
| 441 | static func spreadingOperators(_ providers: [Provider]) -> [Provider] { |
| 442 | var seen = Set<String>() |
| 443 | var first: [Provider] = [] |
| 444 | var repeated: [Provider] = [] |
| 445 | for provider in providers { |
| 446 | if seen.insert(provider.operatorName).inserted { first.append(provider) } else { repeated.append(provider) } |
| 447 | } |
| 448 | return first + repeated |
| 449 | } |
| 450 | |
| 451 | public func reportSuccess(_ provider: Provider) { |
| 452 | failures[provider.name] = 0 |
| 453 | } |
| 454 | |
| 455 | public func reportFailure(_ provider: Provider, now: Date = .now) { |
| 456 | // A consulta cortada por quem pediu (cancelada, ou a tela de segredo que abriu e silenciou a rede) nao e falha do |
| 457 | // operador: contada, punha no banco quem respondia, e a conferencia seguinte ficava com menos de tres (rodada 4). |
| 458 | guard !Task.isCancelled, !HTTPClient.shared.isQuiet else { return } |
| 459 | let count = (failures[provider.name] ?? 0) + 1 |
| 460 | failures[provider.name] = count |
| 461 | if count >= 3 { |
| 462 | benchedUntil[provider.name] = now.addingTimeInterval(60) |
| 463 | failures[provider.name] = 0 |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | /// A falha com o motivo. Recusa por limite vai direto para o banco, por mais tempo: |
| 468 | /// insistir num provedor que ja disse "chega" so prolonga o bloqueio do IP (a |
| 469 | /// Blockchair passa do 429 ao 430, "IP temporary blacklisted"). O resto segue a regra |
| 470 | /// das tres falhas seguidas. |
| 471 | public func reportFailure(_ provider: Provider, error: Error, now: Date = .now) { |
| 472 | guard !Task.isCancelled, !HTTPClient.shared.isQuiet else { return } |
| 473 | guard let pause = Self.benchTime(for: error) else { return reportFailure(provider, now: now) } |
| 474 | let until = now.addingTimeInterval(pause) |
| 475 | benchedUntil[provider.name] = max(benchedUntil[provider.name] ?? until, until) |
| 476 | failures[provider.name] = 0 |
| 477 | } |
| 478 | |
| 479 | /// Quanto tempo cada recusa deixa o provedor de fora. 429 e o limite por IP; 430 |
| 480 | /// (Blockchair) e 403 (Cloudflare) sao bloqueio do IP, mais demorado; um provedor |
| 481 | /// fora do ar custa o timeout inteiro a cada pergunta. |
| 482 | public static func benchTime(for error: Error) -> TimeInterval? { |
| 483 | switch error as? HTTPClient.Failure { |
| 484 | case .status(429): return 5 * 60 |
| 485 | case .status(430), .status(403): return 15 * 60 |
| 486 | case .timeout: return 2 * 60 |
| 487 | default: return nil |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | /// So para os testes e para a tela: ate quando o provedor esta no banco. |
| 492 | public func benched(_ provider: Provider) -> Date? { benchedUntil[provider.name] } |
| 493 | |
| 494 | /// Tenta cada provedor em ordem ate um responder. |
| 495 | public func first<T: Sendable>(_ operation: @Sendable (Provider) async throws -> T) async throws -> T { |
| 496 | var lastError: Error = HTTPClient.Failure.offline |
| 497 | for provider in available() { |
| 498 | do { |
| 499 | let value = try await operation(provider) |
| 500 | reportSuccess(provider) |
| 501 | return value |
| 502 | } catch { |
| 503 | reportFailure(provider) |
| 504 | lastError = error |
| 505 | } |
| 506 | } |
| 507 | throw lastError |
| 508 | } |
| 509 | |
| 510 | /// Pergunta a provedores distintos e exige que dois concordem. Nonce, sequence e |
| 511 | /// saldo que vao para uma transacao passam por aqui (docs/seguranca.md §5.5). |
| 512 | /// |
| 513 | /// Nunca aceita uma resposta so: com menos de dois provedores respondendo, falha. |
| 514 | /// Os que estao no banco do circuit breaker entram no fim da fila, porque um |
| 515 | /// consenso que so tem um provedor vivo nao e consenso. Dois enderecos do mesmo |
| 516 | /// dono valem uma resposta so. |
| 517 | public func agreeing<T: Sendable & Equatable>(_ operation: @Sendable (Provider) async throws -> T) async throws -> T { |
| 518 | let live = available() |
| 519 | let candidates = Self.spreadingOperators(live + providers.filter { !live.contains($0) }) |
| 520 | var answers: [(operatorName: String, value: T)] = [] |
| 521 | for provider in candidates where !answers.contains(where: { $0.operatorName == provider.operatorName }) { |
| 522 | do { |
| 523 | let value = try await operation(provider) |
| 524 | reportSuccess(provider) |
| 525 | if answers.contains(where: { $0.value == value }) { return value } |
| 526 | answers.append((provider.operatorName, value)) |
| 527 | } catch { |
| 528 | reportFailure(provider) |
| 529 | } |
| 530 | } |
| 531 | throw ConsensusFailure(answers: answers.count) |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | public struct ConsensusFailure: Error, Sendable { |
| 536 | public let answers: Int |
| 537 | } |
| 538 | |
| 539 | /// JSON-RPC 2.0 sobre HTTPS. |
| 540 | public struct JSONRPC: Sendable { |
| 541 | public struct RPCError: Error, Sendable, Decodable { |
| 542 | public let code: Int |
| 543 | public let message: String |
| 544 | } |
| 545 | |
| 546 | private struct Envelope<T: Decodable>: Decodable { |
| 547 | let result: T? |
| 548 | let error: RPCError? |
| 549 | } |
| 550 | |
| 551 | public static func call<T: Decodable>(_ url: URL, method: String, params: [JSONValue], as type: T.Type, client: HTTPClient = .shared) async throws -> T { |
| 552 | let body: [String: JSONValue] = [ |
| 553 | "jsonrpc": .string("2.0"), "id": .number(1), "method": .string(method), "params": .array(params), |
| 554 | ] |
| 555 | let data = try await client.post(url, json: try JSONEncoder().encode(body)) |
| 556 | let envelope: Envelope<T> |
| 557 | do { envelope = try JSONDecoder().decode(Envelope<T>.self, from: data) } catch { throw HTTPClient.Failure.decoding(method) } |
| 558 | if let error = envelope.error { throw error } |
| 559 | guard let result = envelope.result else { throw HTTPClient.Failure.invalidResponse } |
| 560 | return result |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | /// Um valor JSON qualquer, para montar parametros sem `[String: Any]`. |
| 565 | public enum JSONValue: Codable, Sendable, Equatable { |
| 566 | case string(String) |
| 567 | case number(Double) |
| 568 | case bool(Bool) |
| 569 | case array([JSONValue]) |
| 570 | case object([String: JSONValue]) |
| 571 | case null |
| 572 | |
| 573 | public func encode(to encoder: Encoder) throws { |
| 574 | var container = encoder.singleValueContainer() |
| 575 | switch self { |
| 576 | case .string(let value): try container.encode(value) |
| 577 | case .number(let value): |
| 578 | if value == value.rounded(), abs(value) < 1e15 { try container.encode(Int64(value)) } else { try container.encode(value) } |
| 579 | case .bool(let value): try container.encode(value) |
| 580 | case .array(let value): try container.encode(value) |
| 581 | case .object(let value): try container.encode(value) |
| 582 | case .null: try container.encodeNil() |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | public init(from decoder: Decoder) throws { |
| 587 | let container = try decoder.singleValueContainer() |
| 588 | if container.decodeNil() { self = .null } |
| 589 | else if let value = try? container.decode(Bool.self) { self = .bool(value) } |
| 590 | else if let value = try? container.decode(Double.self) { self = .number(value) } |
| 591 | else if let value = try? container.decode(String.self) { self = .string(value) } |
| 592 | else if let value = try? container.decode([JSONValue].self) { self = .array(value) } |
| 593 | else { self = .object(try container.decode([String: JSONValue].self)) } |
| 594 | } |
| 595 | |
| 596 | public var stringValue: String? { if case .string(let v) = self { return v }; return nil } |
| 597 | public var doubleValue: Double? { if case .number(let v) = self { return v }; return nil } |
| 598 | public var boolValue: Bool? { if case .bool(let v) = self { return v }; return nil } |
| 599 | public subscript(key: String) -> JSONValue? { if case .object(let o) = self { return o[key] }; return nil } |
| 600 | public subscript(index: Int) -> JSONValue? { |
| 601 | if case .array(let a) = self, a.indices.contains(index) { return a[index] } |
| 602 | return nil |
| 603 | } |
| 604 | public var arrayValue: [JSONValue]? { if case .array(let a) = self { return a }; return nil } |
| 605 | } |
| 606 | |
| 607 | #if DEBUG |
| 608 | /// So no build de teste: as ultimas falhas de rede (host e motivo), para a tela dizer |
| 609 | /// por que uma leitura falhou no iPhone de quem testa. Fica so na memoria, sem endereco |
| 610 | /// nem corpo de resposta, e o build de distribuicao nem compila isto. |
| 611 | public final class NetworkDiagnostics: @unchecked Sendable { |
| 612 | public static let shared = NetworkDiagnostics() |
| 613 | |
| 614 | private let lock = NSLock() |
| 615 | private var entries: [(host: String, reason: String, at: Date)] = [] |
| 616 | |
| 617 | /// A recusa do app (status, tamanho, redirecionamento) ou o codigo do URLError. Pedido |
| 618 | /// cancelado (a tela saiu, a leitura foi trocada) nao e falha de rede e nao entra. |
| 619 | func record(host: String, failure: HTTPClient.Failure?, error: Error?) { |
| 620 | let reason: String |
| 621 | if let failure { |
| 622 | reason = String(describing: failure) |
| 623 | } else if let error = error as? URLError { |
| 624 | guard error.code != .cancelled else { return } |
| 625 | reason = "URLError \(error.code.rawValue)" |
| 626 | } else if let error { |
| 627 | reason = String(describing: type(of: error)) |
| 628 | } else { |
| 629 | return |
| 630 | } |
| 631 | lock.withLock { |
| 632 | entries.append((host, reason, .now)) |
| 633 | if entries.count > 80 { entries.removeFirst(entries.count - 80) } |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | /// "host: motivo (n)" de cada falha dos ultimos `seconds` segundos. |
| 638 | public func recent(seconds: TimeInterval = 180) -> [String] { |
| 639 | let since = Date.now.addingTimeInterval(-seconds) |
| 640 | let recent = lock.withLock { entries.filter { $0.at >= since } } |
| 641 | var counts: [String: Int] = [:] |
| 642 | var order: [String] = [] |
| 643 | for entry in recent { |
| 644 | let key = "\(entry.host): \(entry.reason)" |
| 645 | if counts[key] == nil { order.append(key) } |
| 646 | counts[key, default: 0] += 1 |
| 647 | } |
| 648 | return order.map { "\($0) (\(counts[$0] ?? 0))" } |
| 649 | } |
| 650 | } |
| 651 | #endif |