diff --git a/SignalServiceKit/src/Account/PreKeyRefreshOperation.swift b/SignalServiceKit/src/Account/PreKeyRefreshOperation.swift index f6eeb9c5c..d859dfa7a 100644 --- a/SignalServiceKit/src/Account/PreKeyRefreshOperation.swift +++ b/SignalServiceKit/src/Account/PreKeyRefreshOperation.swift @@ -39,7 +39,7 @@ public class RefreshPreKeysOperation: OWSOperation { // Loki: Doing this on the global queue to match Signal DispatchQueue.global().async { guard self.primaryStorage.currentSignedPrekeyId() == nil else { - print("[Loki] Using existing signed pre key.") + print("[Loki] Skipping pre key refresh; using existing signed pre key.") return self.reportSuccess() } diff --git a/SignalServiceKit/src/Loki/API/LokiAPI+SwarmAPI.swift b/SignalServiceKit/src/Loki/API/LokiAPI+SwarmAPI.swift index 3550444e8..ac45f7091 100644 --- a/SignalServiceKit/src/Loki/API/LokiAPI+SwarmAPI.swift +++ b/SignalServiceKit/src/Loki/API/LokiAPI+SwarmAPI.swift @@ -12,8 +12,6 @@ public extension LokiAPI { // MARK: Caching internal static var swarmCache: [String:[LokiAPITarget]] = [:] - private static let swarmCacheKey = "swarmCacheKey" - private static let swarmCacheCollection = "swarmCacheCollection" internal static func dropIfNeeded(_ target: LokiAPITarget, hexEncodedPublicKey: String) { let swarm = LokiAPI.swarmCache[hexEncodedPublicKey] diff --git a/SignalServiceKit/src/Loki/API/LokiAPI.swift b/SignalServiceKit/src/Loki/API/LokiAPI.swift index 73763e2a7..a093c22c5 100644 --- a/SignalServiceKit/src/Loki/API/LokiAPI.swift +++ b/SignalServiceKit/src/Loki/API/LokiAPI.swift @@ -2,9 +2,26 @@ import PromiseKit @objc(LKAPI) public final class LokiAPI : NSObject { + /// Only ever modified from the message processing queue (`OWSBatchMessageProcessor.processingQueue`). private static var syncMessageTimestamps: [String:Set] = [:] - public static var lastDeviceLinkUpdate: [String:Date] = [:] // Hex encoded public key to date - @objc public static var userHexEncodedPublicKeyCache: [String:Set] = [:] // Thread ID to set of user hex encoded public keys + + public static var _lastDeviceLinkUpdate: [String:Date] = [:] + /// A mapping from hex encoded public key to date updated. + public static var lastDeviceLinkUpdate: [String:Date] { + get { stateQueue.sync { _lastDeviceLinkUpdate } } + set { stateQueue.sync { _lastDeviceLinkUpdate = newValue } } + } + + private static var _userHexEncodedPublicKeyCache: [String:Set] = [:] + /// A mapping from thread ID to set of user hex encoded public keys. + @objc public static var userHexEncodedPublicKeyCache: [String:Set] { + get { stateQueue.sync { _userHexEncodedPublicKeyCache } } + set { stateQueue.sync { _userHexEncodedPublicKeyCache = newValue } } + } + + private static let stateQueue = DispatchQueue(label: "stateQueue") + + /// All service node related errors must be handled on this queue to avoid race conditions maintaining e.g. failure counts. public static let errorHandlingQueue = DispatchQueue(label: "errorHandlingQueue") // MARK: Convenience @@ -12,12 +29,10 @@ public final class LokiAPI : NSObject { internal static let userHexEncodedPublicKey = getUserHexEncodedPublicKey() // MARK: Settings - private static let version = "v1" + private static let apiVersion = "v1" private static let maxRetryCount: UInt = 8 private static let defaultTimeout: TimeInterval = 20 private static let longPollingTimeout: TimeInterval = 40 - private static let receivedMessageHashValuesKey = "receivedMessageHashValuesKey" - private static let receivedMessageHashValuesCollection = "receivedMessageHashValuesCollection" private static var userIDScanLimit: UInt = 4096 internal static var powDifficulty: UInt = 4 public static let defaultMessageTTL: UInt64 = 24 * 60 * 60 * 1000 @@ -69,6 +84,7 @@ public final class LokiAPI : NSObject { } public typealias MessageListPromise = Promise<[SSKProtoEnvelope]> + public typealias RawResponsePromise = Promise // MARK: Lifecycle @@ -77,7 +93,7 @@ public final class LokiAPI : NSObject { // MARK: Internal API internal static func invoke(_ method: LokiAPITarget.Method, on target: LokiAPITarget, associatedWith hexEncodedPublicKey: String, parameters: [String:Any], headers: [String:String]? = nil, timeout: TimeInterval? = nil) -> RawResponsePromise { - let url = URL(string: "\(target.address):\(target.port)/storage_rpc/\(version)")! + let url = URL(string: "\(target.address):\(target.port)/storage_rpc/\(apiVersion)")! let request = TSRequest(url: url, method: "POST", parameters: [ "method" : method.rawValue, "params" : parameters ]) if let headers = headers { request.allHTTPHeaderFields = headers } request.timeoutInterval = timeout ?? defaultTimeout @@ -310,7 +326,10 @@ public final class LokiAPI : NSObject { storage.setLastMessageHash(forServiceNode: target.address, hash: hashValue, expiresAt: expirationDate, transaction: transaction) } } - + + private static let receivedMessageHashValuesKey = "receivedMessageHashValuesKey" + private static let receivedMessageHashValuesCollection = "receivedMessageHashValuesCollection" + private static func getReceivedMessageHashValues() -> Set? { var result: Set? = nil storage.dbReadConnection.read { transaction in diff --git a/SignalServiceKit/src/Loki/API/LokiSnodeProxy.swift b/SignalServiceKit/src/Loki/API/LokiSnodeProxy.swift index 1f55d8ca5..7264254b8 100644 --- a/SignalServiceKit/src/Loki/API/LokiSnodeProxy.swift +++ b/SignalServiceKit/src/Loki/API/LokiSnodeProxy.swift @@ -75,7 +75,7 @@ internal class LokiSnodeProxy : LokiHTTPClient { let response = try DiffieHellman.decrypt(cipherText, using: symmetricKey) let uncheckedJSON = try? JSONSerialization.jsonObject(with: response, options: .allowFragments) as? JSON guard let json = uncheckedJSON, let statusCode = json["status"] as? Int else { throw HTTPError.networkError(code: -1, response: nil, underlyingError: Error.proxyResponseParsingFailed) } - let isSuccess = (200..<300).contains(statusCode) + let isSuccess = (200...299) ~= statusCode var body: Any? = nil if let bodyAsString = json["body"] as? String { body = bodyAsString diff --git a/SignalServiceKit/src/Loki/API/SignalMessage.swift b/SignalServiceKit/src/Loki/API/SignalMessage.swift index d2799dc7d..4ba772320 100644 --- a/SignalServiceKit/src/Loki/API/SignalMessage.swift +++ b/SignalServiceKit/src/Loki/API/SignalMessage.swift @@ -15,7 +15,7 @@ public final class SignalMessage : NSObject { public var ttl: UInt64? { return objc_ttl != 0 ? objc_ttl : nil } @objc public init(type: SSKProtoEnvelope.SSKProtoEnvelopeType, timestamp: UInt64, senderID: String, senderDeviceID: UInt32, - content: String, recipientID: String, ttl: UInt64, isPing: Bool, isFriendRequest: Bool) { + content: String, recipientID: String, ttl: UInt64, isPing: Bool, isFriendRequest: Bool) { self.type = type self.timestamp = timestamp self.senderID = senderID diff --git a/SignalServiceKit/src/Loki/Shelved/LokiP2PAPI.swift b/SignalServiceKit/src/Loki/Shelved/LokiP2PAPI.swift index 69887139a..b0b4edbea 100644 --- a/SignalServiceKit/src/Loki/Shelved/LokiP2PAPI.swift +++ b/SignalServiceKit/src/Loki/Shelved/LokiP2PAPI.swift @@ -200,7 +200,7 @@ public class LokiP2PAPI : NSObject { AssertIsOnMainThread() guard let message = onlineBroadcastMessage(forThread: thread) else { - print("[Loki] P2P address not set.") +// print("[Loki] P2P address not set.") return } @@ -224,7 +224,7 @@ public class LokiP2PAPI : NSObject { private static func createLokiAddressMessage(for thread: TSThread, isPing: Bool) -> LokiAddressMessage? { guard let ourAddress = ourP2PAddress else { - print("[Loki] P2P address not set.") +// print("[Loki] P2P address not set.") return nil }