|
| 1 | +import Foundation |
| 2 | + |
| 3 | +/// Minimal JSON-RPC client for dashd, covering only the calls the |
| 4 | +/// integration framework needs. |
| 5 | +struct CoreRPCClient { |
| 6 | + private(set) var url: URL |
| 7 | + let username: String |
| 8 | + let password: String |
| 9 | + |
| 10 | + init(port: Int, username: String, password: String) { |
| 11 | + var components = URLComponents() |
| 12 | + components.scheme = "http" |
| 13 | + components.host = "127.0.0.1" |
| 14 | + components.port = port |
| 15 | + guard let url = components.url else { |
| 16 | + preconditionFailure("Invalid Core RPC port: \(port)") |
| 17 | + } |
| 18 | + self.url = url |
| 19 | + self.username = username |
| 20 | + self.password = password |
| 21 | + } |
| 22 | + |
| 23 | + // MARK: - Typed methods |
| 24 | + |
| 25 | + /// Throws RPC error -32601 if dashd was built without the miner. |
| 26 | + @discardableResult |
| 27 | + func generateToAddress(count: Int, address: String) async throws -> [String] { |
| 28 | + try await call("generatetoaddress", params: [.int(count), .string(address)]) |
| 29 | + } |
| 30 | + |
| 31 | + func getNewAddress(walletName: String = "main") async throws -> String { |
| 32 | + try await wallet(walletName).call("getnewaddress") |
| 33 | + } |
| 34 | + |
| 35 | + /// `amount` is in DASH (not duffs). Returns the txid. |
| 36 | + @discardableResult |
| 37 | + func sendToAddress(amount: Double, address: String, walletName: String = "main") async throws -> String { |
| 38 | + try await wallet(walletName).call( |
| 39 | + "sendtoaddress", |
| 40 | + params: [.string(address), .double(amount)] |
| 41 | + ) |
| 42 | + } |
| 43 | + |
| 44 | + /// Switches to the per-wallet RPC endpoint (`/wallet/<name>`). |
| 45 | + func wallet(_ name: String) -> CoreRPCClient { |
| 46 | + var copy = self |
| 47 | + copy.url = url.appendingPathComponent("wallet").appendingPathComponent(name) |
| 48 | + return copy |
| 49 | + } |
| 50 | + |
| 51 | + // MARK: - Generic JSON-RPC |
| 52 | + |
| 53 | + enum Param: Sendable { |
| 54 | + case string(String) |
| 55 | + case int(Int) |
| 56 | + case double(Double) |
| 57 | + } |
| 58 | + |
| 59 | + enum RPCError: Error, CustomStringConvertible { |
| 60 | + case http(Int) |
| 61 | + case rpc(code: Int, message: String) |
| 62 | + case decode(String) |
| 63 | + |
| 64 | + var description: String { |
| 65 | + switch self { |
| 66 | + case let .http(code): return "HTTP \(code)" |
| 67 | + case let .rpc(code, msg): return "RPC error \(code): \(msg)" |
| 68 | + case let .decode(msg): return "Decode error: \(msg)" |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + func call<T: Decodable>(_ method: String, params: [Param] = []) async throws -> T { |
| 74 | + var request = URLRequest(url: url) |
| 75 | + request.httpMethod = "POST" |
| 76 | + request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 77 | + |
| 78 | + let credentials = "\(username):\(password)".data(using: .utf8)!.base64EncodedString() |
| 79 | + request.setValue("Basic \(credentials)", forHTTPHeaderField: "Authorization") |
| 80 | + |
| 81 | + let body: [String: Any] = [ |
| 82 | + "jsonrpc": "1.0", |
| 83 | + "id": "swift-integration", |
| 84 | + "method": method, |
| 85 | + "params": encodeParams(params), |
| 86 | + ] |
| 87 | + request.httpBody = try JSONSerialization.data(withJSONObject: body) |
| 88 | + |
| 89 | + let (data, response) = try await URLSession.shared.data(for: request) |
| 90 | + // dashd returns the RPC error in the body even on 500; only |
| 91 | + // bail on HTTP errors if we can't parse the JSON-RPC body. |
| 92 | + if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) { |
| 93 | + if let decoded = try? decodeRPCResponse(data, T.self) { |
| 94 | + return try unwrap(decoded) |
| 95 | + } |
| 96 | + throw RPCError.http(http.statusCode) |
| 97 | + } |
| 98 | + let decoded = try decodeRPCResponse(data, T.self) |
| 99 | + return try unwrap(decoded) |
| 100 | + } |
| 101 | + |
| 102 | + private func decodeRPCResponse<T: Decodable>(_ data: Data, _: T.Type) throws -> RPCResponse<T> { |
| 103 | + do { |
| 104 | + return try JSONDecoder().decode(RPCResponse<T>.self, from: data) |
| 105 | + } catch { |
| 106 | + let raw = String(data: data, encoding: .utf8) ?? "<non-utf8>" |
| 107 | + throw RPCError.decode("\(error) — body: \(raw)") |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + private func unwrap<T: Decodable>(_ response: RPCResponse<T>) throws -> T { |
| 112 | + if let error = response.error { |
| 113 | + throw RPCError.rpc(code: error.code, message: error.message) |
| 114 | + } |
| 115 | + guard let result = response.result else { |
| 116 | + throw RPCError.decode("RPC response had neither `result` nor `error`") |
| 117 | + } |
| 118 | + return result |
| 119 | + } |
| 120 | + |
| 121 | + private func encodeParams(_ params: [Param]) -> [Any] { |
| 122 | + params.map { param -> Any in |
| 123 | + switch param { |
| 124 | + case let .string(s): return s |
| 125 | + case let .int(i): return i |
| 126 | + case let .double(d): return d |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + private struct RPCResponse<T: Decodable>: Decodable { |
| 132 | + let result: T? |
| 133 | + let error: RPCErrorBody? |
| 134 | + } |
| 135 | + |
| 136 | + private struct RPCErrorBody: Decodable { |
| 137 | + let code: Int |
| 138 | + let message: String |
| 139 | + } |
| 140 | +} |
0 commit comments