session-ios/SignalServiceKit/src/Loki/API/LokiAPI.swift

191 lines
8.7 KiB
Swift
Raw Normal View History

2019-04-30 06:27:39 +02:00
import PromiseKit
2019-05-08 01:29:07 +02:00
@objc public final class LokiAPI : NSObject {
2019-05-21 07:21:51 +02:00
private static let storage = OWSPrimaryStorage.shared()
2019-04-30 06:27:39 +02:00
2019-05-21 05:44:46 +02:00
// MARK: Settings
2019-05-08 01:29:07 +02:00
private static let version = "v1"
2019-05-21 08:40:31 +02:00
private static let defaultSnodePort: UInt16 = 8080
2019-05-21 05:26:51 +02:00
private static let targetSnodeCount = 2
2019-05-08 01:29:07 +02:00
public static let defaultMessageTTL: UInt64 = 4 * 24 * 60 * 60
2019-04-30 06:27:39 +02:00
// MARK: Caching
private static var swarmCache: [String:[Target]] = [:]
2019-04-30 06:27:39 +02:00
// MARK: Types
2019-05-21 08:40:31 +02:00
private struct Target : Hashable {
2019-05-07 07:03:54 +02:00
let address: String
let port: UInt16
2019-05-21 05:26:51 +02:00
enum Method : String {
case getSwarm = "get_snodes_for_pubkey"
case getMessages = "retrieve"
case sendMessage = "store"
}
2019-05-07 07:03:54 +02:00
}
2019-05-07 05:53:31 +02:00
public typealias RawResponse = Any
2019-04-30 06:27:39 +02:00
2019-05-07 02:10:15 +02:00
public enum Error : LocalizedError {
case proofOfWorkCalculationFailed
public var errorDescription: String? {
switch self {
case .proofOfWorkCalculationFailed: return NSLocalizedString("Failed to calculate proof of work.", comment: "")
}
}
}
2019-04-30 06:27:39 +02:00
// MARK: Lifecycle
2019-05-06 08:13:32 +02:00
override private init() { }
2019-04-30 06:27:39 +02:00
2019-05-21 05:26:51 +02:00
// MARK: Internal API
private static func invoke(_ method: Target.Method, on target: Target, with parameters: [String:Any] = [:]) -> Promise<RawResponse> {
2019-05-08 01:29:07 +02:00
let url = URL(string: "\(target.address):\(target.port)/\(version)/storage_rpc")!
2019-04-30 06:27:39 +02:00
let request = TSRequest(url: url, method: "POST", parameters: [ "method" : method.rawValue, "params" : parameters ])
2019-05-07 05:53:31 +02:00
return TSNetworkManager.shared().makePromise(request: request).map { $0.responseObject }
2019-04-30 06:27:39 +02:00
}
2019-05-07 02:29:44 +02:00
2019-05-21 05:26:51 +02:00
private static func getRandomSnode() -> Promise<Target> {
2019-05-21 07:21:51 +02:00
return Promise<Target> { _ in notImplemented() } // TODO: Implement
2019-04-30 06:27:39 +02:00
}
private static func getSwarm(for hexEncodedPublicKey: String) -> Promise<[Target]> {
2019-05-21 05:44:46 +02:00
if let cachedSwarm = swarmCache[hexEncodedPublicKey], cachedSwarm.count >= targetSnodeCount {
return Promise<[Target]> { $0.fulfill(cachedSwarm) }
2019-05-21 05:44:46 +02:00
} else {
let parameters: [String:Any] = [ "pubKey" : hexEncodedPublicKey ]
return getRandomSnode().then { invoke(.getSwarm, on: $0, with: parameters) }.map { parseTargets(from: $0) }.get { swarmCache[hexEncodedPublicKey] = $0 }
2019-05-21 05:44:46 +02:00
}
2019-05-21 05:26:51 +02:00
}
private static func getTargetSnodes(for hexEncodedPublicKey: String) -> Promise<[Target]> {
// shuffled() uses the system's default random generator, which is cryptographically secure
return getSwarm(for: hexEncodedPublicKey).map { Array($0.shuffled().prefix(targetSnodeCount)) }
2019-05-21 05:26:51 +02:00
}
// MARK: Public API
public static func getMessages() -> Promise<Set<Promise<[SSKProtoEnvelope]>>> {
2019-05-21 05:26:51 +02:00
let hexEncodedPublicKey = OWSIdentityManager.shared().identityKeyPair()!.hexEncodedPublicKey
return getTargetSnodes(for: hexEncodedPublicKey).mapValues { targetSnode in
let lastHash = getLastMessageHashValue(for: targetSnode) ?? ""
2019-05-21 05:48:42 +02:00
let parameters: [String:Any] = [ "pubKey" : hexEncodedPublicKey, "lastHash" : lastHash ]
2019-05-21 07:21:51 +02:00
return invoke(.getMessages, on: targetSnode, with: parameters).map { rawResponse in
guard let json = rawResponse as? JSON, let rawMessages = json["messages"] as? [JSON] else { return [] }
updateLastMessageHashValueIfPossible(for: targetSnode, from: rawMessages)
let newRawMessages = removeDuplicates(from: rawMessages)
return parseProtoEnvelopes(from: newRawMessages)
2019-05-21 05:48:42 +02:00
}
2019-05-21 08:40:31 +02:00
}.map { Set($0) }
2019-05-07 08:03:57 +02:00
}
public static func sendMessage(_ lokiMessage: Message) -> Promise<Set<Promise<RawResponse>>> {
2019-05-21 08:40:31 +02:00
let parameters = lokiMessage.toJSON()
return getTargetSnodes(for: lokiMessage.destination).mapValues { invoke(.sendMessage, on: $0, with: parameters).recoverNetworkErrorIfNeeded(on: DispatchQueue.global()) }.map { Set($0) }
2019-05-07 08:03:57 +02:00
}
public static func ping(_ hexEncodedPublicKey: String) -> Promise<Set<Promise<RawResponse>>> {
2019-05-21 08:40:31 +02:00
let parameters: [String:Any] = [ "pubKey" : hexEncodedPublicKey ] // TODO: Figure out correct parameters
return getTargetSnodes(for: hexEncodedPublicKey).mapValues { invoke(.sendMessage, on: $0, with: parameters).recoverNetworkErrorIfNeeded(on: DispatchQueue.global()) }.map { Set($0) }
2019-05-08 02:04:19 +02:00
}
2019-05-21 05:26:51 +02:00
// MARK: Public API (Obj-C)
@objc public static func objc_sendSignalMessage(_ signalMessage: SignalMessage, to destination: String, timestamp: UInt64, requiringPoW isPoWRequired: Bool) -> AnyPromise {
2019-05-21 08:40:31 +02:00
let promise = Message.from(signalMessage: signalMessage, timestamp: timestamp, requiringPoW: isPoWRequired).then(sendMessage)
let anyPromise = AnyPromise(promise)
anyPromise.retainUntilComplete()
return anyPromise
2019-05-07 02:29:44 +02:00
}
2019-05-21 05:26:51 +02:00
// MARK: Parsing
// The parsing utilities below use a best attempt approach to parsing; they warn for parsing failures but don't throw exceptions.
private static func parseTargets(from rawResponse: Any) -> [Target] {
guard let json = rawResponse as? JSON, let addresses = json["snodes"] as? [String] else {
Logger.warn("[Loki] Failed to parse targets from: \(rawResponse).")
return []
2019-05-21 07:21:51 +02:00
}
return addresses.map { Target(address: $0, port: defaultSnodePort) }
2019-05-21 07:21:51 +02:00
}
private static func updateLastMessageHashValueIfPossible(for target: Target, from rawMessages: [JSON]) {
guard let lastMessage = rawMessages.last, let hashValue = lastMessage["hash"] as? String, let expiresAt = lastMessage["expiration"] as? Int else {
Logger.warn("[Loki] Failed to update last message hash value from: \(rawMessages).")
return
2019-05-21 07:21:51 +02:00
}
setLastMessageHashValue(for: target, hashValue: hashValue, expiresAt: UInt64(expiresAt))
2019-05-21 07:21:51 +02:00
}
private static func removeDuplicates(from rawMessages: [JSON]) -> [JSON] {
var receivedMessageHashValues = getReceivedMessageHashValues()
return rawMessages.filter { rawMessage in
guard let hashValue = rawMessage["hash"] as? String else {
Logger.warn("[Loki] Missing hash value for message: \(rawMessage).")
return false
}
let isDuplicate = receivedMessageHashValues.contains(hashValue)
receivedMessageHashValues.insert(hashValue)
setReceivedMessageHashValues(to: receivedMessageHashValues)
return !isDuplicate
}
2019-05-21 07:21:51 +02:00
}
private static func parseProtoEnvelopes(from rawMessages: [JSON]) -> [SSKProtoEnvelope] {
return rawMessages.compactMap { rawMessage in
guard let base64EncodedData = rawMessage["data"] as? String, let data = Data(base64Encoded: base64EncodedData) else {
Logger.warn("[Loki] Failed to decode data for message: \(rawMessage).")
2019-05-21 05:26:51 +02:00
return nil
}
guard let envelope = try? unwrap(data: data) else {
Logger.warn("[Loki] Failed to unwrap data for message: \(rawMessage).")
2019-05-21 05:26:51 +02:00
return nil
}
return envelope
}
}
// MARK: Convenience
private static func getLastMessageHashValue(for target: Target) -> String? {
var result: String? = nil
// Uses a read/write connection because getting the last message hash value also removes expired messages as needed
storage.dbReadWriteConnection.readWrite { transaction in
result = storage.getLastMessageHash(forServiceNode: target.address, transaction: transaction)
}
return result
}
private static func setLastMessageHashValue(for target: Target, hashValue: String, expiresAt: UInt64) {
storage.dbReadWriteConnection.readWrite { transaction in
storage.setLastMessageHash(forServiceNode: target.address, hash: hashValue, expiresAt: expiresAt, transaction: transaction)
}
}
private static func getReceivedMessageHashValues() -> Set<String> {
var result: Set<String> = []
storage.dbReadConnection.read { transaction in
result = storage.getReceivedMessageHashes(with: transaction)
}
return result
}
private static func setReceivedMessageHashValues(to receivedMessageHashValues: Set<String>) {
storage.dbReadWriteConnection.readWrite { transaction in
storage.setReceivedMessageHashes(receivedMessageHashValues, with: transaction)
}
2019-05-21 05:26:51 +02:00
}
2019-04-30 06:27:39 +02:00
}
2019-05-08 08:02:53 +02:00
// MARK: Error Handling
private extension Promise {
2019-05-08 08:02:53 +02:00
2019-05-21 03:40:29 +02:00
func recoverNetworkErrorIfNeeded(on queue: DispatchQueue) -> Promise<T> {
2019-05-21 05:44:46 +02:00
return recover(on: queue) { error -> Promise<T> in
2019-05-08 08:02:53 +02:00
switch error {
2019-05-21 03:40:29 +02:00
case NetworkManagerError.taskError(_, let underlyingError): throw underlyingError
default: throw error
2019-05-08 08:02:53 +02:00
}
}
}
}