diff --git a/Session/Meta/Signal-Bridging-Header.h b/Session/Meta/Signal-Bridging-Header.h index 1d91d3eaa..90efdb6ce 100644 --- a/Session/Meta/Signal-Bridging-Header.h +++ b/Session/Meta/Signal-Bridging-Header.h @@ -38,7 +38,6 @@ #import "OWSQRCodeScanningViewController.h" #import "SignalApp.h" #import "UIViewController+Permissions.h" -#import #import #import #import @@ -74,7 +73,6 @@ #import #import #import -#import #import #import #import @@ -88,7 +86,6 @@ #import #import #import -#import #import #import #import diff --git a/Session/Signal/AppDelegate.m b/Session/Signal/AppDelegate.m index ed8040a59..8e69e15a9 100644 --- a/Session/Signal/AppDelegate.m +++ b/Session/Signal/AppDelegate.m @@ -29,7 +29,6 @@ #import #import #import -#import #import #import @@ -72,13 +71,6 @@ static NSTimeInterval launchStartedAt; return [OWSReadReceiptManager sharedManager]; } -- (id)udManager -{ - OWSAssertDebug(SSKEnvironment.shared.udManager); - - return SSKEnvironment.shared.udManager; -} - - (OWSPrimaryStorage *)primaryStorage { OWSAssertDebug(SSKEnvironment.shared.primaryStorage); @@ -377,9 +369,6 @@ static NSTimeInterval launchStartedAt; { OWSAssertIsOnMainThread(); - // Always check prekeys after app launches, and sometimes check on app activation. - [TSPreKeyManager checkPreKeysIfNecessary]; - static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ RTCInitializeSSL(); @@ -525,8 +514,6 @@ static NSTimeInterval launchStartedAt; [self ensureRootViewController]; - [self.udManager setup]; - [self preheatDatabaseViews]; [self.primaryStorage touchDbAsync]; diff --git a/Session/Signal/AppEnvironment.swift b/Session/Signal/AppEnvironment.swift index cfacd98f3..c4981ca22 100644 --- a/Session/Signal/AppEnvironment.swift +++ b/Session/Signal/AppEnvironment.swift @@ -34,9 +34,6 @@ import SignalUtilitiesKit @objc public var pushRegistrationManager: PushRegistrationManager - @objc - public var sessionResetJobQueue: SessionResetJobQueue - @objc public var backup: OWSBackup @@ -71,7 +68,6 @@ import SignalUtilitiesKit self.accountManager = AccountManager() self.notificationPresenter = NotificationPresenter() self.pushRegistrationManager = PushRegistrationManager() - self.sessionResetJobQueue = SessionResetJobQueue() self.backup = OWSBackup() self.backupLazyRestore = BackupLazyRestore() if #available(iOS 10.0, *) { diff --git a/Session/Signal/ConversationView/ConversationViewController.m b/Session/Signal/ConversationView/ConversationViewController.m index cc8f4c1b4..63666af9c 100644 --- a/Session/Signal/ConversationView/ConversationViewController.m +++ b/Session/Signal/ConversationView/ConversationViewController.m @@ -32,7 +32,6 @@ #import "TSGroupThread.h" #import "TSIncomingMessage.h" #import "TSInfoMessage.h" -#import #import "UIFont+OWS.h" #import "UIViewController+Permissions.h" #import @@ -63,7 +62,6 @@ #import #import #import -#import #import #import #import @@ -247,11 +245,6 @@ typedef enum : NSUInteger { #pragma mark - Dependencies -- (OWSSessionResetJobQueue *)sessionResetJobQueue -{ - return AppEnvironment.shared.sessionResetJobQueue; -} - - (OWSAudioSession *)audioSession { return Environment.shared.audioSession; @@ -1525,23 +1518,6 @@ typedef enum : NSUInteger { [alert addAction:[OWSAlerts cancelAction]]; - UIAlertAction *resetSessionAction = [UIAlertAction - actionWithTitle:NSLocalizedString(@"FINGERPRINT_SHRED_KEYMATERIAL_BUTTON", @"") - accessibilityIdentifier:ACCESSIBILITY_IDENTIFIER_WITH_NAME(self, @"reset_session") - style:UIAlertActionStyleDefault - handler:^(UIAlertAction *action) { - if (![self.thread isKindOfClass:[TSContactThread class]]) { - // Corrupt Message errors only appear in contact threads. - OWSLogError(@"Unexpected request to reset session in group thread. Refusing"); - return; - } - TSContactThread *contactThread = (TSContactThread *)self.thread; - [LKStorage writeWithBlock:^(YapDatabaseReadWriteTransaction *_Nonnull transaction) { - [self.sessionResetJobQueue addContactThread:contactThread transaction:transaction]; - }]; - }]; - [alert addAction:resetSessionAction]; - [self dismissKeyBoard]; [self presentAlert:alert]; } diff --git a/Session/Signal/PrivacySettingsTableViewController.m b/Session/Signal/PrivacySettingsTableViewController.m index f4ba3942b..6fb711b9b 100644 --- a/Session/Signal/PrivacySettingsTableViewController.m +++ b/Session/Signal/PrivacySettingsTableViewController.m @@ -56,11 +56,6 @@ static NSString *const kSealedSenderInfoURL = @"https://signal.org/blog/sealed-s #pragma mark - Dependencies -- (id)udManager -{ - return SSKEnvironment.shared.udManager; -} - - (OWSPreferences *)preferences { return Environment.shared.preferences; @@ -291,8 +286,7 @@ static NSString *const kSealedSenderInfoURL = @"https://signal.org/blog/sealed-s - (void)didToggleUDUnrestrictedAccessSwitch:(UISwitch *)sender { - OWSLogInfo(@"toggled to: %@", (sender.isOn ? @"ON" : @"OFF")); - [self.udManager setShouldAllowUnrestrictedAccessLocal:sender.isOn]; + } - (void)didToggleUDShowIndicatorsSwitch:(UISwitch *)sender diff --git a/Session/Signal/SessionResetJob.swift b/Session/Signal/SessionResetJob.swift deleted file mode 100644 index a35f8418c..000000000 --- a/Session/Signal/SessionResetJob.swift +++ /dev/null @@ -1,194 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation -import PromiseKit -import SignalUtilitiesKit - -@objc(OWSSessionResetJobQueue) -public class SessionResetJobQueue: NSObject, SignalUtilitiesKit.JobQueue { - - @objc(addContactThread:transaction:) - public func add(contactThread: TSContactThread, transaction: YapDatabaseReadWriteTransaction) { - let jobRecord = OWSSessionResetJobRecord(contactThread: contactThread, label: self.jobRecordLabel) - self.add(jobRecord: jobRecord, transaction: transaction) - } - - // MARK: JobQueue - - public typealias DurableOperationType = SessionResetOperation - public let jobRecordLabel: String = "SessionReset" - public static let maxRetries: UInt = 10 - public let requiresInternet: Bool = true - public var runningOperations: [SessionResetOperation] = [] - - @objc - public override init() { - super.init() - - AppReadiness.runNowOrWhenAppWillBecomeReady { - self.setup() - } - } - - @objc - public func setup() { - defaultSetup() - } - - public var isSetup: Bool = false - - public func didMarkAsReady(oldJobRecord: JobRecordType, transaction: YapDatabaseReadWriteTransaction) { - // no special handling - } - - let operationQueue: OperationQueue = { - // no need to serialize the operation queuing, since sending will ultimately be serialized by MessageSender - let operationQueue = OperationQueue() - operationQueue.name = "SessionReset.OperationQueue" - return operationQueue - }() - - public func operationQueue(jobRecord: OWSSessionResetJobRecord) -> OperationQueue { - return self.operationQueue - } - - public func buildOperation(jobRecord: OWSSessionResetJobRecord, transaction: YapDatabaseReadTransaction) throws -> SessionResetOperation { - guard let contactThread = TSThread.fetch(uniqueId: jobRecord.contactThreadId, transaction: transaction) as? TSContactThread else { - throw JobError.obsolete(description: "thread for session reset no longer exists") - } - - return SessionResetOperation(contactThread: contactThread, jobRecord: jobRecord) - } -} - -public class SessionResetOperation: OWSOperation, DurableOperation { - - // MARK: DurableOperation - - public let jobRecord: OWSSessionResetJobRecord - - weak public var durableOperationDelegate: SessionResetJobQueue? - - public var operation: OWSOperation { - return self - } - - // MARK: - - let contactThread: TSContactThread - var recipientId: String { - return contactThread.contactIdentifier() - } - - @objc public required init(contactThread: TSContactThread, jobRecord: OWSSessionResetJobRecord) { - self.contactThread = contactThread - self.jobRecord = jobRecord - } - - // MARK: Dependencies - - var dbConnection: YapDatabaseConnection { - return SSKEnvironment.shared.primaryStorage.dbReadWriteConnection - } - - var primaryStorage: OWSPrimaryStorage { - return SSKEnvironment.shared.primaryStorage - } - - // MARK: - - var firstAttempt = true - - override public func run() { - assert(self.durableOperationDelegate != nil) - - /* - let endSessionMessage = EndSessionMessage(timestamp: NSDate.ows_millisecondTimeStamp(), in: self.contactThread) - - firstly { - return self.messageSender.sendPromise(message: endSessionMessage) - }.done { - Logger.info("successfully sent EndSessionMessage.") - Storage.writeSync { transaction in - // Archive the just-created session since the recipient should delete their corresponding - // session upon receiving and decrypting our EndSession message. - // Otherwise if we send another message before them, they wont have the session to decrypt it. - self.primaryStorage.archiveAllSessions(forContact: self.recipientId, protocolContext: transaction) - - /* Loki: Original code - * ================ - let message = TSInfoMessage(timestamp: NSDate.ows_millisecondTimeStamp(), - in: self.contactThread, - messageType: TSInfoMessageType.typeSessionDidEnd) - message.save(with: transaction) - * ================ - */ - - if (self.contactThread.sessionResetStatus != .requestReceived) { - let message = TSInfoMessage(timestamp: NSDate.ows_millisecondTimeStamp(), in: self.contactThread, messageType: .typeLokiSessionResetInProgress) - message.save(with: transaction) - - // Loki: We have initiated a session reset - SNLog("Session reset initiated.") - self.contactThread.sessionResetStatus = .initiated - self.contactThread.save(with: transaction) - } - } - self.reportSuccess() - }.catch { error in - Logger.error("sending error: \(error.localizedDescription)") - self.reportError(error) - }.retainUntilComplete() - */ - } - - override public func didSucceed() { - Storage.writeSync { transaction in - self.durableOperationDelegate?.durableOperationDidSucceed(self, transaction: transaction) - } - } - - override public func didReportError(_ error: Error) { - Logger.debug("remainingRetries: \(self.remainingRetries)") - - Storage.writeSync { transaction in - self.durableOperationDelegate?.durableOperation(self, didReportError: error, transaction: transaction) - } - } - - override public func retryInterval() -> TimeInterval { - // Arbitrary backoff factor... - // With backOffFactor of 1.9 - // try 1 delay: 0.00s - // try 2 delay: 0.19s - // ... - // try 5 delay: 1.30s - // ... - // try 11 delay: 61.31s - let backoffFactor = 1.9 - let maxBackoff = kHourInterval - - let seconds = 0.1 * min(maxBackoff, pow(backoffFactor, Double(self.jobRecord.failureCount))) - - return seconds - } - - override public func didFail(error: Error) { - Logger.error("failed to send EndSessionMessage with error: \(error.localizedDescription)") - Storage.writeSync { transaction in - self.durableOperationDelegate?.durableOperation(self, didFailWithError: error, transaction: transaction) - - // Even though this is the failure handler - which means probably the recipient didn't receive the message - // there's a chance that our send did succeed and the server just timed out our repsonse or something. - // Since the cost of sending a future message using a session the recipient doesn't have is so high, - // we archive the session just in case. - // - // Archive the just-created session since the recipient should delete their corresponding - // session upon receiving and decrypting our EndSession message. - // Otherwise if we send another message before them, they wont have the session to decrypt it. - self.primaryStorage.archiveAllSessions(forContact: self.recipientId, protocolContext: transaction) - } - } -} diff --git a/SessionMessagingKit/Configuration.swift b/SessionMessagingKit/Configuration.swift index 2e195fc19..dc4a80ec6 100644 --- a/SessionMessagingKit/Configuration.swift +++ b/SessionMessagingKit/Configuration.swift @@ -3,43 +3,17 @@ import SessionProtocolKit @objc public final class SNMessagingKitConfiguration : NSObject { public let storage: SessionMessagingKitStorageProtocol - @objc public let signalStorage: SessionStore & PreKeyStore & SignedPreKeyStore - public let identityKeyStore: IdentityKeyStore - public let sessionRestorationImplementation: SessionRestorationProtocol - public let certificateValidator: SMKCertificateValidator @objc public static var shared: SNMessagingKitConfiguration! - fileprivate init( - storage: SessionMessagingKitStorageProtocol, - signalStorage: SessionStore & PreKeyStore & SignedPreKeyStore, - identityKeyStore: IdentityKeyStore, - sessionRestorationImplementation: SessionRestorationProtocol, - certificateValidator: SMKCertificateValidator - ) { + fileprivate init(storage: SessionMessagingKitStorageProtocol) { self.storage = storage - self.signalStorage = signalStorage - self.identityKeyStore = identityKeyStore - self.sessionRestorationImplementation = sessionRestorationImplementation - self.certificateValidator = certificateValidator } } public enum SNMessagingKit { // Just to make the external API nice - public static func configure( - storage: SessionMessagingKitStorageProtocol, - signalStorage: SessionStore & PreKeyStore & SignedPreKeyStore, - identityKeyStore: IdentityKeyStore, - sessionRestorationImplementation: SessionRestorationProtocol, - certificateValidator: SMKCertificateValidator - ) { - SNMessagingKitConfiguration.shared = SNMessagingKitConfiguration( - storage: storage, - signalStorage: signalStorage, - identityKeyStore: identityKeyStore, - sessionRestorationImplementation: sessionRestorationImplementation, - certificateValidator: certificateValidator - ) + public static func configure(storage: SessionMessagingKitStorageProtocol) { + SNMessagingKitConfiguration.shared = SNMessagingKitConfiguration(storage: storage) } } diff --git a/SessionMessagingKit/Database/OWSPrimaryStorage.m b/SessionMessagingKit/Database/OWSPrimaryStorage.m index 1bc9b97ff..105827c31 100644 --- a/SessionMessagingKit/Database/OWSPrimaryStorage.m +++ b/SessionMessagingKit/Database/OWSPrimaryStorage.m @@ -173,7 +173,6 @@ void VerifyRegistrationsForPrimaryStorage(OWSStorage *storage) [TSDatabaseView asyncRegisterUnseenDatabaseView:self]; [TSDatabaseView asyncRegisterThreadOutgoingMessagesDatabaseView:self]; - [TSDatabaseView asyncRegisterThreadSpecialMessagesDatabaseView:self]; [FullTextSearchFinder asyncRegisterDatabaseExtensionWithStorage:self]; [OWSIncomingMessageFinder asyncRegisterExtensionWithPrimaryStorage:self]; diff --git a/SessionMessagingKit/Database/Storage+Messaging.swift b/SessionMessagingKit/Database/Storage+Messaging.swift index 13c092553..0fbb143d7 100644 --- a/SessionMessagingKit/Database/Storage+Messaging.swift +++ b/SessionMessagingKit/Database/Storage+Messaging.swift @@ -6,16 +6,6 @@ extension Storage { SSKEnvironment.shared.tsAccountManager.getOrGenerateRegistrationId(transaction as! YapDatabaseReadWriteTransaction) } - public func getSenderCertificate(for publicKey: String) -> SMKSenderCertificate { - let (promise, seal) = Promise.pending() - SSKEnvironment.shared.udManager.ensureSenderCertificate { senderCertificate in - seal.fulfill(senderCertificate) - } failure: { error in - // Should never fail - } - return try! promise.wait() - } - /// Returns the ID of the thread. public func getOrCreateThread(for publicKey: String, groupPublicKey: String?, openGroupID: String?, using transaction: Any) -> String? { let transaction = transaction as! YapDatabaseReadWriteTransaction diff --git a/SessionMessagingKit/Database/TSDatabaseView.h b/SessionMessagingKit/Database/TSDatabaseView.h index 1598f55fd..689ff804c 100644 --- a/SessionMessagingKit/Database/TSDatabaseView.h +++ b/SessionMessagingKit/Database/TSDatabaseView.h @@ -63,8 +63,6 @@ extern NSString *const TSLazyRestoreAttachmentsDatabaseViewExtensionName; // Instances of OWSReadTracking for wasRead is NO. + (void)asyncRegisterUnseenDatabaseView:(OWSStorage *)storage; -+ (void)asyncRegisterThreadSpecialMessagesDatabaseView:(OWSStorage *)storage; - + (void)asyncRegisterLazyRestoreAttachmentsDatabaseView:(OWSStorage *)storage; @end diff --git a/SessionMessagingKit/Database/TSDatabaseView.m b/SessionMessagingKit/Database/TSDatabaseView.m index b59d16054..d2c8562cd 100644 --- a/SessionMessagingKit/Database/TSDatabaseView.m +++ b/SessionMessagingKit/Database/TSDatabaseView.m @@ -7,7 +7,6 @@ #import "TSAttachment.h" #import "TSAttachmentPointer.h" #import "TSIncomingMessage.h" -#import "TSInvalidIdentityKeyErrorMessage.h" #import "TSOutgoingMessage.h" #import "TSThread.h" #import @@ -128,33 +127,6 @@ NSString *const TSLazyRestoreAttachmentsGroup = @"TSLazyRestoreAttachmentsGroup" storage:storage]; } -+ (void)asyncRegisterThreadSpecialMessagesDatabaseView:(OWSStorage *)storage -{ - YapDatabaseViewGrouping *viewGrouping = [YapDatabaseViewGrouping withObjectBlock:^NSString *( - YapDatabaseReadTransaction *transaction, NSString *collection, NSString *key, id object) { - if (![object isKindOfClass:[TSInteraction class]]) { - return nil; - } - TSInteraction *interaction = (TSInteraction *)object; - if ([interaction isDynamicInteraction]) { - return interaction.uniqueThreadId; - } else if ([object isKindOfClass:[TSInvalidIdentityKeyErrorMessage class]]) { - return interaction.uniqueThreadId; - } else if ([object isKindOfClass:[TSErrorMessage class]]) { - TSErrorMessage *errorMessage = (TSErrorMessage *)object; - if (errorMessage.errorType == TSErrorMessageNonBlockingIdentityChange) { - return errorMessage.uniqueThreadId; - } - } - return nil; - }]; - - [self registerMessageDatabaseViewWithName:TSThreadSpecialMessagesDatabaseViewExtensionName - viewGrouping:viewGrouping - version:@"2" - storage:storage]; -} - + (void)asyncRegisterLegacyThreadInteractionsDatabaseView:(OWSStorage *)storage { YapDatabaseView *existingView = [storage registeredExtension:TSMessageDatabaseViewExtensionName_Legacy]; diff --git a/SessionMessagingKit/Messages/Control Messages/Unused/NullMessage.swift b/SessionMessagingKit/Messages/Control Messages/Unused/NullMessage.swift deleted file mode 100644 index 488956883..000000000 --- a/SessionMessagingKit/Messages/Control Messages/Unused/NullMessage.swift +++ /dev/null @@ -1,39 +0,0 @@ -import SessionProtocolKit -import SessionUtilitiesKit - -@objc(SNNullMessage) -public final class NullMessage : ControlMessage { - - // MARK: Initialization - public override init() { super.init() } - - // MARK: Coding - public required init?(coder: NSCoder) { - super.init(coder: coder) - } - - public override func encode(with coder: NSCoder) { - super.encode(with: coder) - } - - // MARK: Proto Conversion - public override class func fromProto(_ proto: SNProtoContent) -> NullMessage? { - guard proto.nullMessage != nil else { return nil } - return NullMessage() - } - - public override func toProto(using transaction: YapDatabaseReadWriteTransaction) -> SNProtoContent? { - let nullMessageProto = SNProtoNullMessage.builder() - let paddingSize = UInt.random(in: 0..<512) // random(in:) uses the system's default random generator, which is cryptographically secure - let padding = Data.getSecureRandomData(ofSize: paddingSize)! - nullMessageProto.setPadding(padding) - let contentProto = SNProtoContent.builder() - do { - contentProto.setNullMessage(try nullMessageProto.build()) - return try contentProto.build() - } catch { - SNLog("Couldn't construct null message proto from: \(self).") - return nil - } - } -} diff --git a/SessionMessagingKit/Messages/Control Messages/Unused/SessionRequest.swift b/SessionMessagingKit/Messages/Control Messages/Unused/SessionRequest.swift deleted file mode 100644 index 52f6e0293..000000000 --- a/SessionMessagingKit/Messages/Control Messages/Unused/SessionRequest.swift +++ /dev/null @@ -1,80 +0,0 @@ -import SessionProtocolKit -import SessionUtilitiesKit - -@objc(SNSessionRequest) -public final class SessionRequest : ControlMessage { - public var preKeyBundle: PreKeyBundle? - - // MARK: Initialization - public override init() { super.init() } - - internal init(preKeyBundle: PreKeyBundle) { - super.init() - self.preKeyBundle = preKeyBundle - } - - // MARK: Validation - public override var isValid: Bool { - guard super.isValid else { return false } - return preKeyBundle != nil - } - - // MARK: Coding - public required init?(coder: NSCoder) { - super.init(coder: coder) - if let preKeyBundle = coder.decodeObject(forKey: "preKeyBundle") as! PreKeyBundle? { self.preKeyBundle = preKeyBundle } - } - - public override func encode(with coder: NSCoder) { - super.encode(with: coder) - coder.encode(preKeyBundle, forKey: "preKeyBundle") - } - - // MARK: Proto Conversion - public override class func fromProto(_ proto: SNProtoContent) -> SessionRequest? { - guard proto.nullMessage != nil, let preKeyBundleProto = proto.prekeyBundleMessage else { return nil } - var registrationID: UInt32 = 0 - SNMessagingKitConfiguration.shared.storage.writeSync { transaction in - registrationID = SNMessagingKitConfiguration.shared.storage.getOrGenerateRegistrationID(using: transaction) - } - guard let preKeyBundle = PreKeyBundle( - registrationId: Int32(registrationID), - deviceId: 1, - preKeyId: Int32(preKeyBundleProto.prekeyID), - preKeyPublic: preKeyBundleProto.prekey, - signedPreKeyPublic: preKeyBundleProto.signedKey, - signedPreKeyId: Int32(preKeyBundleProto.signedKeyID), - signedPreKeySignature: preKeyBundleProto.signature, - identityKey: preKeyBundleProto.identityKey - ) else { return nil } - return SessionRequest(preKeyBundle: preKeyBundle) - } - - public override func toProto(using transaction: YapDatabaseReadWriteTransaction) -> SNProtoContent? { - guard let preKeyBundle = preKeyBundle else { - SNLog("Couldn't construct session request proto from: \(self).") - return nil - } - let nullMessageProto = SNProtoNullMessage.builder() - let paddingSize = UInt.random(in: 0..<512) // random(in:) uses the system's default random generator, which is cryptographically secure - let padding = Data.getSecureRandomData(ofSize: paddingSize)! - nullMessageProto.setPadding(padding) - let preKeyBundleProto = SNProtoPrekeyBundleMessage.builder() - preKeyBundleProto.setIdentityKey(preKeyBundle.identityKey) - preKeyBundleProto.setDeviceID(UInt32(preKeyBundle.deviceId)) - preKeyBundleProto.setPrekeyID(UInt32(preKeyBundle.preKeyId)) - preKeyBundleProto.setPrekey(preKeyBundle.preKeyPublic) - preKeyBundleProto.setSignedKeyID(UInt32(preKeyBundle.signedPreKeyId)) - preKeyBundleProto.setSignedKey(preKeyBundle.signedPreKeyPublic) - preKeyBundleProto.setSignature(preKeyBundle.signedPreKeySignature) - let contentProto = SNProtoContent.builder() - do { - contentProto.setNullMessage(try nullMessageProto.build()) - contentProto.setPrekeyBundleMessage(try preKeyBundleProto.build()) - return try contentProto.build() - } catch { - SNLog("Couldn't construct session request proto from: \(self).") - return nil - } - } -} diff --git a/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyErrorMessage.h b/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyErrorMessage.h deleted file mode 100644 index a12d51534..000000000 --- a/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyErrorMessage.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface TSInvalidIdentityKeyErrorMessage : TSErrorMessage - -- (void)throws_acceptNewIdentityKey NS_SWIFT_UNAVAILABLE("throws objc exceptions"); -- (nullable NSData *)throws_newIdentityKey NS_SWIFT_UNAVAILABLE("throws objc exceptions"); -- (NSString *)theirSignalId; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyErrorMessage.m b/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyErrorMessage.m deleted file mode 100644 index ce9e3a62d..000000000 --- a/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyErrorMessage.m +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "TSInvalidIdentityKeyErrorMessage.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -@implementation TSInvalidIdentityKeyErrorMessage - -- (void)throws_acceptNewIdentityKey -{ - -} - -- (nullable NSData *)throws_newIdentityKey -{ - return nil; -} - -- (NSString *)theirSignalId -{ - return nil; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyReceivingErrorMessage.h b/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyReceivingErrorMessage.h deleted file mode 100644 index 8b2de8c6f..000000000 --- a/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyReceivingErrorMessage.h +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@class SNProtoEnvelope; - -// DEPRECATED - we no longer create new instances of this class (as of mid-2017); However, existing instances may -// exist, so we should keep this class around to honor their old behavior. -__attribute__((deprecated)) @interface TSInvalidIdentityKeyReceivingErrorMessage : TSInvalidIdentityKeyErrorMessage - -#ifdef DEBUG -+ (nullable instancetype)untrustedKeyWithEnvelope:(SNProtoEnvelope *)envelope - withTransaction:(YapDatabaseReadWriteTransaction *)transaction; -#endif - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyReceivingErrorMessage.m b/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyReceivingErrorMessage.m deleted file mode 100644 index 1f2a562c1..000000000 --- a/SessionMessagingKit/Messages/Signal/TSInvalidIdentityKeyReceivingErrorMessage.m +++ /dev/null @@ -1,141 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "TSInvalidIdentityKeyReceivingErrorMessage.h" -#import "OWSIdentityManager.h" -#import "OWSPrimaryStorage.h" -#import "SSKEnvironment.h" -#import "TSContactThread.h" -#import "TSDatabaseView.h" -#import "TSErrorMessage_privateConstructor.h" -#import -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -__attribute__((deprecated)) @interface TSInvalidIdentityKeyReceivingErrorMessage() - -@property (nonatomic, readonly, copy) NSString *authorId; - -@end - -@implementation TSInvalidIdentityKeyReceivingErrorMessage { - // Not using a property declaration in order to exclude from DB serialization - SNProtoEnvelope *_Nullable _envelope; -} - -@synthesize envelopeData = _envelopeData; - -#ifdef DEBUG -// We no longer create these messages, but they might exist on legacy clients so it's useful to be able to -// create them with the debug UI -+ (nullable instancetype)untrustedKeyWithEnvelope:(SNProtoEnvelope *)envelope - withTransaction:(YapDatabaseReadWriteTransaction *)transaction -{ - TSContactThread *contactThread = - [TSContactThread getOrCreateThreadWithContactId:envelope.source transaction:transaction]; - - // Legit usage of senderTimestamp, references message which failed to decrypt - TSInvalidIdentityKeyReceivingErrorMessage *errorMessage = - [[self alloc] initForUnknownIdentityKeyWithTimestamp:envelope.timestamp - inThread:contactThread - incomingEnvelope:envelope]; - return errorMessage; -} - -- (nullable instancetype)initForUnknownIdentityKeyWithTimestamp:(uint64_t)timestamp - inThread:(TSThread *)thread - incomingEnvelope:(SNProtoEnvelope *)envelope -{ - self = [self initWithTimestamp:timestamp inThread:thread failedMessageType:TSErrorMessageWrongTrustedIdentityKey]; - if (!self) { - return self; - } - - NSError *error; - _envelopeData = [envelope serializedDataAndReturnError:&error]; - if (!_envelopeData || error != nil) { - return nil; - } - - _authorId = envelope.source; - - return self; -} -#endif - -- (nullable SNProtoEnvelope *)envelope -{ - if (!_envelope) { - NSError *error; - SNProtoEnvelope *_Nullable envelope = [SNProtoEnvelope parseData:self.envelopeData error:&error]; - if (error || envelope == nil) { - - } else { - _envelope = envelope; - } - } - return _envelope; -} - -- (void)throws_acceptNewIdentityKey -{ - if (self.errorType != TSErrorMessageWrongTrustedIdentityKey) { - return; - } - - NSData *_Nullable newKey = [self throws_newIdentityKey]; - if (!newKey) { - return; - } - - [[OWSIdentityManager sharedManager] saveRemoteIdentity:newKey recipientId:self.envelope.source]; - - // Decrypt this and any old messages for the newly accepted key - NSArray *messagesToDecrypt = - [self.thread receivedMessagesForInvalidKey:newKey]; - - for (TSInvalidIdentityKeyReceivingErrorMessage *errorMessage in messagesToDecrypt) { - - // Here we remove the existing error message because handleReceivedEnvelope will either - // 1.) succeed and create a new successful message in the thread or... - // 2.) fail and create a new identical error message in the thread. - [errorMessage remove]; - } -} - -- (nullable NSData *)throws_newIdentityKey -{ - if (!self.envelope) { - return nil; - } - - if (self.envelope.type != SNProtoEnvelopeTypePrekeyBundle) { - return nil; - } - - NSData *pkwmData = self.envelope.content; - if (!pkwmData) { - return nil; - } - - PreKeyWhisperMessage *message = [[PreKeyWhisperMessage alloc] init_throws_withData:pkwmData]; - return [message.identityKey throws_removeKeyType]; -} - -- (NSString *)theirSignalId -{ - if (self.authorId) { - return self.authorId; - } else { - // for existing messages before we were storing author id. - return self.envelope.source; - } -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionMessagingKit/Messages/Signal/TSMessage.h b/SessionMessagingKit/Messages/Signal/TSMessage.h index d5f9058cf..1a7c7b610 100644 --- a/SessionMessagingKit/Messages/Signal/TSMessage.h +++ b/SessionMessagingKit/Messages/Signal/TSMessage.h @@ -6,6 +6,11 @@ NS_ASSUME_NONNULL_BEGIN +typedef NS_ENUM(NSUInteger, TSMessageDirection) { + TSMessageDirectionIncoming, + TSMessageDirectionOutgoing +}; + /** * Abstract message class. */ diff --git a/SessionMessagingKit/Meta/SessionMessagingKit.h b/SessionMessagingKit/Meta/SessionMessagingKit.h index f53ee7cfb..6c7247ea4 100644 --- a/SessionMessagingKit/Meta/SessionMessagingKit.h +++ b/SessionMessagingKit/Meta/SessionMessagingKit.h @@ -48,8 +48,6 @@ FOUNDATION_EXPORT const unsigned char SessionMessagingKitVersionString[]; #import #import #import -#import -#import #import #import #import diff --git a/SessionMessagingKit/Sending & Receiving/MessageReceiver+Decryption.swift b/SessionMessagingKit/Sending & Receiving/MessageReceiver+Decryption.swift index a20313452..13bc05b60 100644 --- a/SessionMessagingKit/Sending & Receiving/MessageReceiver+Decryption.swift +++ b/SessionMessagingKit/Sending & Receiving/MessageReceiver+Decryption.swift @@ -5,18 +5,6 @@ import Sodium internal extension MessageReceiver { - static func decryptWithSignalProtocol(envelope: SNProtoEnvelope, using transaction: Any) throws -> (plaintext: Data, senderPublicKey: String) { - let storage = SNMessagingKitConfiguration.shared.signalStorage - let certificateValidator = SNMessagingKitConfiguration.shared.certificateValidator - guard let data = envelope.content else { throw Error.noData } - guard let userPublicKey = SNMessagingKitConfiguration.shared.storage.getUserPublicKey() else { throw Error.noUserX25519KeyPair } - let cipher = try SMKSecretSessionCipher(sessionResetImplementation: SNMessagingKitConfiguration.shared.sessionRestorationImplementation, - sessionStore: storage, preKeyStore: storage, signedPreKeyStore: storage, identityStore: SNMessagingKitConfiguration.shared.identityKeyStore) - let result = try cipher.throwswrapped_decryptMessage(certificateValidator: certificateValidator, cipherTextData: data, - timestamp: envelope.timestamp, localRecipientId: userPublicKey, localDeviceId: 1, protocolContext: transaction) - return (result.paddedPayload, result.senderRecipientId) - } - static func decryptWithSessionProtocol(envelope: SNProtoEnvelope) throws -> (plaintext: Data, senderX25519PublicKey: String) { guard let ciphertext = envelope.content else { throw Error.noData } let recipientX25519PrivateKey: Data @@ -53,38 +41,4 @@ internal extension MessageReceiver { return (Data(plaintext), "05" + senderX25519PublicKey.toHexString()) } - - static func decryptWithSharedSenderKeys(envelope: SNProtoEnvelope, using transaction: Any) throws -> (plaintext: Data, senderPublicKey: String) { - // 1. ) Check preconditions - guard let groupPublicKey = envelope.source, SNMessagingKitConfiguration.shared.storage.isClosedGroup(groupPublicKey) else { - throw Error.invalidGroupPublicKey - } - guard let data = envelope.content else { - throw Error.noData - } - guard let hexEncodedGroupPrivateKey = SNMessagingKitConfiguration.shared.storage.getClosedGroupPrivateKey(for: groupPublicKey) else { - throw Error.noGroupPrivateKey - } - let groupPrivateKey = Data(hex: hexEncodedGroupPrivateKey) - // 2. ) Parse the wrapper - let wrapper = try SNProtoClosedGroupCiphertextMessageWrapper.parseData(data) - let ivAndCiphertext = wrapper.ciphertext - let ephemeralPublicKey = wrapper.ephemeralPublicKey - // 3. ) Decrypt the data inside - guard let ephemeralSharedSecret = try? Curve25519.generateSharedSecret(fromPublicKey: ephemeralPublicKey, privateKey: groupPrivateKey) else { - throw Error.sharedSecretGenerationFailed - } - let salt = "LOKI".data(using: String.Encoding.utf8, allowLossyConversion: true)!.bytes - let symmetricKey = try HMAC(key: salt, variant: .sha256).authenticate(ephemeralSharedSecret.bytes) - let closedGroupCiphertextMessageAsData = try AESGCM.decrypt(ivAndCiphertext, with: Data(symmetricKey)) - // 4. ) Parse the closed group ciphertext message - let closedGroupCiphertextMessage = ClosedGroupCiphertextMessage(_throws_with: closedGroupCiphertextMessageAsData) - let senderPublicKey = closedGroupCiphertextMessage.senderPublicKey.toHexString() - guard senderPublicKey != SNMessagingKitConfiguration.shared.storage.getUserPublicKey() else { throw Error.selfSend } - // 5. ) Use the info inside the closed group ciphertext message to decrypt the actual message content - let plaintext = try SharedSenderKeys.decrypt(closedGroupCiphertextMessage.ivAndCiphertext, for: groupPublicKey, - senderPublicKey: senderPublicKey, keyIndex: UInt(closedGroupCiphertextMessage.keyIndex), using: transaction) - // 6. ) Return - return (plaintext, senderPublicKey) - } } diff --git a/SessionMessagingKit/Sending & Receiving/MessageSender+ClosedGroups.swift b/SessionMessagingKit/Sending & Receiving/MessageSender+ClosedGroups.swift index ad4aca5da..ccaae98b9 100644 --- a/SessionMessagingKit/Sending & Receiving/MessageSender+ClosedGroups.swift +++ b/SessionMessagingKit/Sending & Receiving/MessageSender+ClosedGroups.swift @@ -1,4 +1,5 @@ import PromiseKit +import SessionProtocolKit extension MessageSender : SharedSenderKeysDelegate { diff --git a/SessionMessagingKit/Sending & Receiving/MessageSender+Encryption.swift b/SessionMessagingKit/Sending & Receiving/MessageSender+Encryption.swift index ff11b4e39..323f76c48 100644 --- a/SessionMessagingKit/Sending & Receiving/MessageSender+Encryption.swift +++ b/SessionMessagingKit/Sending & Receiving/MessageSender+Encryption.swift @@ -4,15 +4,6 @@ import Sodium internal extension MessageSender { - static func encryptWithSignalProtocol(_ plaintext: Data, associatedWith message: Message, for publicKey: String, using transaction: Any) throws -> Data { - let storage = SNMessagingKitConfiguration.shared.signalStorage - let cipher = try SMKSecretSessionCipher(sessionResetImplementation: SNMessagingKitConfiguration.shared.sessionRestorationImplementation, - sessionStore: storage, preKeyStore: storage, signedPreKeyStore: storage, identityStore: SNMessagingKitConfiguration.shared.identityKeyStore) - let certificate = SMKSenderCertificate(senderDeviceId: 1, senderRecipientId: SNMessagingKitConfiguration.shared.storage.getUserPublicKey()!) - return try cipher.throwswrapped_encryptMessage(recipientPublicKey: publicKey, deviceID: 1, paddedPlaintext: (plaintext as NSData).paddedMessageBody(), - senderCertificate: certificate, protocolContext: transaction, useFallbackSessionCipher: true) - } - static func encryptWithSessionProtocol(_ plaintext: Data, for recipientHexEncodedX25519PublicKey: String) throws -> Data { guard let userED25519KeyPair = SNMessagingKitConfiguration.shared.storage.getUserED25519KeyPair() else { throw Error.noUserED25519KeyPair } let recipientX25519PublicKey = Data(hex: recipientHexEncodedX25519PublicKey.removing05PrefixIfNeeded()) @@ -25,18 +16,4 @@ internal extension MessageSender { return Data(ciphertext) } - - static func encryptWithSharedSenderKeys(_ plaintext: Data, for groupPublicKey: String, using transaction: Any) throws -> Data { - // 1. ) Encrypt the data with the user's sender key - guard let userPublicKey = SNMessagingKitConfiguration.shared.storage.getUserPublicKey() else { - SNLog("Couldn't find user key pair.") - throw Error.noUserX25519KeyPair - } - let (ivAndCiphertext, keyIndex) = try SharedSenderKeys.encrypt((plaintext as NSData).paddedMessageBody(), for: groupPublicKey, senderPublicKey: userPublicKey, using: transaction) - let encryptedMessage = ClosedGroupCiphertextMessage(_throws_withIVAndCiphertext: ivAndCiphertext, senderPublicKey: Data(hex: userPublicKey), keyIndex: UInt32(keyIndex)) - // 2. ) Encrypt the result for the group's public key to hide the sender public key and key index - let intermediate = try AESGCM.encrypt(encryptedMessage.serialized, for: groupPublicKey.removing05PrefixIfNeeded()) - // 3. ) Wrap the result - return try SNProtoClosedGroupCiphertextMessageWrapper.builder(ciphertext: intermediate.ciphertext, ephemeralPublicKey: intermediate.ephemeralPublicKey).build().serializedData() - } } diff --git a/SessionMessagingKit/Storage.swift b/SessionMessagingKit/Storage.swift index 590f66092..3ea0c21f1 100644 --- a/SessionMessagingKit/Storage.swift +++ b/SessionMessagingKit/Storage.swift @@ -24,7 +24,6 @@ public protocol SessionMessagingKitStorageProtocol { // MARK: - Signal Protocol func getOrGenerateRegistrationID(using transaction: Any) -> UInt32 - func getSenderCertificate(for publicKey: String) -> SMKSenderCertificate // MARK: - Shared Sender Keys diff --git a/SessionMessagingKit/Threads/TSContactThread.m b/SessionMessagingKit/Threads/TSContactThread.m index f97ab07be..10b5cb2eb 100644 --- a/SessionMessagingKit/Threads/TSContactThread.m +++ b/SessionMessagingKit/Threads/TSContactThread.m @@ -64,7 +64,7 @@ NSString *const TSContactThreadPrefix = @"c"; - (BOOL)hasSafetyNumbers { - return !![[OWSIdentityManager sharedManager] identityKeyForRecipientId:self.contactIdentifier]; + return NO; } - (NSString *)name diff --git a/SessionMessagingKit/Threads/TSThread.h b/SessionMessagingKit/Threads/TSThread.h index 1c1858e58..47ef53d3d 100644 --- a/SessionMessagingKit/Threads/TSThread.h +++ b/SessionMessagingKit/Threads/TSThread.h @@ -60,14 +60,6 @@ BOOL IsNoteToSelfEnabled(void); */ - (NSUInteger)numberOfInteractions; -/** - * Get all messages in the thread we weren't able to decrypt - */ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -- (NSArray *)receivedMessagesForInvalidKey:(NSData *)key; -#pragma clang diagnostic pop - - (NSUInteger)unreadMessageCountWithTransaction:(YapDatabaseReadTransaction *)transaction NS_SWIFT_NAME(unreadMessageCount(transaction:)); diff --git a/SessionMessagingKit/Threads/TSThread.m b/SessionMessagingKit/Threads/TSThread.m index 11fca049e..9350446f1 100644 --- a/SessionMessagingKit/Threads/TSThread.m +++ b/SessionMessagingKit/Threads/TSThread.m @@ -224,28 +224,6 @@ BOOL IsNoteToSelfEnabled(void) return [interactions copy]; } -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -- (NSArray *)receivedMessagesForInvalidKey:(NSData *)key -{ - NSMutableArray *errorMessages = [NSMutableArray new]; - [self enumerateInteractionsUsingBlock:^(TSInteraction *interaction) { - if ([interaction isKindOfClass:[TSInvalidIdentityKeyReceivingErrorMessage class]]) { - TSInvalidIdentityKeyReceivingErrorMessage *error = (TSInvalidIdentityKeyReceivingErrorMessage *)interaction; - @try { - if ([[error throws_newIdentityKey] isEqualToData:key]) { - [errorMessages addObject:(TSInvalidIdentityKeyReceivingErrorMessage *)interaction]; - } - } @catch (NSException *exception) { - - } - } - }]; - - return [errorMessages copy]; -} -#pragma clang diagnostic pop - - (NSUInteger)numberOfInteractions { __block NSUInteger count; diff --git a/SessionMessagingKit/To Do/OWSUDManager.swift b/SessionMessagingKit/To Do/OWSUDManager.swift deleted file mode 100644 index 6a8f4226a..000000000 --- a/SessionMessagingKit/To Do/OWSUDManager.swift +++ /dev/null @@ -1,71 +0,0 @@ - -@objc -public enum UnidentifiedAccessMode: Int { - case unknown - case enabled - case disabled - case unrestricted -} - -@objc -public class OWSUDAccess: NSObject { - @objc - public let udAccessKey: SMKUDAccessKey - - @objc - public let udAccessMode: UnidentifiedAccessMode - - @objc - public let isRandomKey: Bool - - @objc - public required init(udAccessKey: SMKUDAccessKey, - udAccessMode: UnidentifiedAccessMode, - isRandomKey: Bool) { - self.udAccessKey = udAccessKey - self.udAccessMode = udAccessMode - self.isRandomKey = isRandomKey - } -} - -@objc public protocol OWSUDManager: class { - - @objc func setup() - - @objc func trustRoot() -> ECPublicKey - - @objc func isUDVerboseLoggingEnabled() -> Bool - - // MARK: - Recipient State - - @objc - func setUnidentifiedAccessMode(_ mode: UnidentifiedAccessMode, recipientId: String) - - @objc - func unidentifiedAccessMode(forRecipientId recipientId: String) -> UnidentifiedAccessMode - - @objc - func udAccessKey(forRecipientId recipientId: String) -> SMKUDAccessKey? - - @objc - func udAccess(forRecipientId recipientId: String, - requireSyncAccess: Bool) -> OWSUDAccess? - - // MARK: Sender Certificate - - // We use completion handlers instead of a promise so that message sending - // logic can access the strongly typed certificate data. - @objc - func ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, - failure:@escaping (Error) -> Void) - - // MARK: Unrestricted Access - - @objc - func shouldAllowUnrestrictedAccessLocal() -> Bool - @objc - func setShouldAllowUnrestrictedAccessLocal(_ value: Bool) - - @objc - func getSenderCertificate() -> SMKSenderCertificate? -} diff --git a/SessionMessagingKit/To Do/SignalRecipient.m b/SessionMessagingKit/To Do/SignalRecipient.m index 796105514..51f5196c1 100644 --- a/SessionMessagingKit/To Do/SignalRecipient.m +++ b/SessionMessagingKit/To Do/SignalRecipient.m @@ -27,11 +27,6 @@ NS_ASSUME_NONNULL_BEGIN return SSKEnvironment.shared.profileManager; } -- (id)udManager -{ - return SSKEnvironment.shared.udManager; -} - - (TSAccountManager *)tsAccountManager { return SSKEnvironment.shared.tsAccountManager; diff --git a/SessionMessagingKit/Utilities/OWSIdentityManager.h b/SessionMessagingKit/Utilities/OWSIdentityManager.h index cb7a23c72..9972facbc 100644 --- a/SessionMessagingKit/Utilities/OWSIdentityManager.h +++ b/SessionMessagingKit/Utilities/OWSIdentityManager.h @@ -2,7 +2,7 @@ // Copyright (c) 2018 Open Whisper Systems. All rights reserved. // -#import +#import #import @class OWSPrimaryStorage; @@ -34,7 +34,7 @@ extern const NSUInteger kStoredIdentityKeyLength; @class YapDatabaseReadWriteTransaction; // This class can be safely accessed and used from any thread. -@interface OWSIdentityManager : NSObject +@interface OWSIdentityManager : NSObject @property (nonatomic, readonly) YapDatabaseConnection *dbConnection; diff --git a/SessionMessagingKit/Utilities/OWSIdentityManager.m b/SessionMessagingKit/Utilities/OWSIdentityManager.m index e99e7c877..fb7cc7586 100644 --- a/SessionMessagingKit/Utilities/OWSIdentityManager.m +++ b/SessionMessagingKit/Utilities/OWSIdentityManager.m @@ -16,10 +16,10 @@ #import "TSContactThread.h" #import "TSErrorMessage.h" #import "TSGroupThread.h" +#import "TSMessage.h" #import #import "YapDatabaseConnection+OWS.h" #import "YapDatabaseTransaction+OWS.h" -#import #import #import #import @@ -223,8 +223,6 @@ NSString *const kNSNotificationName_IdentityStateDidChange = @"kNSNotificationNa createdAt:[NSDate new] verificationState:verificationState] saveWithTransaction:transaction]; - [SNMessagingKitConfiguration.shared.signalStorage archiveAllSessionsForContact:recipientId protocolContext:protocolContext]; - [self fireIdentityStateChangeNotification]; return YES; diff --git a/SessionMessagingKit/Utilities/SSKEnvironment.h b/SessionMessagingKit/Utilities/SSKEnvironment.h index 604bdafac..bd17878ce 100644 --- a/SessionMessagingKit/Utilities/SSKEnvironment.h +++ b/SessionMessagingKit/Utilities/SSKEnvironment.h @@ -41,7 +41,6 @@ NS_ASSUME_NONNULL_BEGIN primaryStorage:(OWSPrimaryStorage *)primaryStorage blockingManager:(OWSBlockingManager *)blockingManager identityManager:(OWSIdentityManager *)identityManager - udManager:(id)udManager tsAccountManager:(TSAccountManager *)tsAccountManager disappearingMessagesJob:(OWSDisappearingMessagesJob *)disappearingMessagesJob readReceiptManager:(OWSReadReceiptManager *)readReceiptManager @@ -64,7 +63,6 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, readonly) OWSPrimaryStorage *primaryStorage; @property (nonatomic, readonly) OWSBlockingManager *blockingManager; @property (nonatomic, readonly) OWSIdentityManager *identityManager; -@property (nonatomic, readonly) id udManager; @property (nonatomic, readonly) TSAccountManager *tsAccountManager; @property (nonatomic, readonly) OWSDisappearingMessagesJob *disappearingMessagesJob; @property (nonatomic, readonly) OWSReadReceiptManager *readReceiptManager; diff --git a/SessionMessagingKit/Utilities/SSKEnvironment.m b/SessionMessagingKit/Utilities/SSKEnvironment.m index e511ce354..662a12556 100644 --- a/SessionMessagingKit/Utilities/SSKEnvironment.m +++ b/SessionMessagingKit/Utilities/SSKEnvironment.m @@ -17,7 +17,6 @@ static SSKEnvironment *sharedSSKEnvironment; @property (nonatomic) OWSPrimaryStorage *primaryStorage; @property (nonatomic) OWSBlockingManager *blockingManager; @property (nonatomic) OWSIdentityManager *identityManager; -@property (nonatomic) id udManager; @property (nonatomic) TSAccountManager *tsAccountManager; @property (nonatomic) OWSDisappearingMessagesJob *disappearingMessagesJob; @property (nonatomic) OWSReadReceiptManager *readReceiptManager; @@ -41,7 +40,6 @@ static SSKEnvironment *sharedSSKEnvironment; primaryStorage:(OWSPrimaryStorage *)primaryStorage blockingManager:(OWSBlockingManager *)blockingManager identityManager:(OWSIdentityManager *)identityManager - udManager:(id)udManager tsAccountManager:(TSAccountManager *)tsAccountManager disappearingMessagesJob:(OWSDisappearingMessagesJob *)disappearingMessagesJob readReceiptManager:(OWSReadReceiptManager *)readReceiptManager @@ -59,7 +57,6 @@ static SSKEnvironment *sharedSSKEnvironment; _primaryStorage = primaryStorage; _blockingManager = blockingManager; _identityManager = identityManager; - _udManager = udManager; _tsAccountManager = tsAccountManager; _disappearingMessagesJob = disappearingMessagesJob; _readReceiptManager = readReceiptManager; diff --git a/SessionMessagingKit/Utilities/YapDatabaseConnection+OWS.h b/SessionMessagingKit/Utilities/YapDatabaseConnection+OWS.h index 96b27b277..2c7e6cc77 100644 --- a/SessionMessagingKit/Utilities/YapDatabaseConnection+OWS.h +++ b/SessionMessagingKit/Utilities/YapDatabaseConnection+OWS.h @@ -23,9 +23,6 @@ NS_ASSUME_NONNULL_BEGIN - (nullable NSString *)stringForKey:(NSString *)key inCollection:(NSString *)collection; - (nullable NSData *)dataForKey:(NSString *)key inCollection:(NSString *)collection; - (nullable ECKeyPair *)keyPairForKey:(NSString *)key inCollection:(NSString *)collection; -- (nullable PreKeyRecord *)preKeyRecordForKey:(NSString *)key inCollection:(NSString *)collection; -- (nullable PreKeyBundle *)preKeyBundleForKey:(NSString *)key inCollection:(NSString *)collection; -- (nullable SignedPreKeyRecord *)signedPreKeyRecordForKey:(NSString *)key inCollection:(NSString *)collection; - (NSUInteger)numberOfKeysInCollection:(NSString *)collection; diff --git a/SessionMessagingKit/Utilities/YapDatabaseConnection+OWS.m b/SessionMessagingKit/Utilities/YapDatabaseConnection+OWS.m index b58c37f1d..77e95a89c 100644 --- a/SessionMessagingKit/Utilities/YapDatabaseConnection+OWS.m +++ b/SessionMessagingKit/Utilities/YapDatabaseConnection+OWS.m @@ -65,21 +65,6 @@ NS_ASSUME_NONNULL_BEGIN return [self objectForKey:key inCollection:collection ofExpectedType:[ECKeyPair class]]; } -- (nullable PreKeyRecord *)preKeyRecordForKey:(NSString *)key inCollection:(NSString *)collection -{ - return [self objectForKey:key inCollection:collection ofExpectedType:[PreKeyRecord class]]; -} - -- (nullable PreKeyBundle *)preKeyBundleForKey:(NSString *)key inCollection:(NSString *)collection -{ - return [self objectForKey:key inCollection:collection ofExpectedType:PreKeyBundle.class]; -} - -- (nullable SignedPreKeyRecord *)signedPreKeyRecordForKey:(NSString *)key inCollection:(NSString *)collection -{ - return [self objectForKey:key inCollection:collection ofExpectedType:[SignedPreKeyRecord class]]; -} - - (int)intForKey:(NSString *)key inCollection:(NSString *)collection { NSNumber *_Nullable number = [self objectForKey:key inCollection:collection ofExpectedType:[NSNumber class]]; diff --git a/SessionMessagingKit/Utilities/YapDatabaseTransaction+OWS.h b/SessionMessagingKit/Utilities/YapDatabaseTransaction+OWS.h index fb9f6524c..03722a874 100644 --- a/SessionMessagingKit/Utilities/YapDatabaseTransaction+OWS.h +++ b/SessionMessagingKit/Utilities/YapDatabaseTransaction+OWS.h @@ -20,9 +20,6 @@ NS_ASSUME_NONNULL_BEGIN - (nullable NSString *)stringForKey:(NSString *)key inCollection:(NSString *)collection; - (nullable NSData *)dataForKey:(NSString *)key inCollection:(NSString *)collection; - (nullable ECKeyPair *)keyPairForKey:(NSString *)key inCollection:(NSString *)collection; -- (nullable PreKeyRecord *)preKeyRecordForKey:(NSString *)key inCollection:(NSString *)collection; -- (nullable PreKeyBundle *)preKeyBundleForKey:(NSString *)key inCollection:(NSString *)collection; -- (nullable SignedPreKeyRecord *)signedPreKeyRecordForKey:(NSString *)key inCollection:(NSString *)collection; @end diff --git a/SessionMessagingKit/Utilities/YapDatabaseTransaction+OWS.m b/SessionMessagingKit/Utilities/YapDatabaseTransaction+OWS.m index 0c9ea9cd0..3697adb5b 100644 --- a/SessionMessagingKit/Utilities/YapDatabaseTransaction+OWS.m +++ b/SessionMessagingKit/Utilities/YapDatabaseTransaction+OWS.m @@ -41,21 +41,6 @@ NS_ASSUME_NONNULL_BEGIN return [self objectForKey:key inCollection:collection ofExpectedType:[ECKeyPair class]]; } -- (nullable PreKeyRecord *)preKeyRecordForKey:(NSString *)key inCollection:(NSString *)collection -{ - return [self objectForKey:key inCollection:collection ofExpectedType:[PreKeyRecord class]]; -} - -- (nullable PreKeyBundle *)preKeyBundleForKey:(NSString *)key inCollection:(NSString *)collection -{ - return [self objectForKey:key inCollection:collection ofExpectedType:PreKeyBundle.class]; -} - -- (nullable SignedPreKeyRecord *)signedPreKeyRecordForKey:(NSString *)key inCollection:(NSString *)collection -{ - return [self objectForKey:key inCollection:collection ofExpectedType:[SignedPreKeyRecord class]]; -} - - (int)intForKey:(NSString *)key inCollection:(NSString *)collection { NSNumber *_Nullable number = [self objectForKey:key inCollection:collection ofExpectedType:[NSNumber class]]; diff --git a/SessionProtocolKit/Shared Sender Keys/ClosedGroupRatchet.swift b/SessionProtocolKit/ClosedGroupRatchet.swift similarity index 100% rename from SessionProtocolKit/Shared Sender Keys/ClosedGroupRatchet.swift rename to SessionProtocolKit/ClosedGroupRatchet.swift diff --git a/SessionProtocolKit/Shared Sender Keys/ClosedGroupSenderKey.swift b/SessionProtocolKit/ClosedGroupSenderKey.swift similarity index 98% rename from SessionProtocolKit/Shared Sender Keys/ClosedGroupSenderKey.swift rename to SessionProtocolKit/ClosedGroupSenderKey.swift index da16b34ec..332ba87d2 100644 --- a/SessionProtocolKit/Shared Sender Keys/ClosedGroupSenderKey.swift +++ b/SessionProtocolKit/ClosedGroupSenderKey.swift @@ -1,3 +1,4 @@ +import CryptoSwift public final class ClosedGroupSenderKey : NSObject, NSCoding { // NSObject/NSCoding conformance is needed for YapDatabase compatibility public let chainKey: Data diff --git a/SessionProtocolKit/Meta/SessionProtocolKit.h b/SessionProtocolKit/Meta/SessionProtocolKit.h index 75a2d0606..e5f9c3595 100644 --- a/SessionProtocolKit/Meta/SessionProtocolKit.h +++ b/SessionProtocolKit/Meta/SessionProtocolKit.h @@ -3,14 +3,4 @@ FOUNDATION_EXPORT double SessionProtocolKitVersionNumber; FOUNDATION_EXPORT const unsigned char SessionProtocolKitVersionString[]; -#import -#import -#import -#import -#import -#import #import -#import -#import -#import -#import diff --git a/SessionProtocolKit/Signal/NSData+messagePadding.h b/SessionProtocolKit/NSData+messagePadding.h similarity index 100% rename from SessionProtocolKit/Signal/NSData+messagePadding.h rename to SessionProtocolKit/NSData+messagePadding.h diff --git a/SessionProtocolKit/Signal/NSData+messagePadding.m b/SessionProtocolKit/NSData+messagePadding.m similarity index 100% rename from SessionProtocolKit/Signal/NSData+messagePadding.m rename to SessionProtocolKit/NSData+messagePadding.m diff --git a/SessionProtocolKit/Shared Sender Keys/SharedSenderKeys.swift b/SessionProtocolKit/SharedSenderKeys.swift similarity index 100% rename from SessionProtocolKit/Shared Sender Keys/SharedSenderKeys.swift rename to SessionProtocolKit/SharedSenderKeys.swift diff --git a/SessionProtocolKit/Signal/AxolotlExceptions.h b/SessionProtocolKit/Signal/AxolotlExceptions.h deleted file mode 100644 index a93421cbb..000000000 --- a/SessionProtocolKit/Signal/AxolotlExceptions.h +++ /dev/null @@ -1,72 +0,0 @@ -// -// AxolotlExceptions.h -// AxolotlKit -// -// Created by Frederic Jacobs on 23/07/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#ifndef AxolotlKit_AxolotlExceptions_h -#define AxolotlKit_AxolotlExceptions_h - -/** - * Thrown when the user is: - - 1) Sending a message with a PreKeyBundle that contains a different identity key than the previously known one. - 2) Receiving a new PreKeyWhisperMessage that has a different identity key than the previously known one. - */ - -static NSString *UntrustedIdentityKeyException = @"AxolotlUnstrustedIdentityKeyException"; - -/** - * Thrown thrown when a message is received with an unknown PreKeyID. - */ - -static NSString *InvalidKeyIdException = @"AxolotlInvalidKeyIdException"; - -/** - * Thrown when: - - 1) Signature of Prekeys are not correctly signed. - 2) We received a key type that is not compatible with this version. (All keys should be Curve25519). - */ - -static NSString *InvalidKeyException = @"AxolotlInvalidKeyException"; - -/** - * Thrown when receiving a message with no associated session for decryption. - */ - -static NSString *NoSessionException = @"AxolotlNoSessionException"; - -/** - * Thrown when receiving a malformatted message. - */ - -static NSString *InvalidMessageException = @"AxolotlInvalidMessageException"; - -/** - * Thrown when experiencing issues encrypting/decrypting a message symetrically. - */ - -static NSString *CipherException = @"AxolotlCipherIssue"; - -/** - * Thrown when detecting a message being sent a second time. (Replay attacks/bugs) - */ - -static NSString *DuplicateMessageException = @"AxolotlDuplicateMessage"; - -/** - * Thrown when receiving a message send with a non-supported version of the TextSecure protocol. - */ - -static NSString *LegacyMessageException = @"AxolotlLegacyMessageException"; - -/** - * Thrown when a client tries to initiate a session with a non-supported version. - */ - -static NSString *InvalidVersionException = @"AxolotlInvalidVersionException"; - -#endif diff --git a/SessionProtocolKit/Signal/CipherMessage/CipherMessage.h b/SessionProtocolKit/Signal/CipherMessage/CipherMessage.h deleted file mode 100644 index 2b0d85415..000000000 --- a/SessionProtocolKit/Signal/CipherMessage/CipherMessage.h +++ /dev/null @@ -1,24 +0,0 @@ -// -// CipherMessage.h -// AxolotlKit -// -// Created by Frederic Jacobs on 26/10/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import - -typedef NS_ENUM(NSUInteger, CipherMessageType) { - CipherMessageType_Prekey = 0, - CipherMessageType_Whisper, - CipherMessageType_Fallback = 3, - CipherMessageType_ClosedGroupCiphertext = 4 -}; - -@protocol CipherMessage - -- (NSData *)serialized; - -@property (nonatomic, readonly) CipherMessageType cipherMessageType; - -@end diff --git a/SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.h b/SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.h deleted file mode 100644 index a145c288c..000000000 --- a/SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.h +++ /dev/null @@ -1,18 +0,0 @@ -#import "CipherMessage.h" - -NS_ASSUME_NONNULL_BEGIN - -@interface ClosedGroupCiphertextMessage : NSObject - -@property (nonatomic, readonly) NSData *serialized; -@property (nonatomic, readonly) NSData *ivAndCiphertext; -@property (nonatomic, readonly) NSData *senderPublicKey; -@property (nonatomic, readonly) uint32_t keyIndex; - -- (instancetype)init_throws_withIVAndCiphertext:(NSData *)ivAndCiphertext senderPublicKey:(NSData *)senderPublicKey keyIndex:(uint32_t)keyIndex; -- (instancetype)init_throws_withData:(NSData *)serialized; - -@end - -NS_ASSUME_NONNULL_END - diff --git a/SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.m b/SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.m deleted file mode 100644 index 9720923b3..000000000 --- a/SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.m +++ /dev/null @@ -1,60 +0,0 @@ -#import "ClosedGroupCiphertextMessage.h" -#import "AxolotlExceptions.h" -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@implementation ClosedGroupCiphertextMessage - -- (instancetype)init_throws_withIVAndCiphertext:(NSData *)ivAndCiphertext senderPublicKey:(NSData *)senderPublicKey keyIndex:(uint32_t)keyIndex -{ - if (self = [super init]) { - _ivAndCiphertext = ivAndCiphertext; - _senderPublicKey = senderPublicKey; - _keyIndex = keyIndex; - - SPKProtoClosedGroupCiphertextMessageBuilder *builder = [SPKProtoClosedGroupCiphertextMessage builderWithCiphertext:ivAndCiphertext - senderPublicKey:senderPublicKey - keyIndex:keyIndex]; - - NSError *error; - NSData *_Nullable serialized = [builder buildSerializedDataAndReturnError:&error]; - if (serialized == nil || error != nil) { - OWSFailDebug(@"Couldn't serialize proto due to error: %@.", error); - OWSRaiseException(InvalidMessageException, @"Couldn't serialize proto."); - } - - _serialized = serialized; - } - - return self; -} - -- (instancetype)init_throws_withData:(NSData *)serialized -{ - if (self = [super init]) { - NSError *error; - SPKProtoClosedGroupCiphertextMessage *_Nullable ciphertextMessage = [SPKProtoClosedGroupCiphertextMessage parseData:serialized error:&error]; - if (ciphertextMessage == nil || error != nil) { - OWSFailDebug(@"Couldn't parse proto due to error: %@.", error); - OWSRaiseException(InvalidMessageException, @"Couldn't parse proto."); - } - - _serialized = serialized; - _ivAndCiphertext = ciphertextMessage.ciphertext; - _senderPublicKey = ciphertextMessage.senderPublicKey; - _keyIndex = ciphertextMessage.keyIndex; - } - - return self; -} - -- (CipherMessageType)cipherMessageType -{ - return CipherMessageType_ClosedGroupCiphertext; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/CipherMessage/FallbackMessage.h b/SessionProtocolKit/Signal/CipherMessage/FallbackMessage.h deleted file mode 100644 index d55c14bf0..000000000 --- a/SessionProtocolKit/Signal/CipherMessage/FallbackMessage.h +++ /dev/null @@ -1,13 +0,0 @@ -#import "CipherMessage.h" - -NS_ASSUME_NONNULL_BEGIN - -@interface FallbackMessage : NSObject - -@property (nonatomic, readonly) NSData *serialized; - -- (instancetype)init_throws_withData:(NSData *)serialized; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/CipherMessage/FallbackMessage.m b/SessionProtocolKit/Signal/CipherMessage/FallbackMessage.m deleted file mode 100644 index 87d1f2ae2..000000000 --- a/SessionProtocolKit/Signal/CipherMessage/FallbackMessage.m +++ /dev/null @@ -1,18 +0,0 @@ -#import "FallbackMessage.h" - -@implementation FallbackMessage - -- (instancetype)init_throws_withData:(NSData *)serialized -{ - if (self = [super init]) { - _serialized = serialized; - } - return self; -} - -- (CipherMessageType)cipherMessageType -{ - return CipherMessageType_Fallback; -} - -@end diff --git a/SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.h b/SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.h deleted file mode 100644 index d64aaa289..000000000 --- a/SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.h +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "WhisperMessage.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface PreKeyWhisperMessage : NSObject - -- (instancetype)init_throws_withData:(NSData *)serialized NS_SWIFT_UNAVAILABLE("throws objc exceptions"); -- (nullable instancetype)initWithData:(NSData *)serialized error:(NSError **)outError; - -- (instancetype)init_throws_withWhisperMessage:(WhisperMessage *)whisperMessage - registrationId:(int)registrationId - prekeyId:(int)prekeyId - signedPrekeyId:(int)signedPrekeyId - baseKey:(NSData *)baseKey - identityKey:(NSData *)identityKey NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -@property (nonatomic, readonly) int registrationId; -@property (nonatomic, readonly) int version; -@property (nonatomic, readonly) int prekeyID; -@property (nonatomic, readonly) int signedPrekeyId; -@property (nonatomic, readonly) NSData *baseKey; -@property (nonatomic, readonly) NSData *identityKey; -@property (nonatomic, readonly) WhisperMessage *message; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.m b/SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.m deleted file mode 100644 index e011fc666..000000000 --- a/SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.m +++ /dev/null @@ -1,149 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "PreKeyWhisperMessage.h" -#import "AxolotlExceptions.h" -#import "Constants.h" -#import "SerializationUtilities.h" -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface PreKeyWhisperMessage () - -@property (nonatomic, readwrite) NSData *identityKey; -@property (nonatomic, readwrite) NSData *baseKey; -@property (nonatomic, readwrite) NSData *serialized; - -@end - -#pragma mark - - -@implementation PreKeyWhisperMessage - -- (instancetype)init_throws_withWhisperMessage:(WhisperMessage *)whisperMessage - registrationId:(int)registrationId - prekeyId:(int)prekeyId - signedPrekeyId:(int)signedPrekeyId - baseKey:(NSData *)baseKey - identityKey:(NSData *)identityKey -{ - OWSAssert(whisperMessage); - OWSAssert(baseKey); - OWSAssert(identityKey); - - if (self = [super init]) { - _registrationId = registrationId; - _version = whisperMessage.version; - _prekeyID = prekeyId; - _signedPrekeyId = signedPrekeyId; - _baseKey = baseKey; - _identityKey = identityKey; - _message = whisperMessage; - - SPKProtoTSProtoPreKeyWhisperMessageBuilder *messageBuilder = [SPKProtoTSProtoPreKeyWhisperMessage builderWithSignedPreKeyID:signedPrekeyId - baseKey:baseKey - identityKey:identityKey - message:whisperMessage.serialized]; - [messageBuilder setRegistrationID:registrationId]; - - if (prekeyId != -1) { - [messageBuilder setPreKeyID:prekeyId]; - } - - Byte versionByte = [SerializationUtilities intsToByteHigh:_version low:CURRENT_VERSION]; - NSMutableData *serialized = [NSMutableData dataWithBytes:&versionByte length:1]; - - NSError *error; - NSData *_Nullable messageData = [messageBuilder buildSerializedDataAndReturnError:&error]; - if (!messageData || error) { - OWSFailDebug(@"Could not serialize proto: %@.", error); - OWSRaiseException(InvalidMessageException, @"Could not serialize proto."); - } - [serialized appendData:messageData]; - - _serialized = [serialized copy]; - } - - return self; -} - -- (nullable instancetype)initWithData:(NSData *)serialized error:(NSError **)outError -{ - @try { - self = [self init_throws_withData:serialized]; - return self; - } @catch (NSException *exception) { - *outError = SCKExceptionWrapperErrorMake(exception); - return nil; - } -} - -- (instancetype)init_throws_withData:(NSData *)serialized -{ - if (self = [super init]) { - if (serialized.length < 1) { - OWSFailDebug(@"Empty data"); - OWSRaiseException(InvalidMessageException, @"Empty data"); - } - - Byte version; - [serialized getBytes:&version length:1]; - _version = [SerializationUtilities highBitsToIntFromByte:version]; - - if (_version > CURRENT_VERSION && _version < MINIMUM_SUPPORTED_VERSION) { - @throw [NSException exceptionWithName:InvalidVersionException - reason:@"Unknown version" - userInfo:@{ @"version" : [NSNumber numberWithInt:_version] }]; - } - - NSUInteger messageDataLength; - ows_sub_overflow(serialized.length, 1, &messageDataLength); - NSData *messageData = [serialized subdataWithRange:NSMakeRange(1, messageDataLength)]; - - NSError *error; - SPKProtoTSProtoPreKeyWhisperMessage *_Nullable preKeyWhisperMessage = - [SPKProtoTSProtoPreKeyWhisperMessage parseData:messageData error:&error]; - if (!preKeyWhisperMessage || error) { - OWSFailDebug(@"Could not parse proto: %@.", error); - OWSRaiseException(InvalidMessageException, @"Could not parse proto."); - } - - _serialized = serialized; - _registrationId = preKeyWhisperMessage.registrationID; - - // This method is called when decrypting a received PreKeyMessage, but to be symmetrical with - // encrypting a PreKeyWhisperMessage before sending, we use "-1" to indicate *no* unsigned prekey was - // included. - _prekeyID = preKeyWhisperMessage.hasPreKeyID ? preKeyWhisperMessage.preKeyID : -1; - _signedPrekeyId = preKeyWhisperMessage.signedPreKeyID; - _baseKey = preKeyWhisperMessage.baseKey; - _identityKey = preKeyWhisperMessage.identityKey; - _message = [[WhisperMessage alloc] init_throws_withData:preKeyWhisperMessage.message]; - } - - return self; -} - -- (CipherMessageType)cipherMessageType { - return CipherMessageType_Prekey; -} - -#pragma mark - Logging - -+ (NSString *)logTag -{ - return [NSString stringWithFormat:@"[%@]", self.class]; -} - -- (NSString *)logTag -{ - return self.class.logTag; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/CipherMessage/WhisperMessage.h b/SessionProtocolKit/Signal/CipherMessage/WhisperMessage.h deleted file mode 100644 index 7ab354448..000000000 --- a/SessionProtocolKit/Signal/CipherMessage/WhisperMessage.h +++ /dev/null @@ -1,40 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "CipherMessage.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -@class ECKeyPair; - -@interface WhisperMessage : NSObject - -@property (nonatomic, readonly) int version; -@property (nonatomic, readonly) NSData *senderRatchetKey; -@property (nonatomic, readonly) int previousCounter; -@property (nonatomic, readonly) int counter; -@property (nonatomic, readonly) NSData *cipherText; -@property (nonatomic, readonly) NSData *serialized; - -- (instancetype)init_throws_withData:(NSData *)serialized NS_SWIFT_UNAVAILABLE("throws objc exceptions"); -- (nullable instancetype)initWithData:(NSData *)serialized error:(NSError **)outError; - -- (instancetype)init_throws_withVersion:(int)version - macKey:(NSData *)macKey - senderRatchetKey:(NSData *)senderRatchetKey - counter:(int)counter - previousCounter:(int)previousCounter - cipherText:(NSData *)cipherText - senderIdentityKey:(NSData *)senderIdentityKey - receiverIdentityKey:(NSData *)receiverIdentityKey NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -- (void)throws_verifyMacWithVersion:(int)messageVersion - senderIdentityKey:(NSData *)senderIdentityKey - receiverIdentityKey:(NSData *)receiverIdentityKey - macKey:(NSData *)macKey NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/CipherMessage/WhisperMessage.m b/SessionProtocolKit/Signal/CipherMessage/WhisperMessage.m deleted file mode 100644 index 9c0526dc5..000000000 --- a/SessionProtocolKit/Signal/CipherMessage/WhisperMessage.m +++ /dev/null @@ -1,202 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "WhisperMessage.h" -#import "AxolotlExceptions.h" -#import "Constants.h" -#import "NSData+keyVersionByte.h" -#import "SerializationUtilities.h" -#import -#import -#import -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -#define VERSION_LENGTH 1 - -@implementation WhisperMessage - -- (instancetype)init_throws_withVersion:(int)version - macKey:(NSData *)macKey - senderRatchetKey:(NSData *)senderRatchetKey - counter:(int)counter - previousCounter:(int)previousCounter - cipherText:(NSData *)cipherText - senderIdentityKey:(NSData *)senderIdentityKey - receiverIdentityKey:(NSData *)receiverIdentityKey -{ - OWSAssert(macKey); - OWSAssert(senderRatchetKey); - OWSAssert(cipherText); - OWSAssert(cipherText); - OWSAssert(senderIdentityKey); - OWSAssert(receiverIdentityKey); - - if (self = [super init]) { - Byte versionByte = [SerializationUtilities intsToByteHigh:version low:CURRENT_VERSION]; - NSMutableData *serialized = [NSMutableData dataWithBytes:&versionByte length:1]; - - SPKProtoTSProtoWhisperMessageBuilder *messageBuilder = [SPKProtoTSProtoWhisperMessage builderWithRatchetKey:senderRatchetKey - counter:counter - ciphertext:cipherText]; - [messageBuilder setPreviousCounter:previousCounter]; - NSError *error; - NSData *_Nullable messageData = [messageBuilder buildSerializedDataAndReturnError:&error]; - if (!messageData || error) { - OWSFailDebug(@"Could not serialize proto: %@.", error); - OWSRaiseException(InvalidMessageException, @"Could not serialize proto."); - } - [serialized appendData:messageData]; - - NSData *mac = [SerializationUtilities throws_macWithVersion:version - identityKey:[senderIdentityKey prependKeyType] - receiverIdentityKey:[receiverIdentityKey prependKeyType] - macKey:macKey - serialized:serialized]; - - [serialized appendData:mac]; - - _version = version; - _senderRatchetKey = senderRatchetKey; - _previousCounter = previousCounter; - _counter = counter; - _cipherText = cipherText; - _serialized = [serialized copy]; - } - - return self; -} - -- (nullable instancetype)initWithData:(NSData *)serialized error:(NSError **)outError -{ - @try { - self = [self init_throws_withData:serialized]; - return self; - } @catch (NSException *exception) { - *outError = SCKExceptionWrapperErrorMake(exception); - return nil; - } -} - -- (instancetype)init_throws_withData:(NSData *)serialized -{ - if (self = [super init]) { - if (serialized.length <= (VERSION_LENGTH + MAC_LENGTH)) { - @throw [NSException exceptionWithName:InvalidMessageException - reason:@"Message size is too short to have content" - userInfo:@{}]; - } - - Byte version; - [serialized getBytes:&version length:VERSION_LENGTH]; - - NSUInteger messageAndMacLength; - ows_sub_overflow(serialized.length, VERSION_LENGTH, &messageAndMacLength); - NSData *messageAndMac = [serialized subdataWithRange:NSMakeRange(VERSION_LENGTH, messageAndMacLength)]; - - NSUInteger messageLength; - ows_sub_overflow(messageAndMac.length, MAC_LENGTH, &messageLength); - NSData *messageData = [messageAndMac subdataWithRange:NSMakeRange(0, messageLength)]; - - if ([SerializationUtilities highBitsToIntFromByte:version] < MINIMUM_SUPPORTED_VERSION) { - @throw [NSException - exceptionWithName:LegacyMessageException - reason:@"Message was sent with an unsupported version of the TextSecure protocol." - userInfo:@{}]; - } - - if ([SerializationUtilities highBitsToIntFromByte:version] > CURRENT_VERSION) { - @throw [NSException exceptionWithName:InvalidMessageException - reason:@"Unknown Version" - userInfo:@{ - @"Version" : [NSNumber - numberWithChar:[SerializationUtilities highBitsToIntFromByte:version]] - }]; - } - - NSError *error; - SPKProtoTSProtoWhisperMessage *_Nullable whisperMessage = - [SPKProtoTSProtoWhisperMessage parseData:messageData error:&error]; - if (!whisperMessage || error) { - OWSFailDebug(@"Could not parse proto: %@.", error); - OWSRaiseException(InvalidMessageException, @"Could not parse proto."); - } - - _serialized = serialized; - _senderRatchetKey = [whisperMessage.ratchetKey throws_removeKeyType]; - _version = [SerializationUtilities highBitsToIntFromByte:version]; - _counter = whisperMessage.counter; - _previousCounter = whisperMessage.previousCounter; - _cipherText = whisperMessage.ciphertext; - } - - return self; -} - -- (void)throws_verifyMacWithVersion:(int)messageVersion - senderIdentityKey:(NSData *)senderIdentityKey - receiverIdentityKey:(NSData *)receiverIdentityKey - macKey:(NSData *)macKey -{ - OWSAssert(senderIdentityKey); - OWSAssert(receiverIdentityKey); - OWSAssert(macKey); - - OWSDataParser *dataParser = [[OWSDataParser alloc] initWithData:self.serialized]; - NSError *error; - - NSUInteger messageLength; - if (__builtin_sub_overflow(self.serialized.length, MAC_LENGTH, &messageLength)) { - OWSFailDebug(@"Data too short"); - OWSRaiseException(InvalidMessageException, @"Data too short"); - } - NSData *_Nullable data = [dataParser nextDataWithLength:messageLength - name:@"message data" - error:&error]; - if (!data || error) { - OWSFailDebug(@"Could not parse data: %@.", error); - OWSRaiseException(InvalidMessageException, @"Could not parse data."); - } - NSData *_Nullable theirMac = [dataParser nextDataWithLength:MAC_LENGTH - name:@"mac data" - error:&error]; - if (!theirMac || error) { - OWSFailDebug(@"Could not parse their mac: %@.", error); - OWSRaiseException(InvalidMessageException, @"Could not parse their mac."); - } - - NSData *ourMac = [SerializationUtilities throws_macWithVersion:messageVersion - identityKey:[senderIdentityKey prependKeyType] - receiverIdentityKey:[receiverIdentityKey prependKeyType] - macKey:macKey - serialized:data]; - - if (![theirMac ows_constantTimeIsEqualToData:ourMac]) { - OWSFailDebug(@"Bad Mac! Their Mac: %@ Our Mac: %@", theirMac, ourMac); - OWSRaiseException(InvalidMessageException, @"Bad Mac!"); - } -} - -- (CipherMessageType)cipherMessageType { - return CipherMessageType_Whisper; -} - -#pragma mark - Logging - -+ (NSString *)logTag -{ - return [NSString stringWithFormat:@"[%@]", self.class]; -} - -- (NSString *)logTag -{ - return self.class.logTag; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Constants.h b/SessionProtocolKit/Signal/Constants.h deleted file mode 100644 index edc957b3e..000000000 --- a/SessionProtocolKit/Signal/Constants.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Constants.h -// AxolotlKit -// -// Created by Frederic Jacobs on 14/10/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#ifndef AxolotlKit_Constants_h -#define AxolotlKit_Constants_h - -#define MINIMUM_SUPPORTED_VERSION 3 -#define CURRENT_VERSION 3 - -#endif diff --git a/SessionProtocolKit/Signal/Crypto/AES-CBC.h b/SessionProtocolKit/Signal/Crypto/AES-CBC.h deleted file mode 100644 index 7862f0915..000000000 --- a/SessionProtocolKit/Signal/Crypto/AES-CBC.h +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface AES_CBC : NSObject - -/** - * Encrypts with AES in CBC mode - * - * @param data data to encrypt - * @param key AES key - * @param iv Initialization vector for CBC - * - * @return ciphertext - */ - -+ (NSData *)throws_encryptCBCMode:(NSData *)data - withKey:(NSData *)key - withIV:(NSData *)iv NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -/** - * Decrypts with AES in CBC mode - * - * @param data data to decrypt - * @param key AES key - * @param iv Initialization vector for CBC - * - * @return plaintext - */ - -+ (NSData *)throws_decryptCBCMode:(NSData *)data - withKey:(NSData *)key - withIV:(NSData *)iv NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Crypto/AES-CBC.m b/SessionProtocolKit/Signal/Crypto/AES-CBC.m deleted file mode 100644 index 720157b6e..000000000 --- a/SessionProtocolKit/Signal/Crypto/AES-CBC.m +++ /dev/null @@ -1,105 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "AES-CBC.h" -#import "AxolotlExceptions.h" -#import "MessageKeys.h" -#import -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@implementation AES_CBC - -#pragma mark AESCBC Mode - -+ (NSData *)throws_encryptCBCMode:(NSData *)data withKey:(NSData *)key withIV:(NSData *)iv -{ - if (!data) { - @throw [NSException exceptionWithName:CipherException reason:@"Missing data to encrypt." userInfo:nil]; - } - if (data.length >= SIZE_MAX - kCCBlockSizeAES128) { - @throw [NSException exceptionWithName:CipherException reason:@"Oversize data." userInfo:nil]; - } - if (key.length != 32) { - @throw [NSException exceptionWithName:CipherException reason:@"AES key should be 256 bits." userInfo:nil]; - } - if (iv.length != 16) { - @throw [NSException exceptionWithName:CipherException reason:@"AES-CBC IV should be 128 bits." userInfo:nil]; - } - - size_t bufferSize; - ows_add_overflow(data.length, kCCBlockSizeAES128, &bufferSize); - NSMutableData *_Nullable bufferData = [NSMutableData dataWithLength:bufferSize]; - OWSAssert(bufferData != nil); - - size_t bytesEncrypted = 0; - CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, - kCCAlgorithmAES128, - kCCOptionPKCS7Padding, - [key bytes], - [key length], - [iv bytes], - [data bytes], - [data length], - bufferData.mutableBytes, - bufferSize, - &bytesEncrypted); - - if (cryptStatus == kCCSuccess) { - return [bufferData subdataWithRange:NSMakeRange(0, bytesEncrypted)]; - } else { - @throw [NSException exceptionWithName:CipherException - reason:@"We encountered an issue while encrypting." - userInfo:nil]; - } -} - -+ (NSData *)throws_decryptCBCMode:(NSData *)data withKey:(NSData *)key withIV:(NSData *)iv -{ - if (!data) { - @throw [NSException exceptionWithName:CipherException reason:@"Missing data to decrypt." userInfo:nil]; - } - if (data.length >= SIZE_MAX - kCCBlockSizeAES128) { - @throw [NSException exceptionWithName:CipherException reason:@"Oversize data." userInfo:nil]; - } - if (key.length != 32) { - @throw [NSException exceptionWithName:CipherException reason:@"AES key should be 256 bits." userInfo:nil]; - } - if (iv.length != 16) { - @throw [NSException exceptionWithName:CipherException reason:@"AES-CBC IV should be 128 bits." userInfo:nil]; - } - - size_t bufferSize; - ows_add_overflow(data.length, kCCBlockSizeAES128, &bufferSize); - NSMutableData *_Nullable bufferData = [NSMutableData dataWithLength:bufferSize]; - OWSAssert(bufferData != nil); - - size_t bytesDecrypted = 0; - CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, - kCCAlgorithmAES128, - kCCOptionPKCS7Padding, - [key bytes], - [key length], - [iv bytes], - [data bytes], - [data length], - bufferData.mutableBytes, - bufferSize, - &bytesDecrypted); - - if (cryptStatus == kCCSuccess) { - return [bufferData subdataWithRange:NSMakeRange(0, bytesDecrypted)]; - } else { - @throw [NSException exceptionWithName:CipherException - reason:@"We encountered an issue while decrypting." - userInfo:nil]; - } -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/FallbackSessionCipher.swift b/SessionProtocolKit/Signal/FallbackSessionCipher.swift deleted file mode 100644 index 897f44c60..000000000 --- a/SessionProtocolKit/Signal/FallbackSessionCipher.swift +++ /dev/null @@ -1,51 +0,0 @@ -import CryptoSwift -import Curve25519Kit -import SessionUtilitiesKit - -/// A fallback session cipher which uses the the recipient's public key to encrypt data. -@objc public final class FallBackSessionCipher : NSObject { - /// The hex encoded public key of the recipient. - private let recipientPublicKey: String - private let privateKey: Data? - private let ivSize: Int32 = 16 - - private lazy var recipientPublicKeyAsData: Data = { - var recipientPublicKey = self.recipientPublicKey - if recipientPublicKey.count == 66 && recipientPublicKey.hasPrefix("05") { - let index = recipientPublicKey.index(recipientPublicKey.startIndex, offsetBy: 2) - recipientPublicKey = recipientPublicKey.substring(from: index) - } - return Data(hex: recipientPublicKey) - }() - - private lazy var symmetricKey: Data? = { - guard let privateKey = privateKey else { return nil } - return try? Curve25519.generateSharedSecret(fromPublicKey: recipientPublicKeyAsData, privateKey: privateKey) - }() - - @objc public init(recipientPublicKey: String, privateKey: Data?) { - self.recipientPublicKey = recipientPublicKey - self.privateKey = privateKey - super.init() - } - - @objc public func encrypt(_ plaintext: Data) -> Data? { - guard let symmetricKey = symmetricKey else { return nil } - do { - return try DiffieHellman.encrypt(plaintext, using: symmetricKey) - } catch { - SNLog("Couldn't encrypt message using fallback session cipher due to error: \(error).") - return nil - } - } - - @objc public func decrypt(_ ivAndCiphertext: Data) -> Data? { - guard let symmetricKey = symmetricKey else { return nil } - do { - return try DiffieHellman.decrypt(ivAndCiphertext, using: symmetricKey) - } catch { - SNLog("Couldn't decrypt message using fallback session cipher due to error: \(error).") - return nil - } - } -} diff --git a/SessionProtocolKit/Signal/LokiSessionCipher.swift b/SessionProtocolKit/Signal/LokiSessionCipher.swift deleted file mode 100644 index 63bc02cf7..000000000 --- a/SessionProtocolKit/Signal/LokiSessionCipher.swift +++ /dev/null @@ -1,104 +0,0 @@ -import Foundation - -@objc(SNSessionCipher) -public final class LokiSessionCipher : SessionCipher { - private let sessionResetImplementation: SessionRestorationProtocol? - private let sessionStore: SessionStore - private let preKeyStore: PreKeyStore - private let recipientID: String - private let deviceID: Int32 - - @objc public static let newSessionAdoptedNotification = "LKNewSessionAdoptedNotification" - @objc public static let contactKey = "LKContactKey" - - @objc public init(sessionResetImplementation: SessionRestorationProtocol, sessionStore: SessionStore, preKeyStore: PreKeyStore, signedPreKeyStore: SignedPreKeyStore, identityKeyStore: IdentityKeyStore, recipientID: String, deviceID: Int32) { - self.sessionResetImplementation = sessionResetImplementation - self.sessionStore = sessionStore - self.preKeyStore = preKeyStore - self.recipientID = recipientID - self.deviceID = deviceID - super.init(sessionStore: sessionStore, preKeyStore: preKeyStore, signedPreKeyStore: signedPreKeyStore, identityKeyStore: identityKeyStore, recipientId: recipientID, deviceId: deviceID) - } - - @available(*, unavailable) - override convenience private init(axolotlStore sessionStore: AxolotlStore, recipientId: String, deviceId: Int32) { - self.init(sessionStore: sessionStore, preKeyStore: sessionStore, signedPreKeyStore: sessionStore, identityKeyStore: sessionStore, recipientId: recipientId, deviceId: deviceId) - } - - override private init(sessionStore: SessionStore, preKeyStore: PreKeyStore, signedPreKeyStore: SignedPreKeyStore, identityKeyStore: IdentityKeyStore, recipientId: String, deviceId: Int32) { - self.sessionResetImplementation = nil - self.sessionStore = sessionStore - self.preKeyStore = preKeyStore - self.recipientID = recipientId - self.deviceID = deviceId - super.init(sessionStore: sessionStore, preKeyStore: preKeyStore, signedPreKeyStore: signedPreKeyStore, identityKeyStore: identityKeyStore, recipientId: recipientId, deviceId: deviceId) - } - - override public func decrypt(_ whisperMessage: CipherMessage, protocolContext: Any?) throws -> Data { - // Note that while decrypting our state may change internally - let currentState = getCurrentState(protocolContext: protocolContext) - if (currentState == nil && whisperMessage.cipherMessageType == .prekey) { - try sessionResetImplementation?.validatePreKeyWhisperMessage(for: recipientID, preKeyWhisperMessage: whisperMessage as! PreKeyWhisperMessage, using: protocolContext!) - } - let plainText = try super.decrypt(whisperMessage, protocolContext: protocolContext) - handleSessionReset(for: whisperMessage, previousState: currentState, protocolContext: protocolContext!) - return plainText - } - - private func getCurrentState(protocolContext: Any?) -> SessionState? { - let record = sessionStore.loadSession(recipientID, deviceId: deviceID, protocolContext: protocolContext) - return record.isFresh() ? nil : record.sessionState() - } - - private func handleSessionReset(for whisperMessage: CipherMessage, previousState: SessionState?, protocolContext: Any) { - // Don't bother doing anything if we didn't have a session before - guard let previousState = previousState else { return } - let sessionResetStatus = sessionResetImplementation?.getSessionRestorationStatus(for: recipientID) ?? SessionRestorationStatus.none - // Bail early if no session reset is in progress - guard sessionResetStatus != .none else { return } - let currentState = getCurrentState(protocolContext: protocolContext) - // Check if our previous state and our current state differ - if (currentState == nil || currentState!.aliceBaseKey != previousState.aliceBaseKey) { - if sessionResetStatus == .requestReceived { - // The other user used an old session to contact us. Wait for them to use a new one - restoreSession(previousState, protocolContext: protocolContext) - } else { - // Our session reset went through successfully. - // We initiated a session reset and got a different session back from the user. - deleteAllSessions(except: currentState, protocolContext: protocolContext) - notifySessionAdopted(protocolContext) - } - } else if sessionResetStatus == .requestReceived { - // Our session reset went through successfully. - // We got a message with the same session from the other user. - deleteAllSessions(except: previousState, protocolContext: protocolContext) - notifySessionAdopted(protocolContext) - } - } - - private func notifySessionAdopted(_ protocolContext: Any) { - self.sessionResetImplementation?.handleNewSessionAdopted(for: recipientID, using: protocolContext) - NotificationCenter.default.post(name: NSNotification.Name(rawValue: LokiSessionCipher.newSessionAdoptedNotification), object: nil, userInfo: [ LokiSessionCipher.contactKey : recipientID ]) - } - - private func deleteAllSessions(except state: SessionState?, protocolContext: Any?) { - let record = sessionStore.loadSession(recipientID, deviceId: deviceID, protocolContext: protocolContext) - record.removePreviousSessionStates() - let newState = state ?? SessionState() - record.setState(newState) - sessionStore.storeSession(recipientID, deviceId: deviceID, session: record, protocolContext: protocolContext) - } - - private func restoreSession(_ state: SessionState, protocolContext: Any?) { - let record = sessionStore.loadSession(recipientID, deviceId: deviceID, protocolContext: protocolContext) - // Remove the state from previous session states - record.previousSessionStates()?.enumerateObjects(options: .reverse) { obj, index, stop in - guard let obj = obj as? SessionState, state.aliceBaseKey == obj.aliceBaseKey else { return } - record.previousSessionStates()?.removeObject(at: index) - stop.pointee = true - } - // Promote so the previous state gets archived - record.promoteState(state) - sessionStore.storeSession(recipientID, deviceId: deviceID, session: record, protocolContext: protocolContext) - } -} diff --git a/SessionProtocolKit/Signal/Prekeys/PreKeyBundle.h b/SessionProtocolKit/Signal/Prekeys/PreKeyBundle.h deleted file mode 100644 index b81791123..000000000 --- a/SessionProtocolKit/Signal/Prekeys/PreKeyBundle.h +++ /dev/null @@ -1,31 +0,0 @@ -// -// AxolotlKeyFetch.h -// AxolotlKit -// -// Created by Frederic Jacobs on 21/07/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import - -@interface PreKeyBundle : NSObject - -@property (nonatomic, readonly) NSData *identityKey; -@property (nonatomic, readonly) int registrationId; -@property (nonatomic, readonly) int deviceId; -@property (nonatomic, readonly) NSData *signedPreKeyPublic; -@property (nonatomic, readonly) NSData *preKeyPublic; -@property (nonatomic, readonly) int preKeyId; -@property (nonatomic, readonly) int signedPreKeyId; -@property (nonatomic, readonly) NSData *signedPreKeySignature; - -- (nullable instancetype)initWithRegistrationId:(int)registrationId - deviceId:(int)deviceId - preKeyId:(int)preKeyId - preKeyPublic:(NSData *)preKeyPublic - signedPreKeyPublic:(NSData *)signedPreKeyPublic - signedPreKeyId:(int)signedPreKeyId - signedPreKeySignature:(NSData *)signedPreKeySignature - identityKey:(NSData *)identityKey; - -@end diff --git a/SessionProtocolKit/Signal/Prekeys/PreKeyBundle.m b/SessionProtocolKit/Signal/Prekeys/PreKeyBundle.m deleted file mode 100644 index b420eb84f..000000000 --- a/SessionProtocolKit/Signal/Prekeys/PreKeyBundle.m +++ /dev/null @@ -1,106 +0,0 @@ -// -// AxolotlKeyFetch.m -// AxolotlKit -// -// Created by Frederic Jacobs on 21/07/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import "PreKeyBundle.h" -#import - - -static NSString* const kCoderPKBIdentityKey = @"kCoderPKBIdentityKey"; -static NSString* const kCoderPKBregistrationId = @"kCoderPKBregistrationId"; -static NSString* const kCoderPKBdeviceId = @"kCoderPKBdeviceId"; -static NSString* const kCoderPKBsignedPreKeyPublic = @"kCoderPKBsignedPreKeyPublic"; -static NSString* const kCoderPKBpreKeyPublic = @"kCoderPKBpreKeyPublic"; -static NSString* const kCoderPKBpreKeyId = @"kCoderPKBpreKeyId"; -static NSString* const kCoderPKBsignedPreKeyId = @"kCoderPKBsignedPreKeyId"; -static NSString* const kCoderPKBsignedPreKeySignature = @"kCoderPKBsignedPreKeySignature"; - -@implementation PreKeyBundle - -- (nullable instancetype)initWithRegistrationId:(int)registrationId - deviceId:(int)deviceId - preKeyId:(int)preKeyId - preKeyPublic:(NSData *)preKeyPublic - signedPreKeyPublic:(NSData *)signedPreKeyPublic - signedPreKeyId:(int)signedPreKeyId - signedPreKeySignature:(NSData *)signedPreKeySignature - identityKey:(NSData *)identityKey -{ - if (preKeyPublic && preKeyPublic.length != 33) { - OWSFailDebug(@"preKeyPublic && preKeyPublic.length != 33"); - return nil; - } - if (signedPreKeyPublic.length != 33) { - OWSFailDebug(@"signedPreKeyPublic.length != 33"); - return nil; - } - if (!signedPreKeySignature) { - OWSFailDebug(@"!signedPreKeySignature"); - return nil; - } - if (identityKey.length != 33) { - OWSFailDebug(@"identityKey.length != 33"); - return nil; - } - - self = [super init]; - - if (self) { - _identityKey = identityKey; - _registrationId = registrationId; - _deviceId = deviceId; - _preKeyPublic = preKeyPublic; - _preKeyId = preKeyId; - _signedPreKeyPublic = signedPreKeyPublic; - _signedPreKeyId = signedPreKeyId; - _signedPreKeySignature = signedPreKeySignature; - } - - return self; -} - -- (id)initWithCoder:(NSCoder *)aDecoder{ - int registrationId = [aDecoder decodeIntForKey:kCoderPKBregistrationId]; - int deviceId = [aDecoder decodeIntForKey:kCoderPKBdeviceId]; - int preKeyId = [aDecoder decodeIntForKey:kCoderPKBpreKeyId]; - int signedPreKeyId = [aDecoder decodeIntForKey:kCoderPKBsignedPreKeyId]; - - NSData *preKeyPublic = [aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderPKBpreKeyPublic]; - NSData *signedPreKeyPublic = [aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderPKBsignedPreKeyPublic]; - NSData *signedPreKeySignature = [aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderPKBsignedPreKeySignature]; - NSData *identityKey = [aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderPKBIdentityKey]; - - - self = [self initWithRegistrationId:registrationId - deviceId:deviceId - preKeyId:preKeyId - preKeyPublic:preKeyPublic - signedPreKeyPublic:signedPreKeyPublic - signedPreKeyId:signedPreKeyId - signedPreKeySignature:signedPreKeySignature - identityKey:identityKey]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder{ - [aCoder encodeInt:_registrationId forKey:kCoderPKBregistrationId]; - [aCoder encodeInt:_deviceId forKey:kCoderPKBdeviceId]; - [aCoder encodeInt:_preKeyId forKey:kCoderPKBpreKeyId]; - [aCoder encodeInt:_signedPreKeyId forKey:kCoderPKBsignedPreKeyId]; - - [aCoder encodeObject:_preKeyPublic forKey:kCoderPKBpreKeyPublic]; - [aCoder encodeObject:_signedPreKeyPublic forKey:kCoderPKBsignedPreKeyPublic]; - [aCoder encodeObject:_signedPreKeySignature forKey:kCoderPKBsignedPreKeySignature]; - [aCoder encodeObject:_identityKey forKey:kCoderPKBIdentityKey]; -} - -+(BOOL)supportsSecureCoding{ - return YES; -} - -@end diff --git a/SessionProtocolKit/Signal/Prekeys/PreKeyRecord.h b/SessionProtocolKit/Signal/Prekeys/PreKeyRecord.h deleted file mode 100644 index ddd58647d..000000000 --- a/SessionProtocolKit/Signal/Prekeys/PreKeyRecord.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import -#import - - -@interface PreKeyRecord : NSObject - -@property (nonatomic, readonly) int Id; -@property (nonatomic, readonly) ECKeyPair *keyPair; - -- (instancetype)initWithId:(int)identifier keyPair:(ECKeyPair*)keyPair; - -@end diff --git a/SessionProtocolKit/Signal/Prekeys/PreKeyRecord.m b/SessionProtocolKit/Signal/Prekeys/PreKeyRecord.m deleted file mode 100644 index 13c8e4c8b..000000000 --- a/SessionProtocolKit/Signal/Prekeys/PreKeyRecord.m +++ /dev/null @@ -1,45 +0,0 @@ -// -// PreKeyRecord.m -// AxolotlKit -// -// Created by Frederic Jacobs on 26/07/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import "PreKeyRecord.h" -#import - -static NSString* const kCoderPreKeyId = @"kCoderPreKeyId"; -static NSString* const kCoderPreKeyPair = @"kCoderPreKeyPair"; - -@implementation PreKeyRecord - -+ (BOOL)supportsSecureCoding{ - return YES; -} - -- (instancetype)initWithId:(int)identifier keyPair:(ECKeyPair*)keyPair{ - OWSAssert(keyPair); - - self = [super init]; - - if (self) { - _Id = identifier; - _keyPair = keyPair; - } - - return self; -} - -- (id)initWithCoder:(NSCoder *)aDecoder{ - return [self initWithId:[aDecoder decodeIntForKey:kCoderPreKeyId] keyPair:[aDecoder decodeObjectOfClass:[ECKeyPair class] forKey:kCoderPreKeyPair]]; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder{ - [aCoder encodeInteger:_Id forKey:kCoderPreKeyId]; - [aCoder encodeObject:_keyPair forKey:kCoderPreKeyPair]; -} - - - -@end diff --git a/SessionProtocolKit/Signal/Prekeys/SignedPrekeyRecord.h b/SessionProtocolKit/Signal/Prekeys/SignedPrekeyRecord.h deleted file mode 100644 index 6bf27ce39..000000000 --- a/SessionProtocolKit/Signal/Prekeys/SignedPrekeyRecord.h +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import -#import "PreKeyRecord.h" -#import - -@interface SignedPreKeyRecord : PreKeyRecord - -@property (nonatomic, readonly) NSData *signature; -@property (nonatomic, readonly) NSDate *generatedAt; -// Defaults to NO. Should only be set after the service accepts this record. -@property (nonatomic, readonly) BOOL wasAcceptedByService; - -- (instancetype)initWithId:(int)identifier keyPair:(ECKeyPair *)keyPair signature:(NSData*)signature generatedAt:(NSDate*)generatedAt; -- (instancetype)initWithId:(int)identifier keyPair:(ECKeyPair *)keyPair NS_UNAVAILABLE; - -- (void)markAsAcceptedByService; - -@end diff --git a/SessionProtocolKit/Signal/Prekeys/SignedPrekeyRecord.m b/SessionProtocolKit/Signal/Prekeys/SignedPrekeyRecord.m deleted file mode 100644 index 46d3e25e6..000000000 --- a/SessionProtocolKit/Signal/Prekeys/SignedPrekeyRecord.m +++ /dev/null @@ -1,78 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import "SignedPrekeyRecord.h" -#import - -static NSString* const kCoderPreKeyId = @"kCoderPreKeyId"; -static NSString* const kCoderPreKeyPair = @"kCoderPreKeyPair"; -static NSString* const kCoderPreKeyDate = @"kCoderPreKeyDate"; -static NSString* const kCoderPreKeySignature = @"kCoderPreKeySignature"; -static NSString *const kCoderPreKeyWasAcceptedByService = @"kCoderPreKeyWasAcceptedByService"; - -@implementation SignedPreKeyRecord - -+ (BOOL)supportsSecureCoding{ - return YES; -} - -- (instancetype)initWithId:(int)identifier - keyPair:(ECKeyPair *)keyPair - signature:(NSData *)signature - generatedAt:(NSDate *)generatedAt - wasAcceptedByService:(BOOL)wasAcceptedByService -{ - OWSAssert(keyPair); - OWSAssert(signature); - OWSAssert(generatedAt); - - self = [super initWithId:identifier keyPair:keyPair]; - - if (self) { - _signature = signature; - _generatedAt = generatedAt; - _wasAcceptedByService = wasAcceptedByService; - } - - return self; -} - -- (instancetype)initWithId:(int)identifier keyPair:(ECKeyPair *)keyPair signature:(NSData*)signature generatedAt:(NSDate *)generatedAt{ - self = [super initWithId:identifier keyPair:keyPair]; - - if (self) { - _signature = signature; - _generatedAt = generatedAt; - } - - return self; -} - -- (id)initWithCoder:(NSCoder *)aDecoder{ - return [self initWithId:[aDecoder decodeIntForKey:kCoderPreKeyId] - keyPair:[aDecoder decodeObjectOfClass:[ECKeyPair class] forKey:kCoderPreKeyPair] - signature:[aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderPreKeySignature] - generatedAt:[aDecoder decodeObjectOfClass:[NSDate class] forKey:kCoderPreKeyDate] - wasAcceptedByService:[aDecoder decodeBoolForKey:kCoderPreKeyWasAcceptedByService]]; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder{ - [aCoder encodeInt:self.Id forKey:kCoderPreKeyId]; - [aCoder encodeObject:self.keyPair forKey:kCoderPreKeyPair]; - [aCoder encodeObject:self.signature forKey:kCoderPreKeySignature]; - [aCoder encodeObject:self.generatedAt forKey:kCoderPreKeyDate]; - [aCoder encodeBool:self.wasAcceptedByService forKey:kCoderPreKeyWasAcceptedByService]; -} - -- (instancetype)initWithId:(int)identifier keyPair:(ECKeyPair*)keyPair{ - OWSAbstractMethod(); - return nil; -} - -- (void)markAsAcceptedByService -{ - _wasAcceptedByService = YES; -} - -@end diff --git a/SessionProtocolKit/Signal/Protos/OWSUnidentifiedDelivery.pb.swift b/SessionProtocolKit/Signal/Protos/OWSUnidentifiedDelivery.pb.swift deleted file mode 100644 index ad0de59b8..000000000 --- a/SessionProtocolKit/Signal/Protos/OWSUnidentifiedDelivery.pb.swift +++ /dev/null @@ -1,571 +0,0 @@ -// DO NOT EDIT. -// swift-format-ignore-file -// -// Generated by the Swift generator plugin for the protocol buffer compiler. -// Source: OWSUnidentifiedDelivery.proto -// -// For information on using the generated types, please see the documentation: -// https://github.com/apple/swift-protobuf/ - -//* -// Copyright (C) 2014-2016 Open Whisper Systems -// -// Licensed according to the LICENSE file in this repository. - -/// iOS - since we use a modern proto-compiler, we must specify -/// the legacy proto format. - -import Foundation -import SwiftProtobuf - -// If the compiler emits an error on this type, it is because this file -// was generated by a version of the `protoc` Swift plug-in that is -// incompatible with the version of SwiftProtobuf to which you are linking. -// Please ensure that you are building against the same version of the API -// that was used to generate this file. -fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { - struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} - typealias Version = _2 -} - -struct SMKProtos_ServerCertificate { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// @required - var certificate: Data { - get {return _certificate ?? SwiftProtobuf.Internal.emptyData} - set {_certificate = newValue} - } - /// Returns true if `certificate` has been explicitly set. - var hasCertificate: Bool {return self._certificate != nil} - /// Clears the value of `certificate`. Subsequent reads from it will return its default value. - mutating func clearCertificate() {self._certificate = nil} - - /// @required - var signature: Data { - get {return _signature ?? SwiftProtobuf.Internal.emptyData} - set {_signature = newValue} - } - /// Returns true if `signature` has been explicitly set. - var hasSignature: Bool {return self._signature != nil} - /// Clears the value of `signature`. Subsequent reads from it will return its default value. - mutating func clearSignature() {self._signature = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - struct Certificate { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// @required - var id: UInt32 { - get {return _id ?? 0} - set {_id = newValue} - } - /// Returns true if `id` has been explicitly set. - var hasID: Bool {return self._id != nil} - /// Clears the value of `id`. Subsequent reads from it will return its default value. - mutating func clearID() {self._id = nil} - - /// @required - var key: Data { - get {return _key ?? SwiftProtobuf.Internal.emptyData} - set {_key = newValue} - } - /// Returns true if `key` has been explicitly set. - var hasKey: Bool {return self._key != nil} - /// Clears the value of `key`. Subsequent reads from it will return its default value. - mutating func clearKey() {self._key = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _id: UInt32? = nil - fileprivate var _key: Data? = nil - } - - init() {} - - fileprivate var _certificate: Data? = nil - fileprivate var _signature: Data? = nil -} - -struct SMKProtos_SenderCertificate { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// @required - var sender: String { - get {return _sender ?? String()} - set {_sender = newValue} - } - /// Returns true if `sender` has been explicitly set. - var hasSender: Bool {return self._sender != nil} - /// Clears the value of `sender`. Subsequent reads from it will return its default value. - mutating func clearSender() {self._sender = nil} - - /// @required - var senderDevice: UInt32 { - get {return _senderDevice ?? 0} - set {_senderDevice = newValue} - } - /// Returns true if `senderDevice` has been explicitly set. - var hasSenderDevice: Bool {return self._senderDevice != nil} - /// Clears the value of `senderDevice`. Subsequent reads from it will return its default value. - mutating func clearSenderDevice() {self._senderDevice = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - struct Certificate { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// @required - var sender: String { - get {return _sender ?? String()} - set {_sender = newValue} - } - /// Returns true if `sender` has been explicitly set. - var hasSender: Bool {return self._sender != nil} - /// Clears the value of `sender`. Subsequent reads from it will return its default value. - mutating func clearSender() {self._sender = nil} - - /// @required - var senderDevice: UInt32 { - get {return _senderDevice ?? 0} - set {_senderDevice = newValue} - } - /// Returns true if `senderDevice` has been explicitly set. - var hasSenderDevice: Bool {return self._senderDevice != nil} - /// Clears the value of `senderDevice`. Subsequent reads from it will return its default value. - mutating func clearSenderDevice() {self._senderDevice = nil} - - /// @required - var expires: UInt64 { - get {return _expires ?? 0} - set {_expires = newValue} - } - /// Returns true if `expires` has been explicitly set. - var hasExpires: Bool {return self._expires != nil} - /// Clears the value of `expires`. Subsequent reads from it will return its default value. - mutating func clearExpires() {self._expires = nil} - - /// @required - var identityKey: Data { - get {return _identityKey ?? SwiftProtobuf.Internal.emptyData} - set {_identityKey = newValue} - } - /// Returns true if `identityKey` has been explicitly set. - var hasIdentityKey: Bool {return self._identityKey != nil} - /// Clears the value of `identityKey`. Subsequent reads from it will return its default value. - mutating func clearIdentityKey() {self._identityKey = nil} - - /// @required - var signer: SMKProtos_ServerCertificate { - get {return _signer ?? SMKProtos_ServerCertificate()} - set {_signer = newValue} - } - /// Returns true if `signer` has been explicitly set. - var hasSigner: Bool {return self._signer != nil} - /// Clears the value of `signer`. Subsequent reads from it will return its default value. - mutating func clearSigner() {self._signer = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _sender: String? = nil - fileprivate var _senderDevice: UInt32? = nil - fileprivate var _expires: UInt64? = nil - fileprivate var _identityKey: Data? = nil - fileprivate var _signer: SMKProtos_ServerCertificate? = nil - } - - init() {} - - fileprivate var _sender: String? = nil - fileprivate var _senderDevice: UInt32? = nil -} - -struct SMKProtos_UnidentifiedSenderMessage { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// @required - var ephemeralPublic: Data { - get {return _ephemeralPublic ?? SwiftProtobuf.Internal.emptyData} - set {_ephemeralPublic = newValue} - } - /// Returns true if `ephemeralPublic` has been explicitly set. - var hasEphemeralPublic: Bool {return self._ephemeralPublic != nil} - /// Clears the value of `ephemeralPublic`. Subsequent reads from it will return its default value. - mutating func clearEphemeralPublic() {self._ephemeralPublic = nil} - - /// @required - var encryptedStatic: Data { - get {return _encryptedStatic ?? SwiftProtobuf.Internal.emptyData} - set {_encryptedStatic = newValue} - } - /// Returns true if `encryptedStatic` has been explicitly set. - var hasEncryptedStatic: Bool {return self._encryptedStatic != nil} - /// Clears the value of `encryptedStatic`. Subsequent reads from it will return its default value. - mutating func clearEncryptedStatic() {self._encryptedStatic = nil} - - /// @required - var encryptedMessage: Data { - get {return _encryptedMessage ?? SwiftProtobuf.Internal.emptyData} - set {_encryptedMessage = newValue} - } - /// Returns true if `encryptedMessage` has been explicitly set. - var hasEncryptedMessage: Bool {return self._encryptedMessage != nil} - /// Clears the value of `encryptedMessage`. Subsequent reads from it will return its default value. - mutating func clearEncryptedMessage() {self._encryptedMessage = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - struct Message { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// @required - var type: SMKProtos_UnidentifiedSenderMessage.Message.TypeEnum { - get {return _type ?? .prekeyMessage} - set {_type = newValue} - } - /// Returns true if `type` has been explicitly set. - var hasType: Bool {return self._type != nil} - /// Clears the value of `type`. Subsequent reads from it will return its default value. - mutating func clearType() {self._type = nil} - - /// @required - var senderCertificate: SMKProtos_SenderCertificate { - get {return _senderCertificate ?? SMKProtos_SenderCertificate()} - set {_senderCertificate = newValue} - } - /// Returns true if `senderCertificate` has been explicitly set. - var hasSenderCertificate: Bool {return self._senderCertificate != nil} - /// Clears the value of `senderCertificate`. Subsequent reads from it will return its default value. - mutating func clearSenderCertificate() {self._senderCertificate = nil} - - /// @required - var content: Data { - get {return _content ?? SwiftProtobuf.Internal.emptyData} - set {_content = newValue} - } - /// Returns true if `content` has been explicitly set. - var hasContent: Bool {return self._content != nil} - /// Clears the value of `content`. Subsequent reads from it will return its default value. - mutating func clearContent() {self._content = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - enum TypeEnum: SwiftProtobuf.Enum { - typealias RawValue = Int - case prekeyMessage // = 1 - case message // = 2 - case fallbackMessage // = 3 - - init() { - self = .prekeyMessage - } - - init?(rawValue: Int) { - switch rawValue { - case 1: self = .prekeyMessage - case 2: self = .message - case 3: self = .fallbackMessage - default: return nil - } - } - - var rawValue: Int { - switch self { - case .prekeyMessage: return 1 - case .message: return 2 - case .fallbackMessage: return 3 - } - } - - } - - init() {} - - fileprivate var _type: SMKProtos_UnidentifiedSenderMessage.Message.TypeEnum? = nil - fileprivate var _senderCertificate: SMKProtos_SenderCertificate? = nil - fileprivate var _content: Data? = nil - } - - init() {} - - fileprivate var _ephemeralPublic: Data? = nil - fileprivate var _encryptedStatic: Data? = nil - fileprivate var _encryptedMessage: Data? = nil -} - -#if swift(>=4.2) - -extension SMKProtos_UnidentifiedSenderMessage.Message.TypeEnum: CaseIterable { - // Support synthesized by the compiler. -} - -#endif // swift(>=4.2) - -// MARK: - Code below here is support for the SwiftProtobuf runtime. - -fileprivate let _protobuf_package = "SMKProtos" - -extension SMKProtos_ServerCertificate: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".ServerCertificate" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "certificate"), - 2: .same(proto: "signature"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularBytesField(value: &self._certificate) - case 2: try decoder.decodeSingularBytesField(value: &self._signature) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._certificate { - try visitor.visitSingularBytesField(value: v, fieldNumber: 1) - } - if let v = self._signature { - try visitor.visitSingularBytesField(value: v, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SMKProtos_ServerCertificate, rhs: SMKProtos_ServerCertificate) -> Bool { - if lhs._certificate != rhs._certificate {return false} - if lhs._signature != rhs._signature {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} - -extension SMKProtos_ServerCertificate.Certificate: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = SMKProtos_ServerCertificate.protoMessageName + ".Certificate" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "id"), - 2: .same(proto: "key"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularUInt32Field(value: &self._id) - case 2: try decoder.decodeSingularBytesField(value: &self._key) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._id { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) - } - if let v = self._key { - try visitor.visitSingularBytesField(value: v, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SMKProtos_ServerCertificate.Certificate, rhs: SMKProtos_ServerCertificate.Certificate) -> Bool { - if lhs._id != rhs._id {return false} - if lhs._key != rhs._key {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} - -extension SMKProtos_SenderCertificate: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".SenderCertificate" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "sender"), - 2: .same(proto: "senderDevice"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularStringField(value: &self._sender) - case 2: try decoder.decodeSingularUInt32Field(value: &self._senderDevice) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._sender { - try visitor.visitSingularStringField(value: v, fieldNumber: 1) - } - if let v = self._senderDevice { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SMKProtos_SenderCertificate, rhs: SMKProtos_SenderCertificate) -> Bool { - if lhs._sender != rhs._sender {return false} - if lhs._senderDevice != rhs._senderDevice {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} - -extension SMKProtos_SenderCertificate.Certificate: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = SMKProtos_SenderCertificate.protoMessageName + ".Certificate" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "sender"), - 2: .same(proto: "senderDevice"), - 3: .same(proto: "expires"), - 4: .same(proto: "identityKey"), - 5: .same(proto: "signer"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularStringField(value: &self._sender) - case 2: try decoder.decodeSingularUInt32Field(value: &self._senderDevice) - case 3: try decoder.decodeSingularFixed64Field(value: &self._expires) - case 4: try decoder.decodeSingularBytesField(value: &self._identityKey) - case 5: try decoder.decodeSingularMessageField(value: &self._signer) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._sender { - try visitor.visitSingularStringField(value: v, fieldNumber: 1) - } - if let v = self._senderDevice { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 2) - } - if let v = self._expires { - try visitor.visitSingularFixed64Field(value: v, fieldNumber: 3) - } - if let v = self._identityKey { - try visitor.visitSingularBytesField(value: v, fieldNumber: 4) - } - if let v = self._signer { - try visitor.visitSingularMessageField(value: v, fieldNumber: 5) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SMKProtos_SenderCertificate.Certificate, rhs: SMKProtos_SenderCertificate.Certificate) -> Bool { - if lhs._sender != rhs._sender {return false} - if lhs._senderDevice != rhs._senderDevice {return false} - if lhs._expires != rhs._expires {return false} - if lhs._identityKey != rhs._identityKey {return false} - if lhs._signer != rhs._signer {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} - -extension SMKProtos_UnidentifiedSenderMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".UnidentifiedSenderMessage" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "ephemeralPublic"), - 2: .same(proto: "encryptedStatic"), - 3: .same(proto: "encryptedMessage"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularBytesField(value: &self._ephemeralPublic) - case 2: try decoder.decodeSingularBytesField(value: &self._encryptedStatic) - case 3: try decoder.decodeSingularBytesField(value: &self._encryptedMessage) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._ephemeralPublic { - try visitor.visitSingularBytesField(value: v, fieldNumber: 1) - } - if let v = self._encryptedStatic { - try visitor.visitSingularBytesField(value: v, fieldNumber: 2) - } - if let v = self._encryptedMessage { - try visitor.visitSingularBytesField(value: v, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SMKProtos_UnidentifiedSenderMessage, rhs: SMKProtos_UnidentifiedSenderMessage) -> Bool { - if lhs._ephemeralPublic != rhs._ephemeralPublic {return false} - if lhs._encryptedStatic != rhs._encryptedStatic {return false} - if lhs._encryptedMessage != rhs._encryptedMessage {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} - -extension SMKProtos_UnidentifiedSenderMessage.Message: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = SMKProtos_UnidentifiedSenderMessage.protoMessageName + ".Message" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "type"), - 2: .same(proto: "senderCertificate"), - 3: .same(proto: "content"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularEnumField(value: &self._type) - case 2: try decoder.decodeSingularMessageField(value: &self._senderCertificate) - case 3: try decoder.decodeSingularBytesField(value: &self._content) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._type { - try visitor.visitSingularEnumField(value: v, fieldNumber: 1) - } - if let v = self._senderCertificate { - try visitor.visitSingularMessageField(value: v, fieldNumber: 2) - } - if let v = self._content { - try visitor.visitSingularBytesField(value: v, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SMKProtos_UnidentifiedSenderMessage.Message, rhs: SMKProtos_UnidentifiedSenderMessage.Message) -> Bool { - if lhs._type != rhs._type {return false} - if lhs._senderCertificate != rhs._senderCertificate {return false} - if lhs._content != rhs._content {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} - -extension SMKProtos_UnidentifiedSenderMessage.Message.TypeEnum: SwiftProtobuf._ProtoNameProviding { - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "PREKEY_MESSAGE"), - 2: .same(proto: "MESSAGE"), - 3: .same(proto: "FALLBACK_MESSAGE"), - ] -} diff --git a/SessionProtocolKit/Signal/Protos/SMKProto.swift b/SessionProtocolKit/Signal/Protos/SMKProto.swift deleted file mode 100644 index 182e86693..000000000 --- a/SessionProtocolKit/Signal/Protos/SMKProto.swift +++ /dev/null @@ -1,782 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -// WARNING: This code is generated. Only edit within the markers. - -public enum SMKProtoError: Error { - case invalidProtobuf(description: String) -} - -// MARK: - SMKProtoServerCertificateCertificate - -@objc public class SMKProtoServerCertificateCertificate: NSObject { - - // MARK: - SMKProtoServerCertificateCertificateBuilder - - @objc public class func builder(id: UInt32, key: Data) -> SMKProtoServerCertificateCertificateBuilder { - return SMKProtoServerCertificateCertificateBuilder(id: id, key: key) - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SMKProtoServerCertificateCertificateBuilder { - let builder = SMKProtoServerCertificateCertificateBuilder(id: id, key: key) - return builder - } - - @objc public class SMKProtoServerCertificateCertificateBuilder: NSObject { - - private var proto = SMKProtos_ServerCertificate.Certificate() - - @objc fileprivate override init() {} - - @objc fileprivate init(id: UInt32, key: Data) { - super.init() - - setId(id) - setKey(key) - } - - @objc public func setId(_ valueParam: UInt32) { - proto.id = valueParam - } - - @objc public func setKey(_ valueParam: Data) { - proto.key = valueParam - } - - @objc public func build() throws -> SMKProtoServerCertificateCertificate { - return try SMKProtoServerCertificateCertificate.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SMKProtoServerCertificateCertificate.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SMKProtos_ServerCertificate.Certificate - - @objc public let id: UInt32 - - @objc public let key: Data - - private init(proto: SMKProtos_ServerCertificate.Certificate, - id: UInt32, - key: Data) { - self.proto = proto - self.id = id - self.key = key - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SMKProtoServerCertificateCertificate { - let proto = try SMKProtos_ServerCertificate.Certificate(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SMKProtos_ServerCertificate.Certificate) throws -> SMKProtoServerCertificateCertificate { - guard proto.hasID else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: id") - } - let id = proto.id - - guard proto.hasKey else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: key") - } - let key = proto.key - - // MARK: - Begin Validation Logic for SMKProtoServerCertificateCertificate - - - // MARK: - End Validation Logic for SMKProtoServerCertificateCertificate - - - let result = SMKProtoServerCertificateCertificate(proto: proto, - id: id, - key: key) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SMKProtoServerCertificateCertificate { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SMKProtoServerCertificateCertificate.SMKProtoServerCertificateCertificateBuilder { - @objc public func buildIgnoringErrors() -> SMKProtoServerCertificateCertificate? { - return try! self.build() - } -} - -#endif - -// MARK: - SMKProtoServerCertificate - -@objc public class SMKProtoServerCertificate: NSObject { - - // MARK: - SMKProtoServerCertificateBuilder - - @objc public class func builder(certificate: Data, signature: Data) -> SMKProtoServerCertificateBuilder { - return SMKProtoServerCertificateBuilder(certificate: certificate, signature: signature) - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SMKProtoServerCertificateBuilder { - let builder = SMKProtoServerCertificateBuilder(certificate: certificate, signature: signature) - return builder - } - - @objc public class SMKProtoServerCertificateBuilder: NSObject { - - private var proto = SMKProtos_ServerCertificate() - - @objc fileprivate override init() {} - - @objc fileprivate init(certificate: Data, signature: Data) { - super.init() - - setCertificate(certificate) - setSignature(signature) - } - - @objc public func setCertificate(_ valueParam: Data) { - proto.certificate = valueParam - } - - @objc public func setSignature(_ valueParam: Data) { - proto.signature = valueParam - } - - @objc public func build() throws -> SMKProtoServerCertificate { - return try SMKProtoServerCertificate.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SMKProtoServerCertificate.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SMKProtos_ServerCertificate - - @objc public let certificate: Data - - @objc public let signature: Data - - private init(proto: SMKProtos_ServerCertificate, - certificate: Data, - signature: Data) { - self.proto = proto - self.certificate = certificate - self.signature = signature - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SMKProtoServerCertificate { - let proto = try SMKProtos_ServerCertificate(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SMKProtos_ServerCertificate) throws -> SMKProtoServerCertificate { - guard proto.hasCertificate else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: certificate") - } - let certificate = proto.certificate - - guard proto.hasSignature else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: signature") - } - let signature = proto.signature - - // MARK: - Begin Validation Logic for SMKProtoServerCertificate - - - // MARK: - End Validation Logic for SMKProtoServerCertificate - - - let result = SMKProtoServerCertificate(proto: proto, - certificate: certificate, - signature: signature) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SMKProtoServerCertificate { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SMKProtoServerCertificate.SMKProtoServerCertificateBuilder { - @objc public func buildIgnoringErrors() -> SMKProtoServerCertificate? { - return try! self.build() - } -} - -#endif - -// MARK: - SMKProtoSenderCertificateCertificate - -@objc public class SMKProtoSenderCertificateCertificate: NSObject { - - // MARK: - SMKProtoSenderCertificateCertificateBuilder - - @objc public class func builder(sender: String, senderDevice: UInt32, expires: UInt64, identityKey: Data, signer: SMKProtoServerCertificate) -> SMKProtoSenderCertificateCertificateBuilder { - return SMKProtoSenderCertificateCertificateBuilder(sender: sender, senderDevice: senderDevice, expires: expires, identityKey: identityKey, signer: signer) - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SMKProtoSenderCertificateCertificateBuilder { - let builder = SMKProtoSenderCertificateCertificateBuilder(sender: sender, senderDevice: senderDevice, expires: expires, identityKey: identityKey, signer: signer) - return builder - } - - @objc public class SMKProtoSenderCertificateCertificateBuilder: NSObject { - - private var proto = SMKProtos_SenderCertificate.Certificate() - - @objc fileprivate override init() {} - - @objc fileprivate init(sender: String, senderDevice: UInt32, expires: UInt64, identityKey: Data, signer: SMKProtoServerCertificate) { - super.init() - - setSender(sender) - setSenderDevice(senderDevice) - setExpires(expires) - setIdentityKey(identityKey) - setSigner(signer) - } - - @objc public func setSender(_ valueParam: String) { - proto.sender = valueParam - } - - @objc public func setSenderDevice(_ valueParam: UInt32) { - proto.senderDevice = valueParam - } - - @objc public func setExpires(_ valueParam: UInt64) { - proto.expires = valueParam - } - - @objc public func setIdentityKey(_ valueParam: Data) { - proto.identityKey = valueParam - } - - @objc public func setSigner(_ valueParam: SMKProtoServerCertificate) { - proto.signer = valueParam.proto - } - - @objc public func build() throws -> SMKProtoSenderCertificateCertificate { - return try SMKProtoSenderCertificateCertificate.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SMKProtoSenderCertificateCertificate.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SMKProtos_SenderCertificate.Certificate - - @objc public let sender: String - - @objc public let senderDevice: UInt32 - - @objc public let expires: UInt64 - - @objc public let identityKey: Data - - @objc public let signer: SMKProtoServerCertificate - - private init(proto: SMKProtos_SenderCertificate.Certificate, - sender: String, - senderDevice: UInt32, - expires: UInt64, - identityKey: Data, - signer: SMKProtoServerCertificate) { - self.proto = proto - self.sender = sender - self.senderDevice = senderDevice - self.expires = expires - self.identityKey = identityKey - self.signer = signer - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SMKProtoSenderCertificateCertificate { - let proto = try SMKProtos_SenderCertificate.Certificate(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SMKProtos_SenderCertificate.Certificate) throws -> SMKProtoSenderCertificateCertificate { - guard proto.hasSender else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: sender") - } - let sender = proto.sender - - guard proto.hasSenderDevice else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: senderDevice") - } - let senderDevice = proto.senderDevice - - guard proto.hasExpires else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: expires") - } - let expires = proto.expires - - guard proto.hasIdentityKey else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: identityKey") - } - let identityKey = proto.identityKey - - guard proto.hasSigner else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: signer") - } - let signer = try SMKProtoServerCertificate.parseProto(proto.signer) - - // MARK: - Begin Validation Logic for SMKProtoSenderCertificateCertificate - - - // MARK: - End Validation Logic for SMKProtoSenderCertificateCertificate - - - let result = SMKProtoSenderCertificateCertificate(proto: proto, - sender: sender, - senderDevice: senderDevice, - expires: expires, - identityKey: identityKey, - signer: signer) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SMKProtoSenderCertificateCertificate { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SMKProtoSenderCertificateCertificate.SMKProtoSenderCertificateCertificateBuilder { - @objc public func buildIgnoringErrors() -> SMKProtoSenderCertificateCertificate? { - return try! self.build() - } -} - -#endif - -// MARK: - SMKProtoSenderCertificate - -@objc public class SMKProtoSenderCertificate: NSObject { - - // MARK: - SMKProtoSenderCertificateBuilder - - @objc public class func builder(sender: String, senderDevice: UInt32) -> SMKProtoSenderCertificateBuilder { - return SMKProtoSenderCertificateBuilder(sender: sender, senderDevice: senderDevice) - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SMKProtoSenderCertificateBuilder { - let builder = SMKProtoSenderCertificateBuilder(sender: sender, senderDevice: senderDevice) - return builder - } - - @objc public class SMKProtoSenderCertificateBuilder: NSObject { - - private var proto = SMKProtos_SenderCertificate() - - @objc fileprivate override init() {} - - @objc fileprivate init(sender: String, senderDevice: UInt32) { - super.init() - - setSender(sender) - setSenderDevice(senderDevice) - } - - @objc public func setSender(_ valueParam: String) { - proto.sender = valueParam - } - - @objc public func setSenderDevice(_ valueParam: UInt32) { - proto.senderDevice = valueParam - } - - @objc public func build() throws -> SMKProtoSenderCertificate { - return try SMKProtoSenderCertificate.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SMKProtoSenderCertificate.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SMKProtos_SenderCertificate - - @objc public let sender: String - - @objc public let senderDevice: UInt32 - - private init(proto: SMKProtos_SenderCertificate, - sender: String, - senderDevice: UInt32) { - self.proto = proto - self.sender = sender - self.senderDevice = senderDevice - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SMKProtoSenderCertificate { - let proto = try SMKProtos_SenderCertificate(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SMKProtos_SenderCertificate) throws -> SMKProtoSenderCertificate { - guard proto.hasSender else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: sender") - } - let sender = proto.sender - - guard proto.hasSenderDevice else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: senderDevice") - } - let senderDevice = proto.senderDevice - - // MARK: - Begin Validation Logic for SMKProtoSenderCertificate - - - // MARK: - End Validation Logic for SMKProtoSenderCertificate - - - let result = SMKProtoSenderCertificate(proto: proto, - sender: sender, - senderDevice: senderDevice) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SMKProtoSenderCertificate { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SMKProtoSenderCertificate.SMKProtoSenderCertificateBuilder { - @objc public func buildIgnoringErrors() -> SMKProtoSenderCertificate? { - return try! self.build() - } -} - -#endif - -// MARK: - SMKProtoUnidentifiedSenderMessageMessage - -@objc public class SMKProtoUnidentifiedSenderMessageMessage: NSObject { - - // MARK: - SMKProtoUnidentifiedSenderMessageMessageType - - @objc public enum SMKProtoUnidentifiedSenderMessageMessageType: Int32 { - case prekeyMessage = 1 - case message = 2 - case fallbackMessage = 3 - } - - private class func SMKProtoUnidentifiedSenderMessageMessageTypeWrap(_ value: SMKProtos_UnidentifiedSenderMessage.Message.TypeEnum) -> SMKProtoUnidentifiedSenderMessageMessageType { - switch value { - case .prekeyMessage: return .prekeyMessage - case .message: return .message - case .fallbackMessage: return .fallbackMessage - } - } - - private class func SMKProtoUnidentifiedSenderMessageMessageTypeUnwrap(_ value: SMKProtoUnidentifiedSenderMessageMessageType) -> SMKProtos_UnidentifiedSenderMessage.Message.TypeEnum { - switch value { - case .prekeyMessage: return .prekeyMessage - case .message: return .message - case .fallbackMessage: return .fallbackMessage - } - } - - // MARK: - SMKProtoUnidentifiedSenderMessageMessageBuilder - - @objc public class func builder(type: SMKProtoUnidentifiedSenderMessageMessageType, senderCertificate: SMKProtoSenderCertificate, content: Data) -> SMKProtoUnidentifiedSenderMessageMessageBuilder { - return SMKProtoUnidentifiedSenderMessageMessageBuilder(type: type, senderCertificate: senderCertificate, content: content) - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SMKProtoUnidentifiedSenderMessageMessageBuilder { - let builder = SMKProtoUnidentifiedSenderMessageMessageBuilder(type: type, senderCertificate: senderCertificate, content: content) - return builder - } - - @objc public class SMKProtoUnidentifiedSenderMessageMessageBuilder: NSObject { - - private var proto = SMKProtos_UnidentifiedSenderMessage.Message() - - @objc fileprivate override init() {} - - @objc fileprivate init(type: SMKProtoUnidentifiedSenderMessageMessageType, senderCertificate: SMKProtoSenderCertificate, content: Data) { - super.init() - - setType(type) - setSenderCertificate(senderCertificate) - setContent(content) - } - - @objc public func setType(_ valueParam: SMKProtoUnidentifiedSenderMessageMessageType) { - proto.type = SMKProtoUnidentifiedSenderMessageMessageTypeUnwrap(valueParam) - } - - @objc public func setSenderCertificate(_ valueParam: SMKProtoSenderCertificate) { - proto.senderCertificate = valueParam.proto - } - - @objc public func setContent(_ valueParam: Data) { - proto.content = valueParam - } - - @objc public func build() throws -> SMKProtoUnidentifiedSenderMessageMessage { - return try SMKProtoUnidentifiedSenderMessageMessage.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SMKProtoUnidentifiedSenderMessageMessage.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SMKProtos_UnidentifiedSenderMessage.Message - - @objc public let type: SMKProtoUnidentifiedSenderMessageMessageType - - @objc public let senderCertificate: SMKProtoSenderCertificate - - @objc public let content: Data - - private init(proto: SMKProtos_UnidentifiedSenderMessage.Message, - type: SMKProtoUnidentifiedSenderMessageMessageType, - senderCertificate: SMKProtoSenderCertificate, - content: Data) { - self.proto = proto - self.type = type - self.senderCertificate = senderCertificate - self.content = content - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SMKProtoUnidentifiedSenderMessageMessage { - let proto = try SMKProtos_UnidentifiedSenderMessage.Message(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SMKProtos_UnidentifiedSenderMessage.Message) throws -> SMKProtoUnidentifiedSenderMessageMessage { - guard proto.hasType else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: type") - } - let type = SMKProtoUnidentifiedSenderMessageMessageTypeWrap(proto.type) - - guard proto.hasSenderCertificate else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: senderCertificate") - } - let senderCertificate = try SMKProtoSenderCertificate.parseProto(proto.senderCertificate) - - guard proto.hasContent else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: content") - } - let content = proto.content - - // MARK: - Begin Validation Logic for SMKProtoUnidentifiedSenderMessageMessage - - - // MARK: - End Validation Logic for SMKProtoUnidentifiedSenderMessageMessage - - - let result = SMKProtoUnidentifiedSenderMessageMessage(proto: proto, - type: type, - senderCertificate: senderCertificate, - content: content) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SMKProtoUnidentifiedSenderMessageMessage { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SMKProtoUnidentifiedSenderMessageMessage.SMKProtoUnidentifiedSenderMessageMessageBuilder { - @objc public func buildIgnoringErrors() -> SMKProtoUnidentifiedSenderMessageMessage? { - return try! self.build() - } -} - -#endif - -// MARK: - SMKProtoUnidentifiedSenderMessage - -@objc public class SMKProtoUnidentifiedSenderMessage: NSObject { - - // MARK: - SMKProtoUnidentifiedSenderMessageBuilder - - @objc public class func builder(ephemeralPublic: Data, encryptedStatic: Data, encryptedMessage: Data) -> SMKProtoUnidentifiedSenderMessageBuilder { - return SMKProtoUnidentifiedSenderMessageBuilder(ephemeralPublic: ephemeralPublic, encryptedStatic: encryptedStatic, encryptedMessage: encryptedMessage) - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SMKProtoUnidentifiedSenderMessageBuilder { - let builder = SMKProtoUnidentifiedSenderMessageBuilder(ephemeralPublic: ephemeralPublic, encryptedStatic: encryptedStatic, encryptedMessage: encryptedMessage) - return builder - } - - @objc public class SMKProtoUnidentifiedSenderMessageBuilder: NSObject { - - private var proto = SMKProtos_UnidentifiedSenderMessage() - - @objc fileprivate override init() {} - - @objc fileprivate init(ephemeralPublic: Data, encryptedStatic: Data, encryptedMessage: Data) { - super.init() - - setEphemeralPublic(ephemeralPublic) - setEncryptedStatic(encryptedStatic) - setEncryptedMessage(encryptedMessage) - } - - @objc public func setEphemeralPublic(_ valueParam: Data) { - proto.ephemeralPublic = valueParam - } - - @objc public func setEncryptedStatic(_ valueParam: Data) { - proto.encryptedStatic = valueParam - } - - @objc public func setEncryptedMessage(_ valueParam: Data) { - proto.encryptedMessage = valueParam - } - - @objc public func build() throws -> SMKProtoUnidentifiedSenderMessage { - return try SMKProtoUnidentifiedSenderMessage.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SMKProtoUnidentifiedSenderMessage.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SMKProtos_UnidentifiedSenderMessage - - @objc public let ephemeralPublic: Data - - @objc public let encryptedStatic: Data - - @objc public let encryptedMessage: Data - - private init(proto: SMKProtos_UnidentifiedSenderMessage, - ephemeralPublic: Data, - encryptedStatic: Data, - encryptedMessage: Data) { - self.proto = proto - self.ephemeralPublic = ephemeralPublic - self.encryptedStatic = encryptedStatic - self.encryptedMessage = encryptedMessage - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SMKProtoUnidentifiedSenderMessage { - let proto = try SMKProtos_UnidentifiedSenderMessage(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SMKProtos_UnidentifiedSenderMessage) throws -> SMKProtoUnidentifiedSenderMessage { - guard proto.hasEphemeralPublic else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: ephemeralPublic") - } - let ephemeralPublic = proto.ephemeralPublic - - guard proto.hasEncryptedStatic else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: encryptedStatic") - } - let encryptedStatic = proto.encryptedStatic - - guard proto.hasEncryptedMessage else { - throw SMKProtoError.invalidProtobuf(description: "\(logTag) missing required field: encryptedMessage") - } - let encryptedMessage = proto.encryptedMessage - - // MARK: - Begin Validation Logic for SMKProtoUnidentifiedSenderMessage - - - // MARK: - End Validation Logic for SMKProtoUnidentifiedSenderMessage - - - let result = SMKProtoUnidentifiedSenderMessage(proto: proto, - ephemeralPublic: ephemeralPublic, - encryptedStatic: encryptedStatic, - encryptedMessage: encryptedMessage) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SMKProtoUnidentifiedSenderMessage { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SMKProtoUnidentifiedSenderMessage.SMKProtoUnidentifiedSenderMessageBuilder { - @objc public func buildIgnoringErrors() -> SMKProtoUnidentifiedSenderMessage? { - return try! self.build() - } -} - -#endif diff --git a/SessionProtocolKit/Signal/Protos/SPKProto.swift b/SessionProtocolKit/Signal/Protos/SPKProto.swift deleted file mode 100644 index 18fa38351..000000000 --- a/SessionProtocolKit/Signal/Protos/SPKProto.swift +++ /dev/null @@ -1,873 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -// WARNING: This code is generated. Only edit within the markers. - -public enum SPKProtoError: Error { - case invalidProtobuf(description: String) -} - -// MARK: - SPKProtoTSProtoWhisperMessage - -@objc public class SPKProtoTSProtoWhisperMessage: NSObject { - - class var logTag: String { "SPKProtoTSProtoWhisperMessage" } - - // MARK: - SPKProtoTSProtoWhisperMessageBuilder - - @objc public class func builder(ratchetKey: Data, counter: UInt32, ciphertext: Data) -> SPKProtoTSProtoWhisperMessageBuilder { - return SPKProtoTSProtoWhisperMessageBuilder(ratchetKey: ratchetKey, counter: counter, ciphertext: ciphertext) - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SPKProtoTSProtoWhisperMessageBuilder { - let builder = SPKProtoTSProtoWhisperMessageBuilder(ratchetKey: ratchetKey, counter: counter, ciphertext: ciphertext) - if hasPreviousCounter { - builder.setPreviousCounter(previousCounter) - } - return builder - } - - @objc public class SPKProtoTSProtoWhisperMessageBuilder: NSObject { - - private var proto = SPKProtos_TSProtoWhisperMessage() - - @objc fileprivate override init() {} - - @objc fileprivate init(ratchetKey: Data, counter: UInt32, ciphertext: Data) { - super.init() - - setRatchetKey(ratchetKey) - setCounter(counter) - setCiphertext(ciphertext) - } - - @objc public func setRatchetKey(_ valueParam: Data) { - proto.ratchetKey = valueParam - } - - @objc public func setCounter(_ valueParam: UInt32) { - proto.counter = valueParam - } - - @objc public func setPreviousCounter(_ valueParam: UInt32) { - proto.previousCounter = valueParam - } - - @objc public func setCiphertext(_ valueParam: Data) { - proto.ciphertext = valueParam - } - - @objc public func build() throws -> SPKProtoTSProtoWhisperMessage { - return try SPKProtoTSProtoWhisperMessage.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SPKProtoTSProtoWhisperMessage.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SPKProtos_TSProtoWhisperMessage - - @objc public let ratchetKey: Data - - @objc public let counter: UInt32 - - @objc public let ciphertext: Data - - @objc public var previousCounter: UInt32 { - return proto.previousCounter - } - @objc public var hasPreviousCounter: Bool { - return proto.hasPreviousCounter - } - - private init(proto: SPKProtos_TSProtoWhisperMessage, - ratchetKey: Data, - counter: UInt32, - ciphertext: Data) { - self.proto = proto - self.ratchetKey = ratchetKey - self.counter = counter - self.ciphertext = ciphertext - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SPKProtoTSProtoWhisperMessage { - let proto = try SPKProtos_TSProtoWhisperMessage(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SPKProtos_TSProtoWhisperMessage) throws -> SPKProtoTSProtoWhisperMessage { - guard proto.hasRatchetKey else { - throw SPKProtoError.invalidProtobuf(description: "\(logTag) missing required field: ratchetKey") - } - let ratchetKey = proto.ratchetKey - - guard proto.hasCounter else { - throw SPKProtoError.invalidProtobuf(description: "\(logTag) missing required field: counter") - } - let counter = proto.counter - - guard proto.hasCiphertext else { - throw SPKProtoError.invalidProtobuf(description: "\(logTag) missing required field: ciphertext") - } - let ciphertext = proto.ciphertext - - // MARK: - Begin Validation Logic for SPKProtoTSProtoWhisperMessage - - - // MARK: - End Validation Logic for SPKProtoTSProtoWhisperMessage - - - let result = SPKProtoTSProtoWhisperMessage(proto: proto, - ratchetKey: ratchetKey, - counter: counter, - ciphertext: ciphertext) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SPKProtoTSProtoWhisperMessage { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SPKProtoTSProtoWhisperMessage.SPKProtoTSProtoWhisperMessageBuilder { - @objc public func buildIgnoringErrors() -> SPKProtoTSProtoWhisperMessage? { - return try! self.build() - } -} - -#endif - -// MARK: - SPKProtoTSProtoPreKeyWhisperMessage - -@objc public class SPKProtoTSProtoPreKeyWhisperMessage: NSObject { - - // MARK: - SPKProtoTSProtoPreKeyWhisperMessageBuilder - - @objc public class func builder(signedPreKeyID: UInt32, baseKey: Data, identityKey: Data, message: Data) -> SPKProtoTSProtoPreKeyWhisperMessageBuilder { - return SPKProtoTSProtoPreKeyWhisperMessageBuilder(signedPreKeyID: signedPreKeyID, baseKey: baseKey, identityKey: identityKey, message: message) - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SPKProtoTSProtoPreKeyWhisperMessageBuilder { - let builder = SPKProtoTSProtoPreKeyWhisperMessageBuilder(signedPreKeyID: signedPreKeyID, baseKey: baseKey, identityKey: identityKey, message: message) - if hasRegistrationID { - builder.setRegistrationID(registrationID) - } - if hasPreKeyID { - builder.setPreKeyID(preKeyID) - } - return builder - } - - @objc public class SPKProtoTSProtoPreKeyWhisperMessageBuilder: NSObject { - - private var proto = SPKProtos_TSProtoPreKeyWhisperMessage() - - @objc fileprivate override init() {} - - @objc fileprivate init(signedPreKeyID: UInt32, baseKey: Data, identityKey: Data, message: Data) { - super.init() - - setSignedPreKeyID(signedPreKeyID) - setBaseKey(baseKey) - setIdentityKey(identityKey) - setMessage(message) - } - - @objc public func setRegistrationID(_ valueParam: UInt32) { - proto.registrationID = valueParam - } - - @objc public func setPreKeyID(_ valueParam: UInt32) { - proto.preKeyID = valueParam - } - - @objc public func setSignedPreKeyID(_ valueParam: UInt32) { - proto.signedPreKeyID = valueParam - } - - @objc public func setBaseKey(_ valueParam: Data) { - proto.baseKey = valueParam - } - - @objc public func setIdentityKey(_ valueParam: Data) { - proto.identityKey = valueParam - } - - @objc public func setMessage(_ valueParam: Data) { - proto.message = valueParam - } - - @objc public func build() throws -> SPKProtoTSProtoPreKeyWhisperMessage { - return try SPKProtoTSProtoPreKeyWhisperMessage.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SPKProtoTSProtoPreKeyWhisperMessage.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SPKProtos_TSProtoPreKeyWhisperMessage - - @objc public let signedPreKeyID: UInt32 - - @objc public let baseKey: Data - - @objc public let identityKey: Data - - @objc public let message: Data - - @objc public var registrationID: UInt32 { - return proto.registrationID - } - @objc public var hasRegistrationID: Bool { - return proto.hasRegistrationID - } - - @objc public var preKeyID: UInt32 { - return proto.preKeyID - } - @objc public var hasPreKeyID: Bool { - return proto.hasPreKeyID - } - - private init(proto: SPKProtos_TSProtoPreKeyWhisperMessage, - signedPreKeyID: UInt32, - baseKey: Data, - identityKey: Data, - message: Data) { - self.proto = proto - self.signedPreKeyID = signedPreKeyID - self.baseKey = baseKey - self.identityKey = identityKey - self.message = message - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SPKProtoTSProtoPreKeyWhisperMessage { - let proto = try SPKProtos_TSProtoPreKeyWhisperMessage(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SPKProtos_TSProtoPreKeyWhisperMessage) throws -> SPKProtoTSProtoPreKeyWhisperMessage { - guard proto.hasSignedPreKeyID else { - throw SPKProtoError.invalidProtobuf(description: "\(logTag) missing required field: signedPreKeyID") - } - let signedPreKeyID = proto.signedPreKeyID - - guard proto.hasBaseKey else { - throw SPKProtoError.invalidProtobuf(description: "\(logTag) missing required field: baseKey") - } - let baseKey = proto.baseKey - - guard proto.hasIdentityKey else { - throw SPKProtoError.invalidProtobuf(description: "\(logTag) missing required field: identityKey") - } - let identityKey = proto.identityKey - - guard proto.hasMessage else { - throw SPKProtoError.invalidProtobuf(description: "\(logTag) missing required field: message") - } - let message = proto.message - - // MARK: - Begin Validation Logic for SPKProtoTSProtoPreKeyWhisperMessage - - - // MARK: - End Validation Logic for SPKProtoTSProtoPreKeyWhisperMessage - - - let result = SPKProtoTSProtoPreKeyWhisperMessage(proto: proto, - signedPreKeyID: signedPreKeyID, - baseKey: baseKey, - identityKey: identityKey, - message: message) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SPKProtoTSProtoPreKeyWhisperMessage { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SPKProtoTSProtoPreKeyWhisperMessage.SPKProtoTSProtoPreKeyWhisperMessageBuilder { - @objc public func buildIgnoringErrors() -> SPKProtoTSProtoPreKeyWhisperMessage? { - return try! self.build() - } -} - -#endif - -// MARK: - SPKProtoTSProtoKeyExchangeMessage - -@objc public class SPKProtoTSProtoKeyExchangeMessage: NSObject { - - // MARK: - SPKProtoTSProtoKeyExchangeMessageBuilder - - @objc public class func builder() -> SPKProtoTSProtoKeyExchangeMessageBuilder { - return SPKProtoTSProtoKeyExchangeMessageBuilder() - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SPKProtoTSProtoKeyExchangeMessageBuilder { - let builder = SPKProtoTSProtoKeyExchangeMessageBuilder() - if hasID { - builder.setId(id) - } - if let _value = baseKey { - builder.setBaseKey(_value) - } - if let _value = ratchetKey { - builder.setRatchetKey(_value) - } - if let _value = identityKey { - builder.setIdentityKey(_value) - } - if let _value = baseKeySignature { - builder.setBaseKeySignature(_value) - } - return builder - } - - @objc public class SPKProtoTSProtoKeyExchangeMessageBuilder: NSObject { - - private var proto = SPKProtos_TSProtoKeyExchangeMessage() - - @objc fileprivate override init() {} - - @objc public func setId(_ valueParam: UInt32) { - proto.id = valueParam - } - - @objc public func setBaseKey(_ valueParam: Data) { - proto.baseKey = valueParam - } - - @objc public func setRatchetKey(_ valueParam: Data) { - proto.ratchetKey = valueParam - } - - @objc public func setIdentityKey(_ valueParam: Data) { - proto.identityKey = valueParam - } - - @objc public func setBaseKeySignature(_ valueParam: Data) { - proto.baseKeySignature = valueParam - } - - @objc public func build() throws -> SPKProtoTSProtoKeyExchangeMessage { - return try SPKProtoTSProtoKeyExchangeMessage.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SPKProtoTSProtoKeyExchangeMessage.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SPKProtos_TSProtoKeyExchangeMessage - - @objc public var id: UInt32 { - return proto.id - } - @objc public var hasID: Bool { - return proto.hasID - } - - @objc public var baseKey: Data? { - guard proto.hasBaseKey else { - return nil - } - return proto.baseKey - } - @objc public var hasBaseKey: Bool { - return proto.hasBaseKey - } - - @objc public var ratchetKey: Data? { - guard proto.hasRatchetKey else { - return nil - } - return proto.ratchetKey - } - @objc public var hasRatchetKey: Bool { - return proto.hasRatchetKey - } - - @objc public var identityKey: Data? { - guard proto.hasIdentityKey else { - return nil - } - return proto.identityKey - } - @objc public var hasIdentityKey: Bool { - return proto.hasIdentityKey - } - - @objc public var baseKeySignature: Data? { - guard proto.hasBaseKeySignature else { - return nil - } - return proto.baseKeySignature - } - @objc public var hasBaseKeySignature: Bool { - return proto.hasBaseKeySignature - } - - private init(proto: SPKProtos_TSProtoKeyExchangeMessage) { - self.proto = proto - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SPKProtoTSProtoKeyExchangeMessage { - let proto = try SPKProtos_TSProtoKeyExchangeMessage(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SPKProtos_TSProtoKeyExchangeMessage) throws -> SPKProtoTSProtoKeyExchangeMessage { - // MARK: - Begin Validation Logic for SPKProtoTSProtoKeyExchangeMessage - - - // MARK: - End Validation Logic for SPKProtoTSProtoKeyExchangeMessage - - - let result = SPKProtoTSProtoKeyExchangeMessage(proto: proto) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SPKProtoTSProtoKeyExchangeMessage { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SPKProtoTSProtoKeyExchangeMessage.SPKProtoTSProtoKeyExchangeMessageBuilder { - @objc public func buildIgnoringErrors() -> SPKProtoTSProtoKeyExchangeMessage? { - return try! self.build() - } -} - -#endif - -// MARK: - SPKProtoTSProtoSenderKeyMessage - -@objc public class SPKProtoTSProtoSenderKeyMessage: NSObject { - - // MARK: - SPKProtoTSProtoSenderKeyMessageBuilder - - @objc public class func builder() -> SPKProtoTSProtoSenderKeyMessageBuilder { - return SPKProtoTSProtoSenderKeyMessageBuilder() - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SPKProtoTSProtoSenderKeyMessageBuilder { - let builder = SPKProtoTSProtoSenderKeyMessageBuilder() - if hasID { - builder.setId(id) - } - if hasIteration { - builder.setIteration(iteration) - } - if let _value = ciphertext { - builder.setCiphertext(_value) - } - return builder - } - - @objc public class SPKProtoTSProtoSenderKeyMessageBuilder: NSObject { - - private var proto = SPKProtos_TSProtoSenderKeyMessage() - - @objc fileprivate override init() {} - - @objc public func setId(_ valueParam: UInt32) { - proto.id = valueParam - } - - @objc public func setIteration(_ valueParam: UInt32) { - proto.iteration = valueParam - } - - @objc public func setCiphertext(_ valueParam: Data) { - proto.ciphertext = valueParam - } - - @objc public func build() throws -> SPKProtoTSProtoSenderKeyMessage { - return try SPKProtoTSProtoSenderKeyMessage.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SPKProtoTSProtoSenderKeyMessage.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SPKProtos_TSProtoSenderKeyMessage - - @objc public var id: UInt32 { - return proto.id - } - @objc public var hasID: Bool { - return proto.hasID - } - - @objc public var iteration: UInt32 { - return proto.iteration - } - @objc public var hasIteration: Bool { - return proto.hasIteration - } - - @objc public var ciphertext: Data? { - guard proto.hasCiphertext else { - return nil - } - return proto.ciphertext - } - @objc public var hasCiphertext: Bool { - return proto.hasCiphertext - } - - private init(proto: SPKProtos_TSProtoSenderKeyMessage) { - self.proto = proto - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SPKProtoTSProtoSenderKeyMessage { - let proto = try SPKProtos_TSProtoSenderKeyMessage(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SPKProtos_TSProtoSenderKeyMessage) throws -> SPKProtoTSProtoSenderKeyMessage { - // MARK: - Begin Validation Logic for SPKProtoTSProtoSenderKeyMessage - - - // MARK: - End Validation Logic for SPKProtoTSProtoSenderKeyMessage - - - let result = SPKProtoTSProtoSenderKeyMessage(proto: proto) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SPKProtoTSProtoSenderKeyMessage { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SPKProtoTSProtoSenderKeyMessage.SPKProtoTSProtoSenderKeyMessageBuilder { - @objc public func buildIgnoringErrors() -> SPKProtoTSProtoSenderKeyMessage? { - return try! self.build() - } -} - -#endif - -// MARK: - SPKProtoTSProtoSenderKeyDistributionMessage - -@objc public class SPKProtoTSProtoSenderKeyDistributionMessage: NSObject { - - // MARK: - SPKProtoTSProtoSenderKeyDistributionMessageBuilder - - @objc public class func builder() -> SPKProtoTSProtoSenderKeyDistributionMessageBuilder { - return SPKProtoTSProtoSenderKeyDistributionMessageBuilder() - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SPKProtoTSProtoSenderKeyDistributionMessageBuilder { - let builder = SPKProtoTSProtoSenderKeyDistributionMessageBuilder() - if hasID { - builder.setId(id) - } - if hasIteration { - builder.setIteration(iteration) - } - if let _value = chainKey { - builder.setChainKey(_value) - } - if let _value = signingKey { - builder.setSigningKey(_value) - } - return builder - } - - @objc public class SPKProtoTSProtoSenderKeyDistributionMessageBuilder: NSObject { - - private var proto = SPKProtos_TSProtoSenderKeyDistributionMessage() - - @objc fileprivate override init() {} - - @objc public func setId(_ valueParam: UInt32) { - proto.id = valueParam - } - - @objc public func setIteration(_ valueParam: UInt32) { - proto.iteration = valueParam - } - - @objc public func setChainKey(_ valueParam: Data) { - proto.chainKey = valueParam - } - - @objc public func setSigningKey(_ valueParam: Data) { - proto.signingKey = valueParam - } - - @objc public func build() throws -> SPKProtoTSProtoSenderKeyDistributionMessage { - return try SPKProtoTSProtoSenderKeyDistributionMessage.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SPKProtoTSProtoSenderKeyDistributionMessage.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SPKProtos_TSProtoSenderKeyDistributionMessage - - @objc public var id: UInt32 { - return proto.id - } - @objc public var hasID: Bool { - return proto.hasID - } - - @objc public var iteration: UInt32 { - return proto.iteration - } - @objc public var hasIteration: Bool { - return proto.hasIteration - } - - @objc public var chainKey: Data? { - guard proto.hasChainKey else { - return nil - } - return proto.chainKey - } - @objc public var hasChainKey: Bool { - return proto.hasChainKey - } - - @objc public var signingKey: Data? { - guard proto.hasSigningKey else { - return nil - } - return proto.signingKey - } - @objc public var hasSigningKey: Bool { - return proto.hasSigningKey - } - - private init(proto: SPKProtos_TSProtoSenderKeyDistributionMessage) { - self.proto = proto - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SPKProtoTSProtoSenderKeyDistributionMessage { - let proto = try SPKProtos_TSProtoSenderKeyDistributionMessage(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SPKProtos_TSProtoSenderKeyDistributionMessage) throws -> SPKProtoTSProtoSenderKeyDistributionMessage { - // MARK: - Begin Validation Logic for SPKProtoTSProtoSenderKeyDistributionMessage - - - // MARK: - End Validation Logic for SPKProtoTSProtoSenderKeyDistributionMessage - - - let result = SPKProtoTSProtoSenderKeyDistributionMessage(proto: proto) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SPKProtoTSProtoSenderKeyDistributionMessage { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SPKProtoTSProtoSenderKeyDistributionMessage.SPKProtoTSProtoSenderKeyDistributionMessageBuilder { - @objc public func buildIgnoringErrors() -> SPKProtoTSProtoSenderKeyDistributionMessage? { - return try! self.build() - } -} - -#endif - -// MARK: - SPKProtoClosedGroupCiphertextMessage - -@objc public class SPKProtoClosedGroupCiphertextMessage: NSObject { - - class var logTag: String { "SPKProtoClosedGroupCiphertextMessage" } - - // MARK: - SPKProtoClosedGroupCiphertextMessageBuilder - - @objc public class func builder(ciphertext: Data, senderPublicKey: Data, keyIndex: UInt32) -> SPKProtoClosedGroupCiphertextMessageBuilder { - return SPKProtoClosedGroupCiphertextMessageBuilder(ciphertext: ciphertext, senderPublicKey: senderPublicKey, keyIndex: keyIndex) - } - - // asBuilder() constructs a builder that reflects the proto's contents. - @objc public func asBuilder() -> SPKProtoClosedGroupCiphertextMessageBuilder { - let builder = SPKProtoClosedGroupCiphertextMessageBuilder(ciphertext: ciphertext, senderPublicKey: senderPublicKey, keyIndex: keyIndex) - return builder - } - - @objc public class SPKProtoClosedGroupCiphertextMessageBuilder: NSObject { - - private var proto = SPKProtos_ClosedGroupCiphertextMessage() - - @objc fileprivate override init() {} - - @objc fileprivate init(ciphertext: Data, senderPublicKey: Data, keyIndex: UInt32) { - super.init() - - setCiphertext(ciphertext) - setSenderPublicKey(senderPublicKey) - setKeyIndex(keyIndex) - } - - @objc public func setCiphertext(_ valueParam: Data) { - proto.ciphertext = valueParam - } - - @objc public func setSenderPublicKey(_ valueParam: Data) { - proto.senderPublicKey = valueParam - } - - @objc public func setKeyIndex(_ valueParam: UInt32) { - proto.keyIndex = valueParam - } - - @objc public func build() throws -> SPKProtoClosedGroupCiphertextMessage { - return try SPKProtoClosedGroupCiphertextMessage.parseProto(proto) - } - - @objc public func buildSerializedData() throws -> Data { - return try SPKProtoClosedGroupCiphertextMessage.parseProto(proto).serializedData() - } - } - - fileprivate let proto: SPKProtos_ClosedGroupCiphertextMessage - - @objc public let ciphertext: Data - - @objc public let senderPublicKey: Data - - @objc public let keyIndex: UInt32 - - private init(proto: SPKProtos_ClosedGroupCiphertextMessage, - ciphertext: Data, - senderPublicKey: Data, - keyIndex: UInt32) { - self.proto = proto - self.ciphertext = ciphertext - self.senderPublicKey = senderPublicKey - self.keyIndex = keyIndex - } - - @objc - public func serializedData() throws -> Data { - return try self.proto.serializedData() - } - - @objc public class func parseData(_ serializedData: Data) throws -> SPKProtoClosedGroupCiphertextMessage { - let proto = try SPKProtos_ClosedGroupCiphertextMessage(serializedData: serializedData) - return try parseProto(proto) - } - - fileprivate class func parseProto(_ proto: SPKProtos_ClosedGroupCiphertextMessage) throws -> SPKProtoClosedGroupCiphertextMessage { - guard proto.hasCiphertext else { - throw SPKProtoError.invalidProtobuf(description: "\(logTag) missing required field: ciphertext") - } - let ciphertext = proto.ciphertext - - guard proto.hasSenderPublicKey else { - throw SPKProtoError.invalidProtobuf(description: "\(logTag) missing required field: senderPublicKey") - } - let senderPublicKey = proto.senderPublicKey - - guard proto.hasKeyIndex else { - throw SPKProtoError.invalidProtobuf(description: "\(logTag) missing required field: keyIndex") - } - let keyIndex = proto.keyIndex - - // MARK: - Begin Validation Logic for SPKProtoClosedGroupCiphertextMessage - - - // MARK: - End Validation Logic for SPKProtoClosedGroupCiphertextMessage - - - let result = SPKProtoClosedGroupCiphertextMessage(proto: proto, - ciphertext: ciphertext, - senderPublicKey: senderPublicKey, - keyIndex: keyIndex) - return result - } - - @objc public override var debugDescription: String { - return "\(proto)" - } -} - -#if DEBUG - -extension SPKProtoClosedGroupCiphertextMessage { - @objc public func serializedDataIgnoringErrors() -> Data? { - return try! self.serializedData() - } -} - -extension SPKProtoClosedGroupCiphertextMessage.SPKProtoClosedGroupCiphertextMessageBuilder { - @objc public func buildIgnoringErrors() -> SPKProtoClosedGroupCiphertextMessage? { - return try! self.build() - } -} - -#endif diff --git a/SessionProtocolKit/Signal/Protos/WhisperTextProtocol.pb.swift b/SessionProtocolKit/Signal/Protos/WhisperTextProtocol.pb.swift deleted file mode 100644 index 8edcccf6d..000000000 --- a/SessionProtocolKit/Signal/Protos/WhisperTextProtocol.pb.swift +++ /dev/null @@ -1,642 +0,0 @@ -// DO NOT EDIT. -// swift-format-ignore-file -// -// Generated by the Swift generator plugin for the protocol buffer compiler. -// Source: WhisperTextProtocol.proto -// -// For information on using the generated types, please see the documentation: -// https://github.com/apple/swift-protobuf/ - -/// iOS - since we use a modern proto-compiler, we must specify -/// the legacy proto format. - -import Foundation -import SwiftProtobuf - -// If the compiler emits an error on this type, it is because this file -// was generated by a version of the `protoc` Swift plug-in that is -// incompatible with the version of SwiftProtobuf to which you are linking. -// Please ensure that you are building against the same version of the API -// that was used to generate this file. -fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { - struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} - typealias Version = _2 -} - -struct SPKProtos_TSProtoWhisperMessage { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// @required - var ratchetKey: Data { - get {return _ratchetKey ?? SwiftProtobuf.Internal.emptyData} - set {_ratchetKey = newValue} - } - /// Returns true if `ratchetKey` has been explicitly set. - var hasRatchetKey: Bool {return self._ratchetKey != nil} - /// Clears the value of `ratchetKey`. Subsequent reads from it will return its default value. - mutating func clearRatchetKey() {self._ratchetKey = nil} - - /// @required - var counter: UInt32 { - get {return _counter ?? 0} - set {_counter = newValue} - } - /// Returns true if `counter` has been explicitly set. - var hasCounter: Bool {return self._counter != nil} - /// Clears the value of `counter`. Subsequent reads from it will return its default value. - mutating func clearCounter() {self._counter = nil} - - var previousCounter: UInt32 { - get {return _previousCounter ?? 0} - set {_previousCounter = newValue} - } - /// Returns true if `previousCounter` has been explicitly set. - var hasPreviousCounter: Bool {return self._previousCounter != nil} - /// Clears the value of `previousCounter`. Subsequent reads from it will return its default value. - mutating func clearPreviousCounter() {self._previousCounter = nil} - - /// @required - var ciphertext: Data { - get {return _ciphertext ?? SwiftProtobuf.Internal.emptyData} - set {_ciphertext = newValue} - } - /// Returns true if `ciphertext` has been explicitly set. - var hasCiphertext: Bool {return self._ciphertext != nil} - /// Clears the value of `ciphertext`. Subsequent reads from it will return its default value. - mutating func clearCiphertext() {self._ciphertext = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _ratchetKey: Data? = nil - fileprivate var _counter: UInt32? = nil - fileprivate var _previousCounter: UInt32? = nil - fileprivate var _ciphertext: Data? = nil -} - -struct SPKProtos_TSProtoPreKeyWhisperMessage { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var registrationID: UInt32 { - get {return _registrationID ?? 0} - set {_registrationID = newValue} - } - /// Returns true if `registrationID` has been explicitly set. - var hasRegistrationID: Bool {return self._registrationID != nil} - /// Clears the value of `registrationID`. Subsequent reads from it will return its default value. - mutating func clearRegistrationID() {self._registrationID = nil} - - var preKeyID: UInt32 { - get {return _preKeyID ?? 0} - set {_preKeyID = newValue} - } - /// Returns true if `preKeyID` has been explicitly set. - var hasPreKeyID: Bool {return self._preKeyID != nil} - /// Clears the value of `preKeyID`. Subsequent reads from it will return its default value. - mutating func clearPreKeyID() {self._preKeyID = nil} - - /// @required - var signedPreKeyID: UInt32 { - get {return _signedPreKeyID ?? 0} - set {_signedPreKeyID = newValue} - } - /// Returns true if `signedPreKeyID` has been explicitly set. - var hasSignedPreKeyID: Bool {return self._signedPreKeyID != nil} - /// Clears the value of `signedPreKeyID`. Subsequent reads from it will return its default value. - mutating func clearSignedPreKeyID() {self._signedPreKeyID = nil} - - /// @required - var baseKey: Data { - get {return _baseKey ?? SwiftProtobuf.Internal.emptyData} - set {_baseKey = newValue} - } - /// Returns true if `baseKey` has been explicitly set. - var hasBaseKey: Bool {return self._baseKey != nil} - /// Clears the value of `baseKey`. Subsequent reads from it will return its default value. - mutating func clearBaseKey() {self._baseKey = nil} - - /// @required - var identityKey: Data { - get {return _identityKey ?? SwiftProtobuf.Internal.emptyData} - set {_identityKey = newValue} - } - /// Returns true if `identityKey` has been explicitly set. - var hasIdentityKey: Bool {return self._identityKey != nil} - /// Clears the value of `identityKey`. Subsequent reads from it will return its default value. - mutating func clearIdentityKey() {self._identityKey = nil} - - /// @required - var message: Data { - get {return _message ?? SwiftProtobuf.Internal.emptyData} - set {_message = newValue} - } - /// Returns true if `message` has been explicitly set. - var hasMessage: Bool {return self._message != nil} - /// Clears the value of `message`. Subsequent reads from it will return its default value. - mutating func clearMessage() {self._message = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _registrationID: UInt32? = nil - fileprivate var _preKeyID: UInt32? = nil - fileprivate var _signedPreKeyID: UInt32? = nil - fileprivate var _baseKey: Data? = nil - fileprivate var _identityKey: Data? = nil - fileprivate var _message: Data? = nil -} - -struct SPKProtos_TSProtoKeyExchangeMessage { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var id: UInt32 { - get {return _id ?? 0} - set {_id = newValue} - } - /// Returns true if `id` has been explicitly set. - var hasID: Bool {return self._id != nil} - /// Clears the value of `id`. Subsequent reads from it will return its default value. - mutating func clearID() {self._id = nil} - - var baseKey: Data { - get {return _baseKey ?? SwiftProtobuf.Internal.emptyData} - set {_baseKey = newValue} - } - /// Returns true if `baseKey` has been explicitly set. - var hasBaseKey: Bool {return self._baseKey != nil} - /// Clears the value of `baseKey`. Subsequent reads from it will return its default value. - mutating func clearBaseKey() {self._baseKey = nil} - - var ratchetKey: Data { - get {return _ratchetKey ?? SwiftProtobuf.Internal.emptyData} - set {_ratchetKey = newValue} - } - /// Returns true if `ratchetKey` has been explicitly set. - var hasRatchetKey: Bool {return self._ratchetKey != nil} - /// Clears the value of `ratchetKey`. Subsequent reads from it will return its default value. - mutating func clearRatchetKey() {self._ratchetKey = nil} - - var identityKey: Data { - get {return _identityKey ?? SwiftProtobuf.Internal.emptyData} - set {_identityKey = newValue} - } - /// Returns true if `identityKey` has been explicitly set. - var hasIdentityKey: Bool {return self._identityKey != nil} - /// Clears the value of `identityKey`. Subsequent reads from it will return its default value. - mutating func clearIdentityKey() {self._identityKey = nil} - - var baseKeySignature: Data { - get {return _baseKeySignature ?? SwiftProtobuf.Internal.emptyData} - set {_baseKeySignature = newValue} - } - /// Returns true if `baseKeySignature` has been explicitly set. - var hasBaseKeySignature: Bool {return self._baseKeySignature != nil} - /// Clears the value of `baseKeySignature`. Subsequent reads from it will return its default value. - mutating func clearBaseKeySignature() {self._baseKeySignature = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _id: UInt32? = nil - fileprivate var _baseKey: Data? = nil - fileprivate var _ratchetKey: Data? = nil - fileprivate var _identityKey: Data? = nil - fileprivate var _baseKeySignature: Data? = nil -} - -struct SPKProtos_TSProtoSenderKeyMessage { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var id: UInt32 { - get {return _id ?? 0} - set {_id = newValue} - } - /// Returns true if `id` has been explicitly set. - var hasID: Bool {return self._id != nil} - /// Clears the value of `id`. Subsequent reads from it will return its default value. - mutating func clearID() {self._id = nil} - - var iteration: UInt32 { - get {return _iteration ?? 0} - set {_iteration = newValue} - } - /// Returns true if `iteration` has been explicitly set. - var hasIteration: Bool {return self._iteration != nil} - /// Clears the value of `iteration`. Subsequent reads from it will return its default value. - mutating func clearIteration() {self._iteration = nil} - - var ciphertext: Data { - get {return _ciphertext ?? SwiftProtobuf.Internal.emptyData} - set {_ciphertext = newValue} - } - /// Returns true if `ciphertext` has been explicitly set. - var hasCiphertext: Bool {return self._ciphertext != nil} - /// Clears the value of `ciphertext`. Subsequent reads from it will return its default value. - mutating func clearCiphertext() {self._ciphertext = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _id: UInt32? = nil - fileprivate var _iteration: UInt32? = nil - fileprivate var _ciphertext: Data? = nil -} - -struct SPKProtos_TSProtoSenderKeyDistributionMessage { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var id: UInt32 { - get {return _id ?? 0} - set {_id = newValue} - } - /// Returns true if `id` has been explicitly set. - var hasID: Bool {return self._id != nil} - /// Clears the value of `id`. Subsequent reads from it will return its default value. - mutating func clearID() {self._id = nil} - - var iteration: UInt32 { - get {return _iteration ?? 0} - set {_iteration = newValue} - } - /// Returns true if `iteration` has been explicitly set. - var hasIteration: Bool {return self._iteration != nil} - /// Clears the value of `iteration`. Subsequent reads from it will return its default value. - mutating func clearIteration() {self._iteration = nil} - - var chainKey: Data { - get {return _chainKey ?? SwiftProtobuf.Internal.emptyData} - set {_chainKey = newValue} - } - /// Returns true if `chainKey` has been explicitly set. - var hasChainKey: Bool {return self._chainKey != nil} - /// Clears the value of `chainKey`. Subsequent reads from it will return its default value. - mutating func clearChainKey() {self._chainKey = nil} - - var signingKey: Data { - get {return _signingKey ?? SwiftProtobuf.Internal.emptyData} - set {_signingKey = newValue} - } - /// Returns true if `signingKey` has been explicitly set. - var hasSigningKey: Bool {return self._signingKey != nil} - /// Clears the value of `signingKey`. Subsequent reads from it will return its default value. - mutating func clearSigningKey() {self._signingKey = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _id: UInt32? = nil - fileprivate var _iteration: UInt32? = nil - fileprivate var _chainKey: Data? = nil - fileprivate var _signingKey: Data? = nil -} - -struct SPKProtos_ClosedGroupCiphertextMessage { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// @required - var ciphertext: Data { - get {return _ciphertext ?? SwiftProtobuf.Internal.emptyData} - set {_ciphertext = newValue} - } - /// Returns true if `ciphertext` has been explicitly set. - var hasCiphertext: Bool {return self._ciphertext != nil} - /// Clears the value of `ciphertext`. Subsequent reads from it will return its default value. - mutating func clearCiphertext() {self._ciphertext = nil} - - /// @required - var senderPublicKey: Data { - get {return _senderPublicKey ?? SwiftProtobuf.Internal.emptyData} - set {_senderPublicKey = newValue} - } - /// Returns true if `senderPublicKey` has been explicitly set. - var hasSenderPublicKey: Bool {return self._senderPublicKey != nil} - /// Clears the value of `senderPublicKey`. Subsequent reads from it will return its default value. - mutating func clearSenderPublicKey() {self._senderPublicKey = nil} - - /// @required - var keyIndex: UInt32 { - get {return _keyIndex ?? 0} - set {_keyIndex = newValue} - } - /// Returns true if `keyIndex` has been explicitly set. - var hasKeyIndex: Bool {return self._keyIndex != nil} - /// Clears the value of `keyIndex`. Subsequent reads from it will return its default value. - mutating func clearKeyIndex() {self._keyIndex = nil} - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _ciphertext: Data? = nil - fileprivate var _senderPublicKey: Data? = nil - fileprivate var _keyIndex: UInt32? = nil -} - -// MARK: - Code below here is support for the SwiftProtobuf runtime. - -fileprivate let _protobuf_package = "SPKProtos" - -extension SPKProtos_TSProtoWhisperMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".TSProtoWhisperMessage" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "ratchetKey"), - 2: .same(proto: "counter"), - 3: .same(proto: "previousCounter"), - 4: .same(proto: "ciphertext"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularBytesField(value: &self._ratchetKey) - case 2: try decoder.decodeSingularUInt32Field(value: &self._counter) - case 3: try decoder.decodeSingularUInt32Field(value: &self._previousCounter) - case 4: try decoder.decodeSingularBytesField(value: &self._ciphertext) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._ratchetKey { - try visitor.visitSingularBytesField(value: v, fieldNumber: 1) - } - if let v = self._counter { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 2) - } - if let v = self._previousCounter { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3) - } - if let v = self._ciphertext { - try visitor.visitSingularBytesField(value: v, fieldNumber: 4) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SPKProtos_TSProtoWhisperMessage, rhs: SPKProtos_TSProtoWhisperMessage) -> Bool { - if lhs._ratchetKey != rhs._ratchetKey {return false} - if lhs._counter != rhs._counter {return false} - if lhs._previousCounter != rhs._previousCounter {return false} - if lhs._ciphertext != rhs._ciphertext {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} - -extension SPKProtos_TSProtoPreKeyWhisperMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".TSProtoPreKeyWhisperMessage" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 5: .same(proto: "registrationId"), - 1: .same(proto: "preKeyId"), - 6: .same(proto: "signedPreKeyId"), - 2: .same(proto: "baseKey"), - 3: .same(proto: "identityKey"), - 4: .same(proto: "message"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularUInt32Field(value: &self._preKeyID) - case 2: try decoder.decodeSingularBytesField(value: &self._baseKey) - case 3: try decoder.decodeSingularBytesField(value: &self._identityKey) - case 4: try decoder.decodeSingularBytesField(value: &self._message) - case 5: try decoder.decodeSingularUInt32Field(value: &self._registrationID) - case 6: try decoder.decodeSingularUInt32Field(value: &self._signedPreKeyID) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._preKeyID { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) - } - if let v = self._baseKey { - try visitor.visitSingularBytesField(value: v, fieldNumber: 2) - } - if let v = self._identityKey { - try visitor.visitSingularBytesField(value: v, fieldNumber: 3) - } - if let v = self._message { - try visitor.visitSingularBytesField(value: v, fieldNumber: 4) - } - if let v = self._registrationID { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 5) - } - if let v = self._signedPreKeyID { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 6) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SPKProtos_TSProtoPreKeyWhisperMessage, rhs: SPKProtos_TSProtoPreKeyWhisperMessage) -> Bool { - if lhs._registrationID != rhs._registrationID {return false} - if lhs._preKeyID != rhs._preKeyID {return false} - if lhs._signedPreKeyID != rhs._signedPreKeyID {return false} - if lhs._baseKey != rhs._baseKey {return false} - if lhs._identityKey != rhs._identityKey {return false} - if lhs._message != rhs._message {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} - -extension SPKProtos_TSProtoKeyExchangeMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".TSProtoKeyExchangeMessage" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "id"), - 2: .same(proto: "baseKey"), - 3: .same(proto: "ratchetKey"), - 4: .same(proto: "identityKey"), - 5: .same(proto: "baseKeySignature"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularUInt32Field(value: &self._id) - case 2: try decoder.decodeSingularBytesField(value: &self._baseKey) - case 3: try decoder.decodeSingularBytesField(value: &self._ratchetKey) - case 4: try decoder.decodeSingularBytesField(value: &self._identityKey) - case 5: try decoder.decodeSingularBytesField(value: &self._baseKeySignature) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._id { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) - } - if let v = self._baseKey { - try visitor.visitSingularBytesField(value: v, fieldNumber: 2) - } - if let v = self._ratchetKey { - try visitor.visitSingularBytesField(value: v, fieldNumber: 3) - } - if let v = self._identityKey { - try visitor.visitSingularBytesField(value: v, fieldNumber: 4) - } - if let v = self._baseKeySignature { - try visitor.visitSingularBytesField(value: v, fieldNumber: 5) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SPKProtos_TSProtoKeyExchangeMessage, rhs: SPKProtos_TSProtoKeyExchangeMessage) -> Bool { - if lhs._id != rhs._id {return false} - if lhs._baseKey != rhs._baseKey {return false} - if lhs._ratchetKey != rhs._ratchetKey {return false} - if lhs._identityKey != rhs._identityKey {return false} - if lhs._baseKeySignature != rhs._baseKeySignature {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} - -extension SPKProtos_TSProtoSenderKeyMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".TSProtoSenderKeyMessage" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "id"), - 2: .same(proto: "iteration"), - 3: .same(proto: "ciphertext"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularUInt32Field(value: &self._id) - case 2: try decoder.decodeSingularUInt32Field(value: &self._iteration) - case 3: try decoder.decodeSingularBytesField(value: &self._ciphertext) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._id { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) - } - if let v = self._iteration { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 2) - } - if let v = self._ciphertext { - try visitor.visitSingularBytesField(value: v, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SPKProtos_TSProtoSenderKeyMessage, rhs: SPKProtos_TSProtoSenderKeyMessage) -> Bool { - if lhs._id != rhs._id {return false} - if lhs._iteration != rhs._iteration {return false} - if lhs._ciphertext != rhs._ciphertext {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} - -extension SPKProtos_TSProtoSenderKeyDistributionMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".TSProtoSenderKeyDistributionMessage" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "id"), - 2: .same(proto: "iteration"), - 3: .same(proto: "chainKey"), - 4: .same(proto: "signingKey"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularUInt32Field(value: &self._id) - case 2: try decoder.decodeSingularUInt32Field(value: &self._iteration) - case 3: try decoder.decodeSingularBytesField(value: &self._chainKey) - case 4: try decoder.decodeSingularBytesField(value: &self._signingKey) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._id { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 1) - } - if let v = self._iteration { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 2) - } - if let v = self._chainKey { - try visitor.visitSingularBytesField(value: v, fieldNumber: 3) - } - if let v = self._signingKey { - try visitor.visitSingularBytesField(value: v, fieldNumber: 4) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SPKProtos_TSProtoSenderKeyDistributionMessage, rhs: SPKProtos_TSProtoSenderKeyDistributionMessage) -> Bool { - if lhs._id != rhs._id {return false} - if lhs._iteration != rhs._iteration {return false} - if lhs._chainKey != rhs._chainKey {return false} - if lhs._signingKey != rhs._signingKey {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} - -extension SPKProtos_ClosedGroupCiphertextMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".ClosedGroupCiphertextMessage" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "ciphertext"), - 2: .same(proto: "senderPublicKey"), - 3: .same(proto: "keyIndex"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - switch fieldNumber { - case 1: try decoder.decodeSingularBytesField(value: &self._ciphertext) - case 2: try decoder.decodeSingularBytesField(value: &self._senderPublicKey) - case 3: try decoder.decodeSingularUInt32Field(value: &self._keyIndex) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = self._ciphertext { - try visitor.visitSingularBytesField(value: v, fieldNumber: 1) - } - if let v = self._senderPublicKey { - try visitor.visitSingularBytesField(value: v, fieldNumber: 2) - } - if let v = self._keyIndex { - try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func ==(lhs: SPKProtos_ClosedGroupCiphertextMessage, rhs: SPKProtos_ClosedGroupCiphertextMessage) -> Bool { - if lhs._ciphertext != rhs._ciphertext {return false} - if lhs._senderPublicKey != rhs._senderPublicKey {return false} - if lhs._keyIndex != rhs._keyIndex {return false} - if lhs.unknownFields != rhs.unknownFields {return false} - return true - } -} diff --git a/SessionProtocolKit/Signal/Ratchet/AliceAxolotlParameters.h b/SessionProtocolKit/Signal/Ratchet/AliceAxolotlParameters.h deleted file mode 100644 index 1623371f5..000000000 --- a/SessionProtocolKit/Signal/Ratchet/AliceAxolotlParameters.h +++ /dev/null @@ -1,22 +0,0 @@ -// -// AliceAxolotlParameters.h -// AxolotlKit -// -// Created by Frederic Jacobs on 26/07/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import - -#import "AxolotlParameters.h" - -@interface AliceAxolotlParameters : NSObject - -@property (nonatomic, readonly)ECKeyPair *ourBaseKey; -@property (nonatomic, readonly)NSData* theirSignedPreKey; -@property (nonatomic, readonly)NSData* theirRatchetKey; -@property (nonatomic, readonly)NSData* theirOneTimePrekey; - -- (instancetype)initWithIdentityKey:(ECKeyPair*)myIdentityKey theirIdentityKey:(NSData*)theirIdentityKey ourBaseKey:(ECKeyPair*)ourBaseKey theirSignedPreKey:(NSData*)theirSignedPreKey theirOneTimePreKey:(NSData*)theirOneTimePreKey theirRatchetKey:(NSData*)theirRatchetKey; - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/AliceAxolotlParameters.m b/SessionProtocolKit/Signal/Ratchet/AliceAxolotlParameters.m deleted file mode 100644 index 10d3189a5..000000000 --- a/SessionProtocolKit/Signal/Ratchet/AliceAxolotlParameters.m +++ /dev/null @@ -1,39 +0,0 @@ -// -// AliceAxolotlParameters.m -// AxolotlKit -// -// Created by Frederic Jacobs on 26/07/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import "AliceAxolotlParameters.h" -#import - -@implementation AliceAxolotlParameters - -@synthesize ourIdentityKeyPair=_ourIdentityKeyPair, theirIdentityKey=_theirIdentityKey; - -- (instancetype)initWithIdentityKey:(ECKeyPair*)myIdentityKey theirIdentityKey:(NSData*)theirIdentityKey ourBaseKey:(ECKeyPair*)ourBaseKey theirSignedPreKey:(NSData*)theirSignedPreKey theirOneTimePreKey:(NSData*)theirOneTimePreKey theirRatchetKey:(NSData*)theirRatchetKey{ - - OWSAssert(myIdentityKey); - OWSAssert(theirIdentityKey); - OWSAssert(ourBaseKey); - OWSAssert(theirSignedPreKey); - OWSAssert(theirRatchetKey); - - self = [super init]; - - if (self) { - _ourIdentityKeyPair = myIdentityKey; - _theirIdentityKey = theirIdentityKey; - _ourBaseKey = ourBaseKey; - _theirSignedPreKey = theirSignedPreKey; - _theirOneTimePrekey = theirOneTimePreKey; - _theirRatchetKey = theirRatchetKey; - } - - return self; -} - - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/AxolotlParameters.h b/SessionProtocolKit/Signal/Ratchet/AxolotlParameters.h deleted file mode 100644 index 5d83e9fa2..000000000 --- a/SessionProtocolKit/Signal/Ratchet/AxolotlParameters.h +++ /dev/null @@ -1,13 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import -#import - -@protocol AxolotlParameters - -@property (nonatomic) ECKeyPair *ourIdentityKeyPair; -@property (nonatomic) NSData *theirIdentityKey; - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/BobAxolotlParameters.h b/SessionProtocolKit/Signal/Ratchet/BobAxolotlParameters.h deleted file mode 100644 index 14ec22b7b..000000000 --- a/SessionProtocolKit/Signal/Ratchet/BobAxolotlParameters.h +++ /dev/null @@ -1,22 +0,0 @@ -// -// BobAxolotlParameters.h -// AxolotlKit -// -// Created by Frederic Jacobs on 26/07/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import -#import "AxolotlParameters.h" - -@interface BobAxolotlParameters : NSObject - -@property (nonatomic, readonly)ECKeyPair *ourSignedPrekey; -@property (nonatomic, readonly)ECKeyPair *ourRatchetKey; -@property (nonatomic, readonly)ECKeyPair *ourOneTimePrekey; - -@property (nonatomic, readonly)NSData *theirBaseKey; - -- (instancetype)initWithMyIdentityKeyPair:(ECKeyPair*)ourIdentityKeyPair theirIdentityKey:(NSData*)theirIdentityKey ourSignedPrekey:(ECKeyPair*)ourSignedPrekey ourRatchetKey:(ECKeyPair*)ourRatchetKey ourOneTimePrekey:(ECKeyPair*)ourOneTimeKeyPair theirBaseKey:(NSData*)theirBaseKey; - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/BobAxolotlParameters.m b/SessionProtocolKit/Signal/Ratchet/BobAxolotlParameters.m deleted file mode 100644 index 1d1f83a5b..000000000 --- a/SessionProtocolKit/Signal/Ratchet/BobAxolotlParameters.m +++ /dev/null @@ -1,37 +0,0 @@ -// -// BobAxolotlParameters.m -// AxolotlKit -// -// Created by Frederic Jacobs on 26/07/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import "BobAxolotlParameters.h" -#import - -@implementation BobAxolotlParameters - -@synthesize theirIdentityKey=_theirIdentityKey, ourIdentityKeyPair=_ourIdentityKeyPair; - -- (instancetype)initWithMyIdentityKeyPair:(ECKeyPair*)ourIdentityKeyPair theirIdentityKey:(NSData*)theirIdentityKey ourSignedPrekey:(ECKeyPair*)ourSignedPrekey ourRatchetKey:(ECKeyPair*)ourRatchetKey ourOneTimePrekey:(ECKeyPair*)ourOneTimeKeyPair theirBaseKey:(NSData*)theirBaseKey{ - - OWSAssert(ourIdentityKeyPair); - OWSAssert(theirIdentityKey); - OWSAssert(ourSignedPrekey); - OWSAssert(ourRatchetKey); - OWSAssert(theirBaseKey); - - self = [super init]; - - if (self) { - _ourIdentityKeyPair = ourIdentityKeyPair; - _theirIdentityKey = theirIdentityKey; - _ourSignedPrekey = ourSignedPrekey; - _ourRatchetKey = ourRatchetKey; - _ourOneTimePrekey = ourOneTimeKeyPair; - _theirBaseKey = theirBaseKey; - } - return self; -} - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/Chain.h b/SessionProtocolKit/Signal/Ratchet/Chain.h deleted file mode 100644 index 1fa3249e3..000000000 --- a/SessionProtocolKit/Signal/Ratchet/Chain.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// Chain.h -// AxolotlKit -// -// Created by Frederic Jacobs on 02/09/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import -@class ChainKey; - -@protocol Chain - --(ChainKey*)chainKey; --(void)setChainKey:(ChainKey*)chainKey; - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/ChainAndIndex.h b/SessionProtocolKit/Signal/Ratchet/ChainAndIndex.h deleted file mode 100644 index 57b82f945..000000000 --- a/SessionProtocolKit/Signal/Ratchet/ChainAndIndex.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// ChainAndIndex.h -// AxolotlKit -// -// Created by Frederic Jacobs on 21/09/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import -#import "ChainKey.h" - -@interface ChainAndIndex : NSObject - -@property id chain; -@property int index; - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/ChainAndIndex.m b/SessionProtocolKit/Signal/Ratchet/ChainAndIndex.m deleted file mode 100644 index f326f4c1c..000000000 --- a/SessionProtocolKit/Signal/Ratchet/ChainAndIndex.m +++ /dev/null @@ -1,13 +0,0 @@ -// -// ChainAndIndex.m -// AxolotlKit -// -// Created by Frederic Jacobs on 21/09/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import "ChainAndIndex.h" - -@implementation ChainAndIndex - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/ChainKey.h b/SessionProtocolKit/Signal/Ratchet/ChainKey.h deleted file mode 100644 index aad87afe3..000000000 --- a/SessionProtocolKit/Signal/Ratchet/ChainKey.h +++ /dev/null @@ -1,25 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "Chain.h" -#import "MessageKeys.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface ChainKey : NSObject - -@property (nonatomic, readonly) int index; -@property (nonatomic, readonly) NSData *key; - -- (instancetype)init NS_UNAVAILABLE; -- (instancetype)initWithData:(NSData *)chainKey index:(int)index NS_DESIGNATED_INITIALIZER; - -- (instancetype)nextChainKey; - -- (MessageKeys *)throws_messageKeys NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Ratchet/ChainKey.m b/SessionProtocolKit/Signal/Ratchet/ChainKey.m deleted file mode 100644 index 5ac5d146e..000000000 --- a/SessionProtocolKit/Signal/Ratchet/ChainKey.m +++ /dev/null @@ -1,96 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "ChainKey.h" -#import "TSDerivedSecrets.h" -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@implementation ChainKey - -static NSString *const kCoderKey = @"kCoderKey"; -static NSString *const kCoderIndex = @"kCoderIndex"; - -#define kTSKeySeedLength 1 - -static uint8_t kMessageKeySeed[kTSKeySeedLength] = { 01 }; -static uint8_t kChainKeySeed[kTSKeySeedLength] = { 02 }; - -+ (BOOL)supportsSecureCoding -{ - return YES; -} - -- (nullable id)initWithCoder:(NSCoder *)aDecoder -{ - NSData *key = [aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderKey]; - int index = [aDecoder decodeIntForKey:kCoderIndex]; - - return [self initWithData:key index:index]; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder -{ - [aCoder encodeObject:_key forKey:kCoderKey]; - [aCoder encodeInt:_index forKey:kCoderIndex]; -} - -- (instancetype)initWithData:(NSData *)chainKey index:(int)index -{ - OWSAssert(chainKey.length == 32); - OWSAssert(index >= 0); - - self = [super init]; - - if (self) { - _key = chainKey; - _index = index; - } - - return self; -} - -- (instancetype)nextChainKey -{ - NSData *nextCK = [self baseMaterial:[NSData dataWithBytes:kChainKeySeed length:kTSKeySeedLength]]; - OWSAssert(nextCK.length == 32); - - int nextIndex; - ows_add_overflow(self.index, 1, &nextIndex); - return [[ChainKey alloc] initWithData:nextCK index:nextIndex]; -} - -- (MessageKeys *)throws_messageKeys -{ - NSData *inputKeyMaterial = [self baseMaterial:[NSData dataWithBytes:kMessageKeySeed length:kTSKeySeedLength]]; - TSDerivedSecrets *derivedSecrets = [TSDerivedSecrets throws_derivedMessageKeysWithData:inputKeyMaterial]; - return [[MessageKeys alloc] initWithCipherKey:derivedSecrets.cipherKey - macKey:derivedSecrets.macKey - iv:derivedSecrets.iv - index:self.index]; -} - -- (NSData *)baseMaterial:(NSData *)seed -{ - OWSAssert(self.key); - OWSAssert(self.key.length == 32); - OWSAssert(seed); - OWSAssert(seed.length == kTSKeySeedLength); - - NSMutableData *_Nullable bufferData = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH]; - OWSAssert(bufferData); - - CCHmacContext ctx; - CCHmacInit(&ctx, kCCHmacAlgSHA256, [self.key bytes], [self.key length]); - CCHmacUpdate(&ctx, [seed bytes], [seed length]); - CCHmacFinal(&ctx, bufferData.mutableBytes); - return [bufferData copy]; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Ratchet/MessageKeys.h b/SessionProtocolKit/Signal/Ratchet/MessageKeys.h deleted file mode 100644 index 6ce8bad41..000000000 --- a/SessionProtocolKit/Signal/Ratchet/MessageKeys.h +++ /dev/null @@ -1,20 +0,0 @@ -// -// TSMessageKeys.h -// AxolotlKit -// -// Created by Frederic Jacobs on 09/03/14. -// Copyright (c) 2014 Open Whisper Systems. All rights reserved. -// - -#import - -@interface MessageKeys : NSObject - -- (instancetype)initWithCipherKey:(NSData*)cipherKey macKey:(NSData*)macKey iv:(NSData*)data index:(int)index; - -@property (readonly)NSData *cipherKey; -@property (readonly)NSData *macKey; -@property (readonly)NSData *iv; -@property (readonly)int index; - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/MessageKeys.m b/SessionProtocolKit/Signal/Ratchet/MessageKeys.m deleted file mode 100644 index 7cb2af79f..000000000 --- a/SessionProtocolKit/Signal/Ratchet/MessageKeys.m +++ /dev/null @@ -1,62 +0,0 @@ -// -// TSMessageKeys.m -// AxolotlKit -// -// Created by Frederic Jacobs on 09/03/14. -// Copyright (c) 2014 Open Whisper Systems. All rights reserved. -// - -#import "MessageKeys.h" -#import - -static NSString* const kCoderMessageKeysCipherKey = @"kCoderMessageKeysCipherKey"; -static NSString* const kCoderMessageKeysMacKey = @"kCoderMessageKeysMacKey"; -static NSString* const kCoderMessageKeysIVKey = @"kCoderMessageKeysIVKey"; -static NSString* const kCoderMessageKeysIndex = @"kCoderMessageKeysIndex"; - - -@implementation MessageKeys - -+ (BOOL)supportsSecureCoding{ - return YES; -} - -- (id)initWithCoder:(NSCoder *)aDecoder{ - self = [self initWithCipherKey:[aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderMessageKeysCipherKey] - macKey:[aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderMessageKeysMacKey] - iv:[aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderMessageKeysIVKey] - index:[aDecoder decodeIntForKey:kCoderMessageKeysIndex]]; - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder{ - [aCoder encodeObject:self.cipherKey forKey:kCoderMessageKeysCipherKey]; - [aCoder encodeObject:self.macKey forKey:kCoderMessageKeysMacKey]; - [aCoder encodeObject:self.iv forKey:kCoderMessageKeysIVKey]; - [aCoder encodeInt:self.index forKey:kCoderMessageKeysIndex]; -} - - -- (instancetype)initWithCipherKey:(NSData*)cipherKey macKey:(NSData*)macKey iv:(NSData *)data index:(int)index{ - - OWSAssert(cipherKey); - OWSAssert(macKey); - OWSAssert(data); - - self = [super init]; - - if (self) { - _cipherKey = cipherKey; - _macKey = macKey; - _iv = data; - _index = index; - } - - return self; -} - --(NSString*) debugDescription { - return [NSString stringWithFormat:@"cipherKey: %@\n macKey %@\n",self.cipherKey,self.macKey]; -} - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/RKCK.h b/SessionProtocolKit/Signal/Ratchet/RKCK.h deleted file mode 100644 index 895717124..000000000 --- a/SessionProtocolKit/Signal/Ratchet/RKCK.h +++ /dev/null @@ -1,19 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "Chain.h" -#import "RootKey.h" -#import "SessionState.h" -#import - -@class ECKeyPair; - -@interface RKCK : NSObject - -@property (nonatomic,strong) RootKey *rootKey; -@property (nonatomic,strong) ChainKey *chainKey; - --(instancetype) initWithRK:(RootKey*)rootKey CK:(ChainKey*)chainKey; - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/RKCK.m b/SessionProtocolKit/Signal/Ratchet/RKCK.m deleted file mode 100644 index 7aade2d12..000000000 --- a/SessionProtocolKit/Signal/Ratchet/RKCK.m +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import "RKCK.h" -#import -#import "TSDerivedSecrets.h" -#import - -@implementation RKCK - -- (instancetype)initWithRK:(RootKey*)rootKey CK:(ChainKey*)chainKey{ - OWSAssert(rootKey); - OWSAssert(chainKey); - - self = [super init]; - self.rootKey = rootKey; - self.chainKey = chainKey; - return self; -} - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/RatchetingSession.h b/SessionProtocolKit/Signal/Ratchet/RatchetingSession.h deleted file mode 100644 index d141123c6..000000000 --- a/SessionProtocolKit/Signal/Ratchet/RatchetingSession.h +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -@class AliceAxolotlParameters; -@class BobAxolotlParameters; -@class ECKeyPair; -@class SessionState; - -@interface RatchetingSession : NSObject - -+ (void)throws_initializeSession:(SessionState *)session - sessionVersion:(int)sessionVersion - AliceParameters:(AliceAxolotlParameters *)parameters NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -+ (BOOL)initializeSession:(SessionState *)session - sessionVersion:(int)sessionVersion - aliceParameters:(AliceAxolotlParameters *)aliceParameters - error:(NSError **)outError; - -+ (void)throws_initializeSession:(SessionState *)session - sessionVersion:(int)sessionVersion - BobParameters:(BobAxolotlParameters *)parameters NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -+ (BOOL)initializeSession:(SessionState *)session - sessionVersion:(int)sessionVersion - bobParameters:(BobAxolotlParameters *)bobParameters - error:(NSError **)outError; - -/** - * For testing purposes - */ - -+ (void)throws_initializeSession:(SessionState *)session - sessionVersion:(int)sessionVersion - AliceParameters:(AliceAxolotlParameters *)parameters - senderRatchet:(ECKeyPair *)ratchet NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/RatchetingSession.m b/SessionProtocolKit/Signal/Ratchet/RatchetingSession.m deleted file mode 100644 index a7fc66ee3..000000000 --- a/SessionProtocolKit/Signal/Ratchet/RatchetingSession.m +++ /dev/null @@ -1,188 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "RatchetingSession.h" -#import "AliceAxolotlParameters.h" -#import "BobAxolotlParameters.h" -#import "ChainKey.h" -#import "RootKey.h" -#import "SessionState.h" -#import -#import -#import -#import - -@interface DHEResult : NSObject - -@property (nonatomic, readonly) RootKey *rootKey; -@property (nonatomic, readonly) NSData *chainKey; - -- (instancetype)init_throws_withMasterKey:(NSData *)data NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -@end - -@implementation DHEResult - -- (instancetype)init_throws_withMasterKey:(NSData *)data -{ - // DHE Result is expected to be the result of 3 or 4 DHEs outputting 32 bytes each, - // plus the 32 discontinuity bytes added to make V3 incompatible with V2 - OWSAssert([data length] == 32 * 4 || [data length] == 32 * 5); - - self = [super init]; - const char *HKDFDefaultSalt[4] = {0}; - NSData *salt = [NSData dataWithBytes:HKDFDefaultSalt length:sizeof(HKDFDefaultSalt)]; - NSData *info = [@"WhisperText" dataUsingEncoding:NSUTF8StringEncoding]; - NSData *derivedMaterial = [HKDFKit deriveKey:data info:info salt:salt outputSize:64]; - OWSAssert(derivedMaterial.length == 64); - _rootKey = [[RootKey alloc] initWithData:[derivedMaterial subdataWithRange:NSMakeRange(0, 32)]]; - _chainKey = [derivedMaterial subdataWithRange:NSMakeRange(32, 32)]; - - return self; -} - -@end - - -@implementation RatchetingSession - -+ (void)throws_initializeSession:(SessionState *)session - sessionVersion:(int)sessionVersion - AliceParameters:(AliceAxolotlParameters *)parameters -{ - OWSAssert(session); - OWSAssert(parameters); - - ECKeyPair *sendingRatchetKey = [Curve25519 generateKeyPair]; - OWSAssert(sendingRatchetKey); - [self throws_initializeSession:session - sessionVersion:sessionVersion - AliceParameters:parameters - senderRatchet:sendingRatchetKey]; -} - -+ (BOOL)initializeSession:(SessionState *)session - sessionVersion:(int)sessionVersion - bobParameters:(BobAxolotlParameters *)bobParameters - error:(NSError **)outError -{ - return [SCKExceptionWrapper - tryBlock:^{ - [self throws_initializeSession:session sessionVersion:sessionVersion BobParameters:bobParameters]; - } - error:outError]; -} - -+ (void)throws_initializeSession:(SessionState *)session - sessionVersion:(int)sessionVersion - BobParameters:(BobAxolotlParameters *)parameters -{ - OWSAssert(session); - OWSAssert(parameters); - - [session setVersion:sessionVersion]; - [session setRemoteIdentityKey:parameters.theirIdentityKey]; - [session setLocalIdentityKey:parameters.ourIdentityKeyPair.publicKey]; - - DHEResult *result = [self throws_DHEKeyAgreement:parameters]; - OWSAssert(result); - - [session setSenderChain:parameters.ourRatchetKey chainKey:[[ChainKey alloc]initWithData:result.chainKey index:0]]; - [session setRootKey:result.rootKey]; -} - -+ (BOOL)initializeSession:(SessionState *)session - sessionVersion:(int)sessionVersion - aliceParameters:(AliceAxolotlParameters *)aliceParameters - error:(NSError **)outError -{ - return [SCKExceptionWrapper - tryBlock:^{ - [self throws_initializeSession:session sessionVersion:sessionVersion AliceParameters:aliceParameters]; - } - error:outError]; -} - -+ (void)throws_initializeSession:(SessionState *)session - sessionVersion:(int)sessionVersion - AliceParameters:(AliceAxolotlParameters *)parameters - senderRatchet:(ECKeyPair *)sendingRatchet -{ - - OWSAssert(session); - OWSAssert(parameters); - OWSAssert(sendingRatchet); - - [session setVersion:sessionVersion]; - [session setRemoteIdentityKey:parameters.theirIdentityKey]; - [session setLocalIdentityKey:parameters.ourIdentityKeyPair.publicKey]; - - DHEResult *result = [self throws_DHEKeyAgreement:parameters]; - OWSAssert(result); - RKCK *sendingChain = - [result.rootKey throws_createChainWithTheirEphemeral:parameters.theirRatchetKey ourEphemeral:sendingRatchet]; - OWSAssert(sendingChain); - - [session addReceiverChain:parameters.theirRatchetKey chainKey:[[ChainKey alloc]initWithData:result.chainKey index:0]]; - [session setSenderChain:sendingRatchet chainKey:sendingChain.chainKey]; - [session setRootKey:sendingChain.rootKey]; -} - -+ (DHEResult *)throws_DHEKeyAgreement:(id)parameters -{ - OWSAssert(parameters); - - NSMutableData *masterKey = [NSMutableData data]; - - [masterKey appendData:[self discontinuityBytes]]; - - if ([parameters isKindOfClass:[AliceAxolotlParameters class]]) { - AliceAxolotlParameters *params = (AliceAxolotlParameters*)parameters; - - [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirSignedPreKey - andKeyPair:params.ourIdentityKeyPair]]; - [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirIdentityKey - andKeyPair:params.ourBaseKey]]; - [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirSignedPreKey - andKeyPair:params.ourBaseKey]]; - if (params.theirOneTimePrekey) { - [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirOneTimePrekey - andKeyPair:params.ourBaseKey]]; - } - } else if ([parameters isKindOfClass:[BobAxolotlParameters class]]){ - BobAxolotlParameters *params = (BobAxolotlParameters*)parameters; - - [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirIdentityKey - andKeyPair:params.ourSignedPrekey]]; - [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirBaseKey - andKeyPair:params.ourIdentityKeyPair]]; - [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirBaseKey - andKeyPair:params.ourSignedPrekey]]; - if (params.ourOneTimePrekey) { - [masterKey appendData:[Curve25519 throws_generateSharedSecretFromPublicKey:params.theirBaseKey - andKeyPair:params.ourOneTimePrekey]]; - } - } - - return [[DHEResult alloc] init_throws_withMasterKey:masterKey]; -} - -/** - * The discontinuity bytes enforce that the session initialization is different between protocol V2 and V3. - * - * @return Returns 32-bytes of 0xFF - */ - -+ (NSData*)discontinuityBytes{ - NSMutableData *discontinuity = [NSMutableData data]; - int8_t byte = 0xFF; - - for (int i = 0; i < 32; i++) { - [discontinuity appendBytes:&byte length:sizeof(int8_t)]; - } - return [NSData dataWithData:discontinuity]; -} - - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/ReceivingChain.h b/SessionProtocolKit/Signal/Ratchet/ReceivingChain.h deleted file mode 100644 index 9904bfd26..000000000 --- a/SessionProtocolKit/Signal/Ratchet/ReceivingChain.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import -#import "Chain.h" -#import - -@interface ReceivingChain : NSObject - -- (instancetype)initWithChainKey:(ChainKey*)chainKey senderRatchetKey:(NSData*)senderRatchet; - -@property NSMutableArray *messageKeysList; -@property NSData *senderRatchetKey; - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/ReceivingChain.m b/SessionProtocolKit/Signal/Ratchet/ReceivingChain.m deleted file mode 100644 index c489c67ab..000000000 --- a/SessionProtocolKit/Signal/Ratchet/ReceivingChain.m +++ /dev/null @@ -1,57 +0,0 @@ -// -// ReceivingChain.m -// AxolotlKit -// -// Created by Frederic Jacobs on 02/09/14. -// Copyright (c) 2014 Frederic Jacobs. All rights reserved. -// - -#import "ReceivingChain.h" -#import - -@interface ReceivingChain () - -@property (nonatomic)ChainKey *chainKey; - -@end - -@implementation ReceivingChain - -static NSString* const kCoderChainKey = @"kCoderChainKey"; -static NSString* const kCoderSenderRatchet = @"kCoderSenderRatchet"; -static NSString* const kCoderMessageKeys = @"kCoderMessageKeys"; - -+ (BOOL)supportsSecureCoding{ - return YES; -} - -- (id)initWithCoder:(NSCoder *)aDecoder{ - self = [self initWithChainKey:[aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderChainKey] - senderRatchetKey:[aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderSenderRatchet]]; - if (self) { - self.messageKeysList = [aDecoder decodeObjectOfClass:[NSMutableArray class] forKey:kCoderMessageKeys]; - } - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder{ - [aCoder encodeObject:self.chainKey forKey:kCoderChainKey]; - [aCoder encodeObject:self.senderRatchetKey forKey:kCoderSenderRatchet]; - [aCoder encodeObject:self.messageKeysList forKey:kCoderMessageKeys]; -} - -- (instancetype)initWithChainKey:(ChainKey *)chainKey senderRatchetKey:(NSData *)senderRatchet{ - OWSAssert(chainKey); - OWSAssert(senderRatchet); - - self = [super init]; - - self.chainKey = chainKey; - self.senderRatchetKey = senderRatchet; - self.messageKeysList = [NSMutableArray array]; - - return self; -} - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/RootKey.h b/SessionProtocolKit/Signal/Ratchet/RootKey.h deleted file mode 100644 index 7882d7baa..000000000 --- a/SessionProtocolKit/Signal/Ratchet/RootKey.h +++ /dev/null @@ -1,18 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -@class ECKeyPair; -@class RKCK; - -@interface RootKey : NSObject - -- (instancetype)initWithData:(NSData *)data; -- (RKCK *)throws_createChainWithTheirEphemeral:(NSData *)theirEphemeral - ourEphemeral:(ECKeyPair *)ourEphemeral NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -@property (nonatomic, readonly) NSData *keyData; - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/RootKey.m b/SessionProtocolKit/Signal/Ratchet/RootKey.m deleted file mode 100644 index fd905642d..000000000 --- a/SessionProtocolKit/Signal/Ratchet/RootKey.m +++ /dev/null @@ -1,64 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "RootKey.h" -#import "ChainKey.h" -#import "RKCK.h" -#import "TSDerivedSecrets.h" -#import -#import - -static NSString* const kCoderData = @"kCoderData"; - -@implementation RootKey - -+(BOOL)supportsSecureCoding{ - return YES; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder{ - [aCoder encodeObject:_keyData forKey:kCoderData]; -} - -- (id)initWithCoder:(NSCoder *)aDecoder{ - self = [super init]; - - if (self) { - _keyData = [aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderData]; - } - - return self; -} - -- (instancetype)initWithData:(NSData *)data{ - self = [super init]; - - OWSAssert(data.length == 32); - - if (self) { - _keyData = data; - } - - return self; -} - -- (RKCK *)throws_createChainWithTheirEphemeral:(NSData *)theirEphemeral ourEphemeral:(ECKeyPair *)ourEphemeral -{ - OWSAssert(theirEphemeral); - OWSAssert(ourEphemeral); - - NSData *sharedSecret = [Curve25519 throws_generateSharedSecretFromPublicKey:theirEphemeral andKeyPair:ourEphemeral]; - OWSAssert(sharedSecret.length == 32); - - TSDerivedSecrets *secrets = - [TSDerivedSecrets throws_derivedRatchetedSecretsWithSharedSecret:sharedSecret rootKey:_keyData]; - OWSAssert(secrets); - - RKCK *newRKCK = [[RKCK alloc] initWithRK:[[RootKey alloc] initWithData:secrets.cipherKey] - CK:[[ChainKey alloc] initWithData:secrets.macKey index:0]]; - - return newRKCK; -} - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/SendingChain.h b/SessionProtocolKit/Signal/Ratchet/SendingChain.h deleted file mode 100644 index c6e787d09..000000000 --- a/SessionProtocolKit/Signal/Ratchet/SendingChain.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import -#import "Chain.h" - -#import - -@interface SendingChain : NSObject - --(instancetype)initWithChainKey:(ChainKey*)chainKey senderRatchetKeyPair:(ECKeyPair*)keyPair; - -@property ECKeyPair *senderRatchetKeyPair; - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/SendingChain.m b/SessionProtocolKit/Signal/Ratchet/SendingChain.m deleted file mode 100644 index 10502f6d0..000000000 --- a/SessionProtocolKit/Signal/Ratchet/SendingChain.m +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import "SendingChain.h" -#import "ChainKey.h" -#import - -@interface SendingChain () - -@property (nonatomic)ChainKey *chainKey; - -@end - -@implementation SendingChain - -static NSString* const kCoderChainKey = @"kCoderChainKey"; -static NSString* const kCoderSenderRatchet = @"kCoderSenderRatchet"; - -+ (BOOL)supportsSecureCoding{ - return YES; -} - -- (id)initWithCoder:(NSCoder *)aDecoder{ - self = [self initWithChainKey:[aDecoder decodeObjectOfClass:[ChainKey class] forKey:kCoderChainKey] - senderRatchetKeyPair:[aDecoder decodeObjectOfClass:[ECKeyPair class] forKey:kCoderSenderRatchet]]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder{ - [aCoder encodeObject:self.chainKey forKey:kCoderChainKey]; - [aCoder encodeObject:self.senderRatchetKeyPair forKey:kCoderSenderRatchet]; -} - -- (instancetype)initWithChainKey:(ChainKey *)chainKey senderRatchetKeyPair:(ECKeyPair *)keyPair{ - self = [super init]; - - OWSAssert(chainKey.key.length == 32); - OWSAssert(keyPair); - - if (self) { - _chainKey = chainKey; - _senderRatchetKeyPair = keyPair; - } - - return self; -} - --(ChainKey *)chainKey{ - return _chainKey; -} - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/TSDerivedSecrets.h b/SessionProtocolKit/Signal/Ratchet/TSDerivedSecrets.h deleted file mode 100644 index 9497dfe83..000000000 --- a/SessionProtocolKit/Signal/Ratchet/TSDerivedSecrets.h +++ /dev/null @@ -1,20 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -@interface TSDerivedSecrets : NSData - -+ (instancetype)throws_derivedInitialSecretsWithMasterKey:(NSData *)masterKey - NS_SWIFT_UNAVAILABLE("throws objc exceptions"); -+ (instancetype)throws_derivedRatchetedSecretsWithSharedSecret:(NSData *)masterKey - rootKey:(NSData *)rootKey - NS_SWIFT_UNAVAILABLE("throws objc exceptions"); -+ (instancetype)throws_derivedMessageKeysWithData:(NSData *)data NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -@property NSData *cipherKey; -@property NSData *macKey; -@property NSData *iv; - -@end diff --git a/SessionProtocolKit/Signal/Ratchet/TSDerivedSecrets.m b/SessionProtocolKit/Signal/Ratchet/TSDerivedSecrets.m deleted file mode 100644 index 931d13cf2..000000000 --- a/SessionProtocolKit/Signal/Ratchet/TSDerivedSecrets.m +++ /dev/null @@ -1,67 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "TSDerivedSecrets.h" -#import -#import -#import - -@implementation TSDerivedSecrets - -+ (instancetype)throws_derivedSecretsWithSeed:(NSData *)masterKey salt:(NSData *)salt info:(NSData *)info -{ - OWSAssert(masterKey.length == 32); - OWSAssert(info); - - TSDerivedSecrets *secrets = [[TSDerivedSecrets alloc] init]; - OWSAssert(secrets); - - if (!salt) { - const char *HKDFDefaultSalt[4] = {0}; - salt = [NSData dataWithBytes:HKDFDefaultSalt length:sizeof(HKDFDefaultSalt)]; - } - - @try { - NSData *derivedMaterial = [HKDFKit deriveKey:masterKey info:info salt:salt outputSize:96]; - secrets.cipherKey = [derivedMaterial subdataWithRange:NSMakeRange(0, 32)]; - secrets.macKey = [derivedMaterial subdataWithRange:NSMakeRange(32, 32)]; - secrets.iv = [derivedMaterial subdataWithRange:NSMakeRange(64, 16)]; - } - @catch (NSException *exception) { - @throw NSInvalidArgumentException; - } - - OWSAssert(secrets.cipherKey.length == 32); - OWSAssert(secrets.macKey.length == 32); - OWSAssert(secrets.iv.length == 16); - - return secrets; -} - -+ (instancetype)throws_derivedInitialSecretsWithMasterKey:(NSData *)masterKey -{ - OWSAssert(masterKey); - - NSData *info = [@"WhisperText" dataUsingEncoding:NSUTF8StringEncoding]; - return [self throws_derivedSecretsWithSeed:masterKey salt:nil info:info]; -} - -+ (instancetype)throws_derivedRatchetedSecretsWithSharedSecret:(NSData *)masterKey rootKey:(NSData *)rootKey -{ - OWSAssert(masterKey); - OWSAssert(rootKey); - - NSData *info = [@"WhisperRatchet" dataUsingEncoding:NSUTF8StringEncoding]; - return [self throws_derivedSecretsWithSeed:masterKey salt:rootKey info:info]; -} - -+ (instancetype)throws_derivedMessageKeysWithData:(NSData *)data -{ - OWSAssert(data); - - NSData *info = [@"WhisperMessageKeys" dataUsingEncoding:NSUTF8StringEncoding]; - return [self throws_derivedSecretsWithSeed:data salt:nil info:info]; -} - -@end diff --git a/SessionProtocolKit/Signal/SMKCertificateValidator.swift b/SessionProtocolKit/Signal/SMKCertificateValidator.swift deleted file mode 100644 index da8b7efbd..000000000 --- a/SessionProtocolKit/Signal/SMKCertificateValidator.swift +++ /dev/null @@ -1,107 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation -import SignalCoreKit - -public enum SMKCertificateError: Error { - case invalidCertificate(description: String) -} - -@objc public protocol SMKCertificateValidator: class { - - @objc func throwswrapped_validate(senderCertificate: SMKSenderCertificate, validationTime: UInt64) throws - - @objc func throwswrapped_validate(serverCertificate: SMKServerCertificate) throws -} - -// See: https://github.com/signalapp/libsignal-metadata-java/blob/master/java/src/main/java/org/signal/libsignal/metadata/certificate/CertificateValidator.java -//public class CertificateValidator { -@objc public class SMKCertificateDefaultValidator: NSObject, SMKCertificateValidator { - -// @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") -// private static final Set REVOKED = new HashSet() {{ -// -// }}; - private static let kRevokedCertificateIds = Set() - -// -// private final ECPublicKey trustRoot; - private let trustRoot: ECPublicKey - -// public CertificateValidator(ECPublicKey trustRoot) { -// this.trustRoot = trustRoot; -// } - @objc public init(trustRoot: ECPublicKey ) { - self.trustRoot = trustRoot - } - -// public void validate(SenderCertificate certificate, long validationTime) throws InvalidCertificateException { - @objc public func throwswrapped_validate(senderCertificate: SMKSenderCertificate, validationTime: UInt64) throws { -// try { -// ServerCertificate serverCertificate = certificate.getSigner(); -// let serverCertificate = senderCertificate.signer - -// validate(serverCertificate); -// try throwswrapped_validate(serverCertificate: serverCertificate) - -// if (!Curve.verifySignature(serverCertificate.getKey(), certificate.getCertificate(), certificate.getSignature())) { -// throw new InvalidCertificateException("Signature failed"); -// } -// let certificateData = try senderCertificate.toProto().certificate -// guard try Ed25519.verifySignature(senderCertificate.signatureData, -// publicKey: serverCertificate.key.keyData, -// data: certificateData) else { -// Logger.error("Sender certificate signature verification failed.") -// let error = SMKCertificateError.invalidCertificate(description: "Sender certificate signature verification failed.") -// Logger.error("\(error)") -// throw error -// } - -// if (validationTime > certificate.getExpiration()) { -// throw new InvalidCertificateException("Certificate is expired"); -// } -// guard validationTime <= senderCertificate.expirationTimestamp else { -// let error = SMKCertificateError.invalidCertificate(description: "Certficate is expired.") -// Logger.error("\(error)") -// throw error -// } - -// } catch (InvalidKeyException e) { -// throw new InvalidCertificateException(e); -// } - } - -// // VisibleForTesting -// void validate(ServerCertificate certificate) throws InvalidCertificateException { - @objc public func throwswrapped_validate(serverCertificate: SMKServerCertificate) throws { -// try { -// if (!Curve.verifySignature(trustRoot, certificate.getCertificate(), certificate.getSignature())) { -// throw new InvalidCertificateException("Signature failed"); -// } - let certificateBuilder = SMKProtoServerCertificateCertificate.builder(id: serverCertificate.keyId, - key: serverCertificate.key.serialized) - let certificateData = try certificateBuilder.build().serializedData() - -// let certificateData = try serverCertificate.toProto().certificate - guard try Ed25519.verifySignature(serverCertificate.signatureData, - publicKey: trustRoot.keyData, - data: certificateData) else { - let error = SMKCertificateError.invalidCertificate(description: "Server certificate signature verification failed.") - Logger.error("\(error)") - throw error - } -// if (REVOKED.contains(certificate.getKeyId())) { -// throw new InvalidCertificateException("Server certificate has been revoked"); -// } - guard !SMKCertificateDefaultValidator.kRevokedCertificateIds.contains(serverCertificate.keyId) else { - let error = SMKCertificateError.invalidCertificate(description: "Revoked certificate.") - Logger.error("\(error)") - throw error - } -// } catch (InvalidKeyException e) { -// throw new InvalidCertificateException(e); -// } - } -} diff --git a/SessionProtocolKit/Signal/SMKError.swift b/SessionProtocolKit/Signal/SMKError.swift deleted file mode 100644 index 912eb76ea..000000000 --- a/SessionProtocolKit/Signal/SMKError.swift +++ /dev/null @@ -1,9 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -public enum SMKError: Error { - case assertionError(description: String) -} diff --git a/SessionProtocolKit/Signal/SMKSecretSessionCipher.swift b/SessionProtocolKit/Signal/SMKSecretSessionCipher.swift deleted file mode 100644 index 2d7e2813f..000000000 --- a/SessionProtocolKit/Signal/SMKSecretSessionCipher.swift +++ /dev/null @@ -1,563 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation -import HKDFKit -import SignalCoreKit - -@objc -public class SecretSessionKnownSenderError: NSObject, CustomNSError { - - @objc - public static let kSenderRecipientIdKey = "kSenderRecipientIdKey" - - @objc - public static let kSenderDeviceIdKey = "kSenderDeviceIdKey" - - public let senderRecipientId: String - public let senderDeviceId: UInt32 - public let underlyingError: Error - - init(senderRecipientId: String, senderDeviceId: UInt32, underlyingError: Error) { - self.senderRecipientId = senderRecipientId - self.senderDeviceId = senderDeviceId - self.underlyingError = underlyingError - } - - public var errorUserInfo: [String: Any] { - return [ - type(of: self).kSenderRecipientIdKey: self.senderRecipientId, - type(of: self).kSenderDeviceIdKey: self.senderDeviceId, - NSUnderlyingErrorKey: (underlyingError as NSError) - ] - } -} - -@objc -public enum SMKSecretSessionCipherError: Int, Error { - case selfSentMessage -} - -// MARK: - - -private class SMKSecretKeySpec: NSObject { - - @objc public let keyData: Data - @objc public let algorithm: String - - init(keyData: Data, algorithm: String) { - self.keyData = keyData - self.algorithm = algorithm - } -} - -// MARK: - - -private class SMKEphemeralKeys: NSObject { - - @objc public let chainKey: Data - @objc public let cipherKey: SMKSecretKeySpec - @objc public let macKey: SMKSecretKeySpec - - init(chainKey: Data, cipherKey: Data, macKey: Data) { - self.chainKey = chainKey - self.cipherKey = SMKSecretKeySpec(keyData: cipherKey, algorithm: "AES") - self.macKey = SMKSecretKeySpec(keyData: macKey, algorithm: "HmacSHA256") - } -} - -// MARK: - - -private class SMKStaticKeys: NSObject { - - @objc public let cipherKey: SMKSecretKeySpec - @objc public let macKey: SMKSecretKeySpec - - init(cipherKey: Data, macKey: Data) { - self.cipherKey = SMKSecretKeySpec(keyData: cipherKey, algorithm: "AES") - self.macKey = SMKSecretKeySpec(keyData: macKey, algorithm: "HmacSHA256") - } -} - -// MARK: - - -@objc -public class SMKDecryptResult: NSObject { - - @objc public let senderRecipientId: String - @objc public let senderDeviceId: Int - @objc public let paddedPayload: Data - @objc public let messageType: SMKMessageType - - init(senderRecipientId: String, - senderDeviceId: Int, - paddedPayload: Data, - messageType: SMKMessageType) { - self.senderRecipientId = senderRecipientId - self.senderDeviceId = senderDeviceId - self.paddedPayload = paddedPayload - self.messageType = messageType - } -} - -// MARK: - - -@objc public class SMKSecretSessionCipher: NSObject { - - private let kUDPrefixString = "UnidentifiedDelivery" - - private let kSMKSecretSessionCipherMacLength: UInt = 10 - - private let sessionResetImplementation: SessionRestorationProtocol! - private let sessionStore: SessionStore - private let preKeyStore: PreKeyStore - private let signedPreKeyStore: SignedPreKeyStore - private let identityStore: IdentityKeyStore - - @objc public init(sessionResetImplementation: SessionRestorationProtocol!, - sessionStore: SessionStore, - preKeyStore: PreKeyStore, - signedPreKeyStore: SignedPreKeyStore, - identityStore: IdentityKeyStore) throws { - self.sessionResetImplementation = sessionResetImplementation - self.sessionStore = sessionStore - self.preKeyStore = preKeyStore - self.signedPreKeyStore = signedPreKeyStore - self.identityStore = identityStore - } - - @objc public convenience init(sessionStore: SessionStore, - preKeyStore: PreKeyStore, - signedPreKeyStore: SignedPreKeyStore, - identityStore: IdentityKeyStore) throws { - try self.init(sessionResetImplementation: nil, sessionStore: sessionStore, preKeyStore: preKeyStore, signedPreKeyStore: signedPreKeyStore, identityStore: identityStore) - } - - // MARK: - Public - - @objc - public func throwswrapped_encryptMessage(recipientPublicKey: String, - deviceID: Int32, - paddedPlaintext: Data, - senderCertificate: SMKSenderCertificate, - protocolContext: Any, - useFallbackSessionCipher: Bool) throws -> Data { - guard recipientPublicKey.count > 0 else { - throw SMKError.assertionError(description: "\(SMKSecretSessionCipher.logTag) invalid recipientId") - } - - guard deviceID > 0 else { - throw SMKError.assertionError(description: "\(SMKSecretSessionCipher.logTag) invalid deviceId") - } - - guard let ourIdentityKeyPair = identityStore.identityKeyPair(protocolContext) else { - throw SMKError.assertionError(description: "\(logTag) Missing our identity key pair.") - } - - let encryptedMessage: CipherMessage - if useFallbackSessionCipher { - let cipher = FallBackSessionCipher(recipientPublicKey: recipientPublicKey, privateKey: try ourIdentityKeyPair.privateKey) - let ivAndCiphertext = cipher.encrypt(paddedPlaintext)! - encryptedMessage = FallbackMessage(_throws_with: ivAndCiphertext) - } else { - let cipher = SessionCipher(sessionStore: sessionStore, - preKeyStore: preKeyStore, - signedPreKeyStore: signedPreKeyStore, - identityKeyStore: identityStore, - recipientId: recipientPublicKey, - deviceId: deviceID) - encryptedMessage = try cipher.encryptMessage(paddedPlaintext, protocolContext: protocolContext) - } - - guard let encryptedMessageData = encryptedMessage.serialized() else { - throw SMKError.assertionError(description: "\(logTag) Could not serialize encrypted message.") - } - - guard let theirIdentityKeyData = Data.data(fromHex: recipientPublicKey.substring(from: recipientPublicKey.index(recipientPublicKey.startIndex, offsetBy: 2))) else { - throw SMKError.assertionError(description: "\(logTag) Missing their public identity key.") - } - - // NOTE: we don't use ECPublicKey(serializedKeyData) since the - // key data should not have a type byte. - let theirIdentityKey = try ECPublicKey(keyData: theirIdentityKeyData) - - let ephemeral = Curve25519.generateKeyPair() - - guard let prefixData = kUDPrefixString.data(using: String.Encoding.utf8) else { - throw SMKError.assertionError(description: "\(logTag) Could not encode prefix.") - } - - let ephemeralSalt = NSData.join([ - prefixData, - theirIdentityKey.serialized, - try ephemeral.ecPublicKey().serialized - ]) - - let ephemeralKeys = try throwswrapped_calculateEphemeralKeys(ephemeralPublicKey: theirIdentityKey, - ephemeralPrivateKey: ephemeral.ecPrivateKey(), - salt: ephemeralSalt) - - let staticKeyCipherData = try encrypt(cipherKey: ephemeralKeys.cipherKey, - macKey: ephemeralKeys.macKey, - plaintextData: ourIdentityKeyPair.ecPublicKey().serialized) - - let staticSalt = NSData.join([ - ephemeralKeys.chainKey, - staticKeyCipherData - ]) - - let staticKeys = try throwswrapped_calculateStaticKeys(staticPublicKey: theirIdentityKey, - staticPrivateKey: ourIdentityKeyPair.ecPrivateKey(), - salt: staticSalt) - - let messageType: SMKMessageType - switch encryptedMessage.cipherMessageType { - case .prekey: - messageType = .prekey - case .whisper: - messageType = .whisper - case .fallback: - messageType = .fallback - default: - throw SMKError.assertionError(description: "\(logTag) Unknown cipher message type.") - } - - let messageContent = SMKUnidentifiedSenderMessageContent(messageType: messageType, - senderCertificate: senderCertificate, - contentData: encryptedMessageData) - - let messageData = try encrypt(cipherKey: staticKeys.cipherKey, - macKey: staticKeys.macKey, - plaintextData: try messageContent.serialized()) - - let message = SMKUnidentifiedSenderMessage(ephemeralKey: try ephemeral.ecPublicKey(), - encryptedStatic: staticKeyCipherData, - encryptedMessage: messageData) - - return try message.serialized() - } - - @objc - public func throwswrapped_decryptMessage(certificateValidator: SMKCertificateValidator, - cipherTextData: Data, - timestamp: UInt64, - localRecipientId: String, - localDeviceId: Int32, - protocolContext: Any) throws -> SMKDecryptResult { - guard timestamp > 0 else { - throw SMKError.assertionError(description: "\(logTag) invalid timestamp") - } - - guard let ourIdentityKeyPair = identityStore.identityKeyPair(protocolContext) else { - throw SMKError.assertionError(description: "\(logTag) Missing our identity key pair.") - } - - let wrapper = try SMKUnidentifiedSenderMessage.parse(dataAndPrefix: cipherTextData) - - guard let prefixData = kUDPrefixString.data(using: String.Encoding.utf8) else { - throw SMKError.assertionError(description: "\(logTag) Could not encode prefix.") - } - - let ephemeralSalt = NSData.join([ - prefixData, - try ourIdentityKeyPair.ecPublicKey().serialized, - wrapper.ephemeralKey.serialized - ]) - - let ephemeralKeys = try throwswrapped_calculateEphemeralKeys(ephemeralPublicKey: wrapper.ephemeralKey, - ephemeralPrivateKey: ourIdentityKeyPair.ecPrivateKey(), - salt: ephemeralSalt) - - let staticKeyBytes = try decrypt(cipherKey: ephemeralKeys.cipherKey, - macKey: ephemeralKeys.macKey, - cipherTextWithMac: wrapper.encryptedStatic) - - let staticKey = try ECPublicKey(serializedKeyData: staticKeyBytes) - - let staticSalt = NSData.join([ - ephemeralKeys.chainKey, - wrapper.encryptedStatic - ]) - - let staticKeys = try throwswrapped_calculateStaticKeys(staticPublicKey: staticKey, - staticPrivateKey: ourIdentityKeyPair.ecPrivateKey(), - salt: staticSalt) - - let messageBytes = try decrypt(cipherKey: staticKeys.cipherKey, - macKey: staticKeys.macKey, - cipherTextWithMac: wrapper.encryptedMessage) - - let messageContent = try SMKUnidentifiedSenderMessageContent.parse(data: messageBytes) - - let senderRecipientId = messageContent.senderCertificate.senderRecipientId - let senderDeviceId = messageContent.senderCertificate.senderDeviceId - - guard senderRecipientId != localRecipientId || senderDeviceId != localDeviceId else { - Logger.info("Discarding self-sent message") - throw SMKSecretSessionCipherError.selfSentMessage - } - - // validator.validate(content.getSenderCertificate(), timestamp); - - let wrapAsKnownSenderError = { (underlyingError: Error) in - return SecretSessionKnownSenderError(senderRecipientId: senderRecipientId, senderDeviceId: senderDeviceId, underlyingError: underlyingError) - } - - do { - try certificateValidator.throwswrapped_validate(senderCertificate: messageContent.senderCertificate, - validationTime: timestamp) - } catch { - throw wrapAsKnownSenderError(error) - } - -// if (!MessageDigest.isEqual(content.getSenderCertificate().getKey().serialize(), staticKeyBytes)) { -// throw new InvalidKeyException("Sender's certificate key does not match key used in message"); -// } - -// // NOTE: Constant time comparison. -// guard messageContent.senderCertificate.key.serialized.ows_constantTimeIsEqual(to: staticKeyBytes) else { -// let underlyingError = SMKError.assertionError(description: "\(logTag) Sender's certificate key does not match key used in message.") -// throw wrapAsKnownSenderError(underlyingError) -// } - - let paddedMessagePlaintext: Data - do { - paddedMessagePlaintext = try throwswrapped_decrypt(messageContent: messageContent, protocolContext: protocolContext) - } catch { - throw wrapAsKnownSenderError(error) - } - - // NOTE: We use the sender properties from the sender certificate, not from this class' properties. - guard senderDeviceId >= 0 && senderDeviceId <= INT_MAX else { - let underlyingError = SMKError.assertionError(description: "\(logTag) Invalid senderDeviceId.") - throw wrapAsKnownSenderError(underlyingError) - } - - return SMKDecryptResult(senderRecipientId: senderRecipientId, - senderDeviceId: Int(senderDeviceId), - paddedPayload: paddedMessagePlaintext, - messageType: messageContent.messageType) - } - - // MARK: - Encrypt - - // private EphemeralKeys calculateEphemeralKeys(ECPublicKey ephemeralPublic, ECPrivateKey ephemeralPrivate, byte[] salt) - // throws InvalidKeyException { - private func throwswrapped_calculateEphemeralKeys(ephemeralPublicKey: ECPublicKey, - ephemeralPrivateKey: ECPrivateKey, - salt: Data) throws -> SMKEphemeralKeys { - guard ephemeralPublicKey.keyData.count > 0 else { - throw SMKError.assertionError(description: "\(logTag) invalid ephemeralPublicKey") - } - - guard ephemeralPrivateKey.keyData.count > 0 else { - throw SMKError.assertionError(description: "\(logTag) invalid ephemeralPrivateKey") - } - - guard salt.count > 0 else { - throw SMKError.assertionError(description: "\(logTag) invalid salt") - } - - // byte[] ephemeralSecret = Curve.calculateAgreement(ephemeralPublic, ephemeralPrivate); - // - // See: - // https://github.com/signalapp/libsignal-protocol-java/blob/master/java/src/main/java/org/whispersystems/libsignal/ecc/Curve.java#L30 - let ephemeralSecret = try Curve25519.generateSharedSecret(fromPublicKey: ephemeralPublicKey.keyData, privateKey: ephemeralPrivateKey.keyData) - - // byte[] ephemeralDerived = new HKDFv3().deriveSecrets(ephemeralSecret, salt, new byte[0], 96); - let kEphemeralDerivedLength: UInt = 96 - let ephemeralDerived: Data = - try HKDFKit.deriveKey(ephemeralSecret, info: Data(), salt: salt, outputSize: Int32(kEphemeralDerivedLength)) - guard ephemeralDerived.count == kEphemeralDerivedLength else { - throw SMKError.assertionError(description: "\(logTag) derived ephemeral has unexpected length: \(ephemeralDerived.count).") - } - - let ephemeralDerivedParser = OWSDataParser(data: ephemeralDerived) - let chainKey = try ephemeralDerivedParser.nextData(length: 32, name: "chain key") - let cipherKey = try ephemeralDerivedParser.nextData(length: 32, name: "cipher key") - let macKey = try ephemeralDerivedParser.nextData(length: 32, name: "mac key") - guard ephemeralDerivedParser.isEmpty else { - throw SMKError.assertionError(description: "\(logTag) could not parse derived ephemeral.") - } - - return SMKEphemeralKeys(chainKey: chainKey, cipherKey: cipherKey, macKey: macKey) - } - - // private StaticKeys calculateStaticKeys(ECPublicKey staticPublic, ECPrivateKey staticPrivate, byte[] salt) throws - // InvalidKeyException { - private func throwswrapped_calculateStaticKeys(staticPublicKey: ECPublicKey, - staticPrivateKey: ECPrivateKey, - salt: Data) throws -> SMKStaticKeys { - guard staticPublicKey.keyData.count > 0 else { - throw SMKError.assertionError(description: "\(logTag) invalid staticPublicKey") - } - guard staticPrivateKey.keyData.count > 0 else { - throw SMKError.assertionError(description: "\(logTag) invalid staticPrivateKey") - } - guard salt.count > 0 else { - throw SMKError.assertionError(description: "\(logTag) invalid salt") - } - - // byte[] staticSecret = Curve.calculateAgreement(staticPublic, staticPrivate); - // - // See: - // https://github.com/signalapp/libsignal-protocol-java/blob/master/java/src/main/java/org/whispersystems/libsignal/ecc/Curve.java#L30 - let staticSecret = try Curve25519.generateSharedSecret(fromPublicKey: staticPublicKey.keyData, privateKey: staticPrivateKey.keyData) - - // byte[] staticDerived = new HKDFv3().deriveSecrets(staticSecret, salt, new byte[0], 96); - let kStaticDerivedLength: UInt = 96 - let staticDerived: Data = - HKDFKit.deriveKey(staticSecret, info: Data(), salt: salt, outputSize: Int32(kStaticDerivedLength)) - guard staticDerived.count == kStaticDerivedLength else { - throw SMKError.assertionError(description: "\(logTag) could not derive static.") - } - - // byte[][] staticDerivedParts = ByteUtil.split(staticDerived, 32, 32, 32); - let staticDerivedParser = OWSDataParser(data: staticDerived) - _ = try staticDerivedParser.nextData(length: 32) - let cipherKey = try staticDerivedParser.nextData(length: 32) - let macKey = try staticDerivedParser.nextData(length: 32) - guard staticDerivedParser.isEmpty else { - throw SMKError.assertionError(description: "\(logTag) invalid derived static.") - } - - // return new StaticKeys(staticDerivedParts[1], staticDerivedParts[2]); - return SMKStaticKeys(cipherKey: cipherKey, macKey: macKey) - } - - // private byte[] encrypt(SecretKeySpec cipherKey, SecretKeySpec macKey, byte[] plaintext) { - private func encrypt(cipherKey: SMKSecretKeySpec, - macKey: SMKSecretKeySpec, - plaintextData: Data) throws -> Data { - - // Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); - // cipher.init(Cipher.ENCRYPT_MODE, cipherKey, new IvParameterSpec(new byte[16])); - // byte[] ciphertext = cipher.doFinal(plaintext); - guard let aesKey = OWSAES256Key(data: cipherKey.keyData) else { - throw SMKError.assertionError(description: "\(logTag) Invalid encryption key.") - } - - // NOTE: The IV is all zeroes. This is fine since we're using a unique key. - let initializationVector = Data(count: Int(kAES256CTR_IVLength)) - - guard let encryptionResult = Cryptography.encryptAESCTR(plaintextData: plaintextData, initializationVector: initializationVector, key: aesKey) else { - throw SMKError.assertionError(description: "\(logTag) Could not encrypt data.") - } - let cipherText = encryptionResult.ciphertext - - // Mac mac = Mac.getInstance("HmacSHA256"); - // mac.init(macKey); - // - // byte[] ourFullMac = mac.doFinal(ciphertext); - // byte[] ourMac = ByteUtil.trim(ourFullMac, 10); - guard let ourMac = Cryptography.truncatedSHA256HMAC(cipherText, withHMACKey: macKey.keyData, truncation: 10) else { - throw SMKError.assertionError(description: "\(logTag) Could not compute HmacSHA256.") - } - - // return ByteUtil.combine(ciphertext, ourMac); - let result = NSData.join([ - cipherText, - ourMac - ]) - - return result - } - - // MARK: - Decrypt - - private func throwswrapped_decrypt(messageContent: SMKUnidentifiedSenderMessageContent, - protocolContext: Any) throws -> Data { - // NOTE: We use the sender properties from the sender certificate, not from this class' properties. - let senderRecipientId = messageContent.senderCertificate.senderRecipientId - let senderDeviceId = messageContent.senderCertificate.senderDeviceId - guard senderDeviceId >= 0 && senderDeviceId <= INT32_MAX else { - throw SMKError.assertionError(description: "\(logTag) Invalid senderDeviceId.") - } - - let cipherMessage: CipherMessage - switch (messageContent.messageType) { - case .whisper: - cipherMessage = try WhisperMessage(data: messageContent.contentData) - case .prekey: - cipherMessage = try PreKeyWhisperMessage(data: messageContent.contentData) - case .fallback: - let privateKey = try? identityStore.identityKeyPair(protocolContext)?.privateKey - let cipher = FallBackSessionCipher(recipientPublicKey: senderRecipientId, privateKey: privateKey) - let plaintext = cipher.decrypt(messageContent.contentData)! - return plaintext - } - - let cipher = LokiSessionCipher(sessionResetImplementation: sessionResetImplementation, - sessionStore: sessionStore, - preKeyStore: preKeyStore, - signedPreKeyStore: signedPreKeyStore, - identityKeyStore: identityStore, - recipientID: senderRecipientId, - deviceID: Int32(senderDeviceId)) - - let plaintextData = try cipher.decrypt(cipherMessage, protocolContext: protocolContext) - return plaintextData - } - - // private byte[] decrypt(SecretKeySpec cipherKey, SecretKeySpec macKey, byte[] ciphertext) throws InvalidMacException { - private func decrypt(cipherKey: SMKSecretKeySpec, - macKey: SMKSecretKeySpec, - cipherTextWithMac: Data) throws -> Data { - - // if (ciphertext.count < 10) { - // throw new InvalidMacException("Ciphertext not long enough for MAC!"); - // } - if (cipherTextWithMac.count < kSMKSecretSessionCipherMacLength) { - throw SMKError.assertionError(description: "\(logTag) Cipher text not long enough for MAC.") - } - - // byte[][] ciphertextParts = ByteUtil.split(ciphertext, ciphertext.count - 10, 10); - let cipherTextWithMacParser = OWSDataParser(data: cipherTextWithMac) - let cipherTextLength = UInt(cipherTextWithMac.count) - kSMKSecretSessionCipherMacLength - let cipherText = try cipherTextWithMacParser.nextData(length: cipherTextLength, name: "cipher text") - let theirMac = try cipherTextWithMacParser.nextData(length: kSMKSecretSessionCipherMacLength, name: "their mac") - guard cipherTextWithMacParser.isEmpty else { - throw SMKError.assertionError(description: "\(logTag) Could not parse cipher text.") - } - - // Mac mac = Mac.getInstance("HmacSHA256"); - // mac.init(macKey); - // - // byte[] digest = mac.doFinal(ciphertextParts[0]); - guard let ourFullMac = Cryptography.computeSHA256HMAC(cipherText, withHMACKey: macKey.keyData) else { - throw SMKError.assertionError(description: "\(logTag) Could not compute HmacSHA256.") - } - - // byte[] ourMac = ByteUtil.trim(digest, 10); - guard ourFullMac.count >= kSMKSecretSessionCipherMacLength else { - throw SMKError.assertionError(description: "\(logTag) HmacSHA256 has unexpected length.") - } - - let ourMac = ourFullMac[0.. SMKSenderCertificate { - let proto = try SMKProtoSenderCertificate.parseData(data) - return try parse(proto: proto) - } - - @objc public class func parse(proto: SMKProtoSenderCertificate) throws -> SMKSenderCertificate { - - let sender = proto.sender - let senderDevice = proto.senderDevice - - return SMKSenderCertificate(senderDeviceId: senderDevice, senderRecipientId: sender) - } - - @objc public func toProto() throws -> SMKProtoSenderCertificate { - let builder = - SMKProtoSenderCertificate.builder(sender: senderRecipientId, senderDevice: senderDeviceId) - return try builder.build() - } - - @objc public func serialized() throws -> Data { - return try toProto().serializedData() - } - - open override func isEqual(_ other: Any?) -> Bool { - if let other = other as? SMKSenderCertificate { - return (senderDeviceId == other.senderDeviceId && senderRecipientId == other.senderRecipientId) - } else { - return false - } - } - - public override var hash: Int { - return senderDeviceId.hashValue ^ senderRecipientId.hashValue - } -} diff --git a/SessionProtocolKit/Signal/SMKServerCertificate.swift b/SessionProtocolKit/Signal/SMKServerCertificate.swift deleted file mode 100644 index 0a01878d5..000000000 --- a/SessionProtocolKit/Signal/SMKServerCertificate.swift +++ /dev/null @@ -1,64 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -// See: -// https://github.com/signalapp/libsignal-metadata-java/blob/cac0dde9de416a192e64a8940503982820870090/java/src/main/java/org/signal/libsignal/metadata/certificate/ServerCertificate.java -@objc public class SMKServerCertificate: NSObject { - - @objc public let keyId: UInt32 - @objc public let key: ECPublicKey - @objc public let signatureData: Data - - public init(keyId: UInt32, - key: ECPublicKey, - signatureData: Data) { - self.keyId = keyId - self.key = key - self.signatureData = signatureData - } - - @objc public class func parse(data: Data) throws -> SMKServerCertificate { - let proto = try SMKProtoServerCertificate.parseData(data) - return try parse(proto: proto) - } - - @objc public class func parse(proto: SMKProtoServerCertificate) throws -> SMKServerCertificate { - let signatureData = proto.signature - let certificateData = proto.certificate - let certificateProto = try SMKProtoServerCertificateCertificate.parseData(certificateData) - let keyId = certificateProto.id - let keyData = certificateProto.key - let key = try ECPublicKey(serializedKeyData: keyData) - return SMKServerCertificate(keyId: keyId, key: key, signatureData: signatureData) - } - - @objc public func toProto() throws -> SMKProtoServerCertificate { - let certificateBuilder = SMKProtoServerCertificateCertificate.builder(id: keyId, key: key.serialized) - - let builder = - SMKProtoServerCertificate.builder(certificate: try certificateBuilder.buildSerializedData(), - signature: signatureData) - return try builder.build() - } - - @objc public func serialized() throws -> Data { - return try toProto().serializedData() - } - - open override func isEqual(_ other: Any?) -> Bool { - if let other = other as? SMKServerCertificate { - return (keyId == other.keyId && - key.isEqual(other.key) && - (signatureData == other.signatureData)) - } else { - return false - } - } - - public override var hash: Int { - return keyId.hashValue ^ key.hashValue ^ signatureData.hashValue - } -} diff --git a/SessionProtocolKit/Signal/SMKUDAccessKey.swift b/SessionProtocolKit/Signal/SMKUDAccessKey.swift deleted file mode 100644 index 70ec3b9c3..000000000 --- a/SessionProtocolKit/Signal/SMKUDAccessKey.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation -import SignalCoreKit - -@objc -public class SMKUDAccessKey: NSObject { - - @objc - public static let kUDAccessKeyLength: Int = 16 - - @objc - public let keyData: Data - - @objc - public init(profileKey: Data) throws { - guard let aesGcmKey = OWSAES256Key(data: profileKey) else { - throw SMKError.assertionError(description: "Profile key is not valid AES GCM key.") - } - - // We derive the "ud access key" from the private key by encrypting zeroes. - let emptyPlaintextLength = 16 - let emptyPlaintext = Data(count: Int(emptyPlaintextLength)) - let initializationVector = Data(count: Int(kAESGCM256_DefaultIVLength)) - guard let keyData = Cryptography.encryptAESGCM(plainTextData: emptyPlaintext, - initializationVector: initializationVector, - additionalAuthenticatedData: nil, - key: aesGcmKey) else { - throw SMKError.assertionError(description: "Could not derive UD access key from profile key.") - } - guard keyData.ciphertext.count == SMKUDAccessKey.kUDAccessKeyLength else { - throw SMKError.assertionError(description: "\(SMKUDAccessKey.logTag) key has invalid length") - } - - self.keyData = keyData.ciphertext - } - - @objc - public init(randomKeyData: ()) { - self.keyData = Randomness.generateRandomBytes(Int32(SMKUDAccessKey.kUDAccessKeyLength)) - } - - // MARK: - - override public func isEqual(_ object: Any?) -> Bool { - guard let other = object as? SMKUDAccessKey else { return false } - return self.keyData == other.keyData - } -} diff --git a/SessionProtocolKit/Signal/SMKUnidentifiedSenderMessage.swift b/SessionProtocolKit/Signal/SMKUnidentifiedSenderMessage.swift deleted file mode 100644 index d536d7d60..000000000 --- a/SessionProtocolKit/Signal/SMKUnidentifiedSenderMessage.swift +++ /dev/null @@ -1,95 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation -import SignalCoreKit - -// https://github.com/signalapp/libsignal-metadata-java/blob/master/java/src/main/java/org/signal/libsignal/metadata/protocol/UnidentifiedSenderMessage.java -@objc public class SMKUnidentifiedSenderMessage: NSObject { - - @objc public static let kSMKMessageCipherTextVersion: UInt = 1 - - public let cipherTextVersion: UInt - public let ephemeralKey: ECPublicKey - public let encryptedStatic: Data - public let encryptedMessage: Data - - public init(cipherTextVersion: UInt, - ephemeralKey: ECPublicKey, - encryptedStatic: Data, - encryptedMessage: Data) { - self.cipherTextVersion = cipherTextVersion - self.ephemeralKey = ephemeralKey - self.encryptedStatic = encryptedStatic - self.encryptedMessage = encryptedMessage - } - - public init(ephemeralKey: ECPublicKey, - encryptedStatic: Data, - encryptedMessage: Data) { - self.cipherTextVersion = SMKUnidentifiedSenderMessage.kSMKMessageCipherTextVersion - self.ephemeralKey = ephemeralKey - self.encryptedStatic = encryptedStatic - self.encryptedMessage = encryptedMessage - } - - @objc public class func parse(dataAndPrefix: Data) throws -> SMKUnidentifiedSenderMessage { - // public UnidentifiedSenderMessage(byte[] serialized) - // throws InvalidMetadataMessageException, InvalidMetadataVersionException - - let parser = OWSDataParser(data: dataAndPrefix) - - // this.version = ByteUtil.highBitsToInt(serialized[0]); - let versionByte = try parser.nextByte(name: "version byte") - let cipherTextVersion = UInt(SerializationUtilities.highBitsToInt(fromByte: versionByte)) - - // if (version > CIPHERTEXT_VERSION) { - // throw new InvalidMetadataVersionException("Unknown version: " + this.version); - // } - guard cipherTextVersion <= SMKUnidentifiedSenderMessage.kSMKMessageCipherTextVersion else { - throw SMKError.assertionError(description: "\(logTag) unknown cipher text version: \(cipherTextVersion)") - } - - // SignalProtos.UnidentifiedSenderMessage unidentifiedSenderMessage = - // SignalProtos.UnidentifiedSenderMessage.parseFrom(ByteString.copyFrom(serialized, 1, serialized.length - 1)); - let protoData = try parser.remainder(name: "proto data") - let proto = try SMKProtoUnidentifiedSenderMessage.parseData(protoData) - - // if (!unidentifiedSenderMessage.hasEphemeralPublic() || - // !unidentifiedSenderMessage.hasEncryptedStatic() || - // !unidentifiedSenderMessage.hasEncryptedMessage()) - // { - // throw new InvalidMetadataMessageException("Missing fields"); - // } - // NOTE: These fields are required in the proto schema. - - // this.ephemeral = Curve.decodePoint(unidentifiedSenderMessage.getEphemeralPublic().toByteArray(), 0); - let ephemeralKeyData = proto.ephemeralPublic - let ephemeralKey = try ECPublicKey(serializedKeyData: ephemeralKeyData) - - // this.encryptedStatic = unidentifiedSenderMessage.getEncryptedStatic().toByteArray(); - let encryptedStatic = proto.encryptedStatic - - // this.encryptedMessage = unidentifiedSenderMessage.getEncryptedMessage().toByteArray(); - let encryptedMessage = proto.encryptedMessage - - return SMKUnidentifiedSenderMessage(cipherTextVersion: cipherTextVersion, ephemeralKey: ephemeralKey, encryptedStatic: encryptedStatic, encryptedMessage: encryptedMessage) - } - - @objc public func toProto() throws -> SMKProtoUnidentifiedSenderMessage { - let builder = SMKProtoUnidentifiedSenderMessage.builder(ephemeralPublic: ephemeralKey.serialized, - encryptedStatic: encryptedStatic, - encryptedMessage: encryptedMessage) - return try builder.build() - } - - @objc public func serialized() throws -> Data { - let versionByte: UInt8 = UInt8((self.cipherTextVersion << 4 | self.cipherTextVersion) & 0xFF) - let versionBytes = [versionByte] - let versionData = Data(bytes: versionBytes) - let messageData = try toProto().serializedData() - - return NSData.join([versionData, messageData]) - } -} diff --git a/SessionProtocolKit/Signal/SMKUnidentifiedSenderMessageContent.swift b/SessionProtocolKit/Signal/SMKUnidentifiedSenderMessageContent.swift deleted file mode 100644 index 68116bafe..000000000 --- a/SessionProtocolKit/Signal/SMKUnidentifiedSenderMessageContent.swift +++ /dev/null @@ -1,71 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation - -@objc public enum SMKMessageType: Int { - case whisper - case prekey - case fallback -} - -// See: -// https://github.com/signalapp/libsignal-metadata-java/blob/0cbbbf23eaf9f46fdf2d9463f3dfab2fb3271292/java/src/main/java/org/signal/libsignal/metadata/protocol/UnidentifiedSenderMessageContent.java -@objc public class SMKUnidentifiedSenderMessageContent: NSObject { - - @objc public let messageType: SMKMessageType - @objc public let senderCertificate: SMKSenderCertificate - @objc public let contentData: Data - - @objc public init(messageType: SMKMessageType, - senderCertificate: SMKSenderCertificate, - contentData: Data) { - self.messageType = messageType - self.senderCertificate = senderCertificate - self.contentData = contentData - } - - @objc public class func parse(data: Data) throws -> SMKUnidentifiedSenderMessageContent { - - let proto = try SMKProtoUnidentifiedSenderMessageMessage.parseData(data) - - // TODO: Should we have a default case in our switches? Probably. - var messageType: SMKMessageType - switch (proto.type) { - case .prekeyMessage: - messageType = .prekey - case .message: - messageType = .whisper - case .fallbackMessage: - messageType = .fallback - } - - let contentData = proto.content - let senderCertificateProto = proto.senderCertificate - let senderCertificate = try SMKSenderCertificate.parse(proto: senderCertificateProto) - - return SMKUnidentifiedSenderMessageContent(messageType: messageType, senderCertificate: senderCertificate, contentData: contentData) - } - - @objc public func toProto() throws -> SMKProtoUnidentifiedSenderMessageMessage { - let builderType: SMKProtoUnidentifiedSenderMessageMessage.SMKProtoUnidentifiedSenderMessageMessageType - switch messageType { - case .whisper: - builderType = .message - case .prekey: - builderType = .prekeyMessage - case .fallback: - builderType = .fallbackMessage - } - - let builder = SMKProtoUnidentifiedSenderMessageMessage.builder(type: builderType, - senderCertificate: try senderCertificate.toProto(), - content: contentData) - return try builder.build() - } - - @objc public func serialized() throws -> Data { - return try toProto().serializedData() - } -} diff --git a/SessionProtocolKit/Signal/SessionCipher.h b/SessionProtocolKit/Signal/SessionCipher.h deleted file mode 100644 index 80e330969..000000000 --- a/SessionProtocolKit/Signal/SessionCipher.h +++ /dev/null @@ -1,44 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "AxolotlStore.h" -#import "IdentityKeyStore.h" -#import "PreKeyStore.h" -#import "PreKeyWhisperMessage.h" -#import "SessionState.h" -#import "SessionStore.h" -#import "SignedPreKeyStore.h" -#import "WhisperMessage.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface SessionCipher : NSObject - -- (instancetype)initWithAxolotlStore:(id)sessionStore recipientId:(NSString*)recipientId deviceId:(int)deviceId; - -- (instancetype)initWithSessionStore:(id)sessionStore preKeyStore:(id)preKeyStore signedPreKeyStore:(id)signedPreKeyStore identityKeyStore:(id)identityKeyStore recipientId:(NSString*)recipientId deviceId:(int)deviceId; - -// protocolContext is an optional parameter that can be used to ensure that all -// identity and session store writes are coordinated and/or occur within a single -// transaction. -- (id)throws_encryptMessage:(NSData *)paddedMessage - protocolContext:(nullable id)protocolContext NS_SWIFT_UNAVAILABLE("throws objc exceptions"); -- (nullable id)encryptMessage:(NSData *)paddedMessage - protocolContext:(nullable id)protocolContext - error:(NSError **)outError; - -- (NSData *)throws_decrypt:(id)whisperMessage - protocolContext:(nullable id)protocolContext NS_SWIFT_UNAVAILABLE("throws objc exceptions"); -- (nullable NSData *)decrypt:(id)whisperMessage - protocolContext:(nullable id)protocolContext - error:(NSError **)outError; - -- (int)throws_remoteRegistrationId:(nullable id)protocolContext NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -- (int)throws_sessionVersion:(nullable id)protocolContext NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/SessionCipher.m b/SessionProtocolKit/Signal/SessionCipher.m deleted file mode 100644 index ed5adef81..000000000 --- a/SessionProtocolKit/Signal/SessionCipher.m +++ /dev/null @@ -1,528 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "SessionCipher.h" -#import "AES-CBC.h" -#import "AxolotlExceptions.h" -#import "AxolotlParameters.h" -#import "ChainKey.h" -#import "MessageKeys.h" -#import "NSData+keyVersionByte.h" -#import "PreKeyStore.h" -#import "RootKey.h" -#import "SessionBuilder.h" -#import "SessionState.h" -#import "SessionStore.h" -#import "SignedPreKeyStore.h" -#import "WhisperMessage.h" -#import -#import -#import -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface SessionCipher () - -@property (nonatomic, readonly) NSString *recipientId; -@property (nonatomic, readonly) int deviceId; - -@property (nonatomic, readonly) id identityKeyStore; -@property (nonatomic, readonly) id sessionStore; -@property (nonatomic, readonly) SessionBuilder *sessionBuilder; -@property (nonatomic, readonly) id prekeyStore; - -@end - -#pragma mark - - -@implementation SessionCipher - -- (instancetype)initWithAxolotlStore:(id)sessionStore recipientId:(NSString*)recipientId deviceId:(int)deviceId{ - OWSAssert(sessionStore); - OWSAssert(recipientId); - return [self initWithSessionStore:sessionStore - preKeyStore:sessionStore - signedPreKeyStore:sessionStore - identityKeyStore:sessionStore - recipientId:recipientId - deviceId:deviceId]; -} - -- (instancetype)initWithSessionStore:(id)sessionStore - preKeyStore:(id)preKeyStore - signedPreKeyStore:(id)signedPreKeyStore - identityKeyStore:(id)identityKeyStore - recipientId:(NSString*)recipientId - deviceId:(int)deviceId{ - OWSAssert(sessionStore); - OWSAssert(preKeyStore); - OWSAssert(signedPreKeyStore); - OWSAssert(identityKeyStore); - OWSAssert(recipientId); - - self = [super init]; - - if (self){ - _recipientId = recipientId; - _deviceId = deviceId; - _sessionStore = sessionStore; - _identityKeyStore = identityKeyStore; - _prekeyStore = preKeyStore; - _sessionBuilder = [[SessionBuilder alloc] initWithSessionStore:sessionStore - preKeyStore:preKeyStore - signedPreKeyStore:signedPreKeyStore - identityKeyStore:identityKeyStore - recipientId:recipientId - deviceId:deviceId]; - } - - return self; -} - -- (nullable id)encryptMessage:(NSData *)paddedMessage - protocolContext:(nullable id)protocolContext - error:(NSError **)outError -{ - __block id result; - [SCKExceptionWrapper - tryBlock:^{ - result = [self throws_encryptMessage:paddedMessage protocolContext:protocolContext]; - } - error:outError]; - - return result; -} - -- (id)throws_encryptMessage:(NSData *)paddedMessage protocolContext:(nullable id)protocolContext -{ - OWSAssert(paddedMessage); - - SessionRecord *sessionRecord = - [self.sessionStore loadSession:self.recipientId deviceId:self.deviceId protocolContext:protocolContext]; - SessionState *sessionState = sessionRecord.sessionState; - ChainKey *chainKey = sessionState.senderChainKey; - MessageKeys *messageKeys = [chainKey throws_messageKeys]; - NSData *senderRatchetKey = sessionState.senderRatchetKey; - int previousCounter = sessionState.previousCounter; - int sessionVersion = sessionState.version; - - if (![self.identityKeyStore isTrustedIdentityKey:sessionState.remoteIdentityKey - recipientId:self.recipientId - direction:TSMessageDirectionOutgoing - protocolContext:protocolContext]) { - DDLogWarn( - @"%@ Previously known identity key for while encrypting for recipient: %@", self.tag, self.recipientId); - @throw [NSException exceptionWithName:UntrustedIdentityKeyException - reason:@"There is a previously known identity key." - userInfo:@{}]; - } - - [self.identityKeyStore saveRemoteIdentity:sessionState.remoteIdentityKey - recipientId:self.recipientId - protocolContext:protocolContext]; - - NSData *ciphertextBody = - [AES_CBC throws_encryptCBCMode:paddedMessage withKey:messageKeys.cipherKey withIV:messageKeys.iv]; - - id cipherMessage = - [[WhisperMessage alloc] init_throws_withVersion:sessionVersion - macKey:messageKeys.macKey - senderRatchetKey:senderRatchetKey.prependKeyType - counter:chainKey.index - previousCounter:previousCounter - cipherText:ciphertextBody - senderIdentityKey:sessionState.localIdentityKey.prependKeyType - receiverIdentityKey:sessionState.remoteIdentityKey.prependKeyType]; - - if ([sessionState hasUnacknowledgedPreKeyMessage]) { - PendingPreKey *items = [sessionState unacknowledgedPreKeyMessageItems]; - int localRegistrationId = [sessionState localRegistrationId]; - - DDLogInfo(@"Building PreKeyWhisperMessage for: %@ with preKeyId: %d", self.recipientId, items.preKeyId); - - cipherMessage = - [[PreKeyWhisperMessage alloc] init_throws_withWhisperMessage:cipherMessage - registrationId:localRegistrationId - prekeyId:items.preKeyId - signedPrekeyId:items.signedPreKeyId - baseKey:items.baseKey.prependKeyType - identityKey:sessionState.localIdentityKey.prependKeyType]; - } - - [sessionState setSenderChainKey:[chainKey nextChainKey]]; - [self.sessionStore storeSession:self.recipientId - deviceId:self.deviceId - session:sessionRecord - protocolContext:protocolContext]; - - return cipherMessage; -} - -- (nullable NSData *)decrypt:(id)whisperMessage - protocolContext:(nullable id)protocolContext - error:(NSError **)outError -{ - __block NSData *_Nullable result; - [SCKExceptionWrapper - tryBlock:^{ - result = [self throws_decrypt:whisperMessage protocolContext:protocolContext]; - } - error:outError]; - - return result; -} - -- (NSData *)throws_decrypt:(id)whisperMessage protocolContext:(nullable id)protocolContext -{ - OWSAssert(whisperMessage); - - switch (whisperMessage.cipherMessageType) { - case CipherMessageType_Whisper: - if (![whisperMessage isKindOfClass:[WhisperMessage class]]) { - OWSFail(@"Unexpected message type: %@", [whisperMessage class]); - return nil; - } - return [self throws_decryptWhisperMessage:(WhisperMessage *)whisperMessage protocolContext:protocolContext]; - case CipherMessageType_Prekey: - if (![whisperMessage isKindOfClass:[PreKeyWhisperMessage class]]) { - OWSFail(@"Unexpected message type: %@", [whisperMessage class]); - return nil; - } - return [self throws_decryptPreKeyWhisperMessage:(PreKeyWhisperMessage *)whisperMessage - protocolContext:protocolContext]; - default: - OWSFailDebug(@"Unexpected message type: %@", [whisperMessage class]); - return [NSData new]; - } -} - -- (NSData *)throws_decryptPreKeyWhisperMessage:(PreKeyWhisperMessage *)preKeyWhisperMessage - protocolContext:(nullable id)protocolContext -{ - OWSAssert(preKeyWhisperMessage); - - SessionRecord *sessionRecord = - [self.sessionStore loadSession:self.recipientId deviceId:self.deviceId protocolContext:protocolContext]; - int unsignedPreKeyId = [self.sessionBuilder throws_processPrekeyWhisperMessage:preKeyWhisperMessage - withSession:sessionRecord - protocolContext:protocolContext]; - NSData *plaintext = [self throws_decryptWithSessionRecord:sessionRecord - whisperMessage:preKeyWhisperMessage.message - protocolContext:protocolContext]; - - [self.sessionStore storeSession:self.recipientId - deviceId:self.deviceId - session:sessionRecord - protocolContext:protocolContext]; - - // If there was an unsigned PreKey - if (unsignedPreKeyId >= 0) { - [self.prekeyStore removePreKey:unsignedPreKeyId protocolContext:protocolContext]; - } - - return plaintext; -} - -- (NSData *)throws_decryptWhisperMessage:(WhisperMessage *)whisperMessage protocolContext:(nullable id)protocolContext -{ - OWSAssert(whisperMessage); - - SessionRecord *sessionRecord = - [self.sessionStore loadSession:self.recipientId deviceId:self.deviceId protocolContext:protocolContext]; - NSData *plaintext = [self throws_decryptWithSessionRecord:sessionRecord - whisperMessage:whisperMessage - protocolContext:protocolContext]; - - if (![self.identityKeyStore isTrustedIdentityKey:sessionRecord.sessionState.remoteIdentityKey - recipientId:self.recipientId - direction:TSMessageDirectionIncoming - protocolContext:protocolContext]) { - DDLogWarn( - @"%@ Previously known identity key for while decrypting from recipient: %@", self.tag, self.recipientId); - @throw [NSException exceptionWithName:UntrustedIdentityKeyException - reason:@"There is a previously known identity key." - userInfo:@{}]; - } - - [self.identityKeyStore saveRemoteIdentity:sessionRecord.sessionState.remoteIdentityKey - recipientId:self.recipientId - protocolContext:protocolContext]; - [self.sessionStore storeSession:self.recipientId - deviceId:self.deviceId - session:sessionRecord - protocolContext:protocolContext]; - - return plaintext; -} - -- (NSData *)throws_decryptWithSessionRecord:(SessionRecord *)sessionRecord - whisperMessage:(WhisperMessage *)whisperMessage - protocolContext:(nullable id)protocolContext -{ - OWSAssert(sessionRecord); - OWSAssert(whisperMessage); - - SessionState *sessionState = [sessionRecord sessionState]; - NSMutableArray *exceptions = [NSMutableArray array]; - - @try { - NSData *decryptedData = [self throws_decryptWithSessionState:sessionState - whisperMessage:whisperMessage - protocolContext:protocolContext]; - DDLogDebug(@"%@ successfully decrypted with current session state: %@", self.tag, sessionState); - return decryptedData; - } - @catch (NSException *exception) { - if ([exception.name isEqualToString:InvalidMessageException]) { - [exceptions addObject:exception]; - } else { - @throw exception; - } - } - - // If we can decrypt the message with an "old" session state, that means the sender is using an "old" session. - // In which case, we promote that session to "active" so as to converge on a single session for sending/receiving. - __block NSUInteger stateToPromoteIdx; - __block NSData *decryptedData; - [[sessionRecord previousSessionStates] - enumerateObjectsUsingBlock:^(SessionState *_Nonnull previousState, NSUInteger idx, BOOL *_Nonnull stop) { - @try { - decryptedData = [self throws_decryptWithSessionState:previousState - whisperMessage:whisperMessage - protocolContext:protocolContext]; - DDLogInfo(@"%@ successfully decrypted with PREVIOUS session state: %@", self.tag, previousState); - OWSAssert(decryptedData != nil); - stateToPromoteIdx = idx; - *stop = YES; - } @catch (NSException *exception) { - [exceptions addObject:exception]; - } - }]; - - if (decryptedData) { - SessionState *sessionStateToPromote = [sessionRecord previousSessionStates][stateToPromoteIdx]; - OWSAssert(sessionStateToPromote != nil); - DDLogInfo(@"%@ promoting session: %@", self.tag, sessionStateToPromote); - [[sessionRecord previousSessionStates] removeObjectAtIndex:stateToPromoteIdx]; - [sessionRecord promoteState:sessionStateToPromote]; - - return decryptedData; - } - - BOOL containsActiveSession = - [self.sessionStore containsSession:self.recipientId deviceId:self.deviceId protocolContext:protocolContext]; - DDLogError(@"%@ No valid session for recipient: %@ containsActiveSession: %@, previousStates: %lu", - self.tag, - self.recipientId, - (containsActiveSession ? @"YES" : @"NO"), - (unsigned long)sessionRecord.previousSessionStates.count); - - if (containsActiveSession) { - @throw [NSException exceptionWithName:InvalidMessageException - reason:@"No valid sessions" - userInfo:@{ - @"Exceptions" : exceptions - }]; - } else { - @throw [NSException - exceptionWithName:NoSessionException - reason:[NSString stringWithFormat:@"No session for: %@, %d", self.recipientId, self.deviceId] - userInfo:nil]; - } -} - -- (NSData *)throws_decryptWithSessionState:(SessionState *)sessionState - whisperMessage:(WhisperMessage *)whisperMessage - protocolContext:(nullable id)protocolContext -{ - OWSAssert(sessionState); - OWSAssert(whisperMessage); - - if (![sessionState hasSenderChain]) { - @throw [NSException exceptionWithName:InvalidMessageException reason:@"Uninitialized session!" userInfo:nil]; - } - - if (whisperMessage.version != sessionState.version) { - @throw [NSException exceptionWithName:InvalidMessageException - reason:[NSString stringWithFormat:@"Got message version %d but was expecting %d", - whisperMessage.version, - sessionState.version] - userInfo:nil]; - } - - int messageVersion = whisperMessage.version; - NSData *theirEphemeral = whisperMessage.senderRatchetKey.throws_removeKeyType; - int counter = whisperMessage.counter; - ChainKey *chainKey = [self throws_getOrCreateChainKeys:sessionState theirEphemeral:theirEphemeral]; - OWSAssert(chainKey); - MessageKeys *messageKeys = [self throws_getOrCreateMessageKeysForSession:sessionState - theirEphemeral:theirEphemeral - chainKey:chainKey - counter:counter]; - OWSAssert(messageKeys); - - [whisperMessage throws_verifyMacWithVersion:messageVersion - senderIdentityKey:sessionState.remoteIdentityKey - receiverIdentityKey:sessionState.localIdentityKey - macKey:messageKeys.macKey]; - - NSData *plaintext = - [AES_CBC throws_decryptCBCMode:whisperMessage.cipherText withKey:messageKeys.cipherKey withIV:messageKeys.iv]; - - [sessionState clearUnacknowledgedPreKeyMessage]; - - return plaintext; -} - -- (ChainKey *)throws_getOrCreateChainKeys:(SessionState *)sessionState theirEphemeral:(NSData *)theirEphemeral -{ - OWSAssert(sessionState); - OWSGuardWithException(theirEphemeral, InvalidMessageException); - OWSGuardWithException(theirEphemeral.length == 32, InvalidMessageException); - - @try { - if ([sessionState hasReceiverChain:theirEphemeral]) { - DDLogInfo(@"%@ %@.%d has existing receiver chain.", self.tag, self.recipientId, self.deviceId); - return [sessionState receiverChainKey:theirEphemeral]; - } else{ - DDLogInfo(@"%@ %@.%d creating new chains.", self.tag, self.recipientId, self.deviceId); - RootKey *rootKey = [sessionState rootKey]; - OWSAssert(rootKey.keyData.length == 32); - - ECKeyPair *ourEphemeral = [sessionState senderRatchetKeyPair]; - OWSAssert(ourEphemeral.publicKey.length == 32); - - RKCK *receiverChain = - [rootKey throws_createChainWithTheirEphemeral:theirEphemeral ourEphemeral:ourEphemeral]; - - ECKeyPair *ourNewEphemeral = [Curve25519 generateKeyPair]; - OWSAssert(ourNewEphemeral.publicKey.length == 32); - - RKCK *senderChain = [receiverChain.rootKey throws_createChainWithTheirEphemeral:theirEphemeral - ourEphemeral:ourNewEphemeral]; - - OWSAssert(senderChain.rootKey.keyData.length == 32); - [sessionState setRootKey:senderChain.rootKey]; - - OWSAssert(receiverChain.chainKey.key.length == 32); - [sessionState addReceiverChain:theirEphemeral chainKey:receiverChain.chainKey]; - - int previousCounter; - ows_sub_overflow(sessionState.senderChainKey.index, 1, &previousCounter); - [sessionState setPreviousCounter:MAX(previousCounter, 0)]; - [sessionState setSenderChain:ourNewEphemeral chainKey:senderChain.chainKey]; - - return receiverChain.chainKey; - } - } - @catch (NSException *exception) { - @throw [NSException exceptionWithName:InvalidMessageException reason:@"Chainkeys couldn't be derived" userInfo:nil]; - } -} - -- (MessageKeys *)throws_getOrCreateMessageKeysForSession:(SessionState *)sessionState - theirEphemeral:(NSData *)theirEphemeral - chainKey:(ChainKey *)chainKey - counter:(int)counter -{ - OWSAssert(sessionState); - OWSGuardWithException(theirEphemeral, InvalidMessageException); - OWSGuardWithException(theirEphemeral.length == 32, InvalidMessageException); - OWSAssert(chainKey); - - if (chainKey.index > counter) { - if ([sessionState hasMessageKeys:theirEphemeral counter:counter]) { - return [sessionState removeMessageKeys:theirEphemeral counter:counter]; - } else { - OWSLogInfo( - @"%@ %@.%d Duplicate message for counter: %d", self.tag, self.recipientId, self.deviceId, counter); - OWSLogFlush(); - @throw [NSException exceptionWithName:DuplicateMessageException reason:@"Received message with old counter!" userInfo:@{}]; - } - } - - NSUInteger kCounterLimit = 2000; - int counterOffset; - if (__builtin_sub_overflow(counter, chainKey.index, &counterOffset)) { - OWSFailDebug(@"Overflow while calculating counter offset"); - OWSRaiseException(InvalidMessageException, @"Overflow while calculating counter offset"); - } - if (counterOffset > kCounterLimit) { - OWSLogError(@"%@ %@.%d Exceeded future message limit: %lu, index: %d, counter: %d)", - self.tag, - self.recipientId, - self.deviceId, - (unsigned long)kCounterLimit, - chainKey.index, - counter); - OWSLogFlush(); - @throw [NSException exceptionWithName:InvalidMessageException - reason:@"Exceeded message keys chain length limit" - userInfo:@{}]; - } - - while (chainKey.index < counter) { - MessageKeys *messageKeys = [chainKey throws_messageKeys]; - [sessionState setMessageKeys:theirEphemeral messageKeys:messageKeys]; - chainKey = chainKey.nextChainKey; - } - - [sessionState setReceiverChainKey:theirEphemeral chainKey:[chainKey nextChainKey]]; - return [chainKey throws_messageKeys]; -} - -/** - * The current version data. First 4 bits are the current version and the last 4 ones are the lowest version we support. - * - * @return Current version data - */ - -+ (NSData*)currentProtocolVersion{ - NSUInteger index = 0b00100010; - NSData *versionByte = [NSData dataWithBytes:&index length:1]; - return versionByte; -} - -- (int)throws_remoteRegistrationId:(nullable id)protocolContext -{ - SessionRecord *_Nullable record = - [self.sessionStore loadSession:self.recipientId deviceId:_deviceId protocolContext:protocolContext]; - - if (!record) { - @throw [NSException exceptionWithName:NoSessionException reason:@"Trying to get registration Id of a non-existing session." userInfo:nil]; - } - - return record.sessionState.remoteRegistrationId; -} - -- (int)throws_sessionVersion:(nullable id)protocolContext -{ - SessionRecord *_Nullable record = - [self.sessionStore loadSession:self.recipientId deviceId:_deviceId protocolContext:protocolContext]; - - if (!record) { - @throw [NSException exceptionWithName:NoSessionException reason:@"Trying to get the version of a non-existing session." userInfo:nil]; - } - - return record.sessionState.version; -} - -#pragma mark - Logging - -+ (NSString *)tag -{ - return [NSString stringWithFormat:@"[%@]", self.class]; -} - -- (NSString *)tag -{ - return self.class.tag; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/SessionRestorationProtocol.swift b/SessionProtocolKit/Signal/SessionRestorationProtocol.swift deleted file mode 100644 index 9f73257d6..000000000 --- a/SessionProtocolKit/Signal/SessionRestorationProtocol.swift +++ /dev/null @@ -1,8 +0,0 @@ - -@objc(SNSessionRestorationProtocol) -public protocol SessionRestorationProtocol { - - func validatePreKeyWhisperMessage(for publicKey: String, preKeyWhisperMessage: PreKeyWhisperMessage, using transaction: Any) throws - func getSessionRestorationStatus(for publicKey: String) -> SessionRestorationStatus - func handleNewSessionAdopted(for publicKey: String, using transaction: Any) -} diff --git a/SessionProtocolKit/Signal/SessionRestorationStatus.swift b/SessionProtocolKit/Signal/SessionRestorationStatus.swift deleted file mode 100644 index 3c6e0c199..000000000 --- a/SessionProtocolKit/Signal/SessionRestorationStatus.swift +++ /dev/null @@ -1,5 +0,0 @@ - -@objc(SNSessionRestorationStatus) -public enum SessionRestorationStatus : Int { - case none, initiated, requestReceived -} diff --git a/SessionProtocolKit/Signal/Sessions/SessionBuilder.h b/SessionProtocolKit/Signal/Sessions/SessionBuilder.h deleted file mode 100644 index 80dde718f..000000000 --- a/SessionProtocolKit/Signal/Sessions/SessionBuilder.h +++ /dev/null @@ -1,44 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "AxolotlStore.h" -#import "IdentityKeyStore.h" -#import "PreKeyBundle.h" -#import "PreKeyStore.h" -#import "SessionStore.h" -#import "SignedPreKeyStore.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -@class PreKeyWhisperMessage; - -extern const int kPreKeyOfLastResortId; - -@interface SessionBuilder : NSObject - -- (instancetype)initWithAxolotlStore:(id)sessionStore - recipientId:(NSString *)recipientId - deviceId:(int)deviceId; - -- (instancetype)initWithSessionStore:(id)sessionStore - preKeyStore:(id)preKeyStore - signedPreKeyStore:(id)signedPreKeyStore - identityKeyStore:(id)identityKeyStore - recipientId:(NSString *)recipientId - deviceId:(int)deviceId; - -- (void)throws_processPrekeyBundle:(PreKeyBundle *)preKeyBundle - protocolContext:(nullable id)protocolContext NS_SWIFT_UNAVAILABLE("throws objc exceptions"); -- (BOOL)processPrekeyBundle:(PreKeyBundle *)preKeyBundle - protocolContext:(nullable id)protocolContext - error:(NSError **)outError; - -- (int)throws_processPrekeyWhisperMessage:(PreKeyWhisperMessage *)message - withSession:(SessionRecord *)sessionRecord - protocolContext:(nullable id)protocolContext NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Sessions/SessionBuilder.m b/SessionProtocolKit/Signal/Sessions/SessionBuilder.m deleted file mode 100644 index 2961c08c9..000000000 --- a/SessionProtocolKit/Signal/Sessions/SessionBuilder.m +++ /dev/null @@ -1,263 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "SessionBuilder.h" -#import "AliceAxolotlParameters.h" -#import "AxolotlExceptions.h" -#import "AxolotlParameters.h" -#import "AxolotlStore.h" -#import "BobAxolotlParameters.h" -#import "NSData+keyVersionByte.h" -#import "PreKeyWhisperMessage.h" -#import "PrekeyBundle.h" -#import "RatchetingSession.h" -#import "SessionState.h" -#import -#import -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -#define CURRENT_VERSION 3 -#define MINUMUM_VERSION 3 - -const int kPreKeyOfLastResortId = 0xFFFFFF; - -@interface SessionBuilder () - -@property (nonatomic, readonly)NSString* recipientId; -@property (nonatomic, readonly)int deviceId; - -@property(nonatomic, readonly)id sessionStore; -@property(nonatomic, readonly)id prekeyStore ; -@property(nonatomic, readonly)id signedPreKeyStore; -@property(nonatomic, readonly)id identityStore; - - -@end - -@implementation SessionBuilder - -- (instancetype)initWithAxolotlStore:(id)sessionStore recipientId:(NSString*)recipientId deviceId:(int)deviceId{ - OWSAssert(sessionStore); - OWSAssert(recipientId); - - return [self initWithSessionStore:sessionStore - preKeyStore:sessionStore - signedPreKeyStore:sessionStore - identityKeyStore:sessionStore - recipientId:recipientId - deviceId:deviceId]; -} - -- (instancetype)initWithSessionStore:(id)sessionStore - preKeyStore:(id)preKeyStore - signedPreKeyStore:(id)signedPreKeyStore - identityKeyStore:(id)identityKeyStore - recipientId:(NSString*)recipientId - deviceId:(int)deviceId{ - - OWSAssert(sessionStore); - OWSAssert(preKeyStore); - OWSAssert(signedPreKeyStore); - OWSAssert(identityKeyStore); - OWSAssert(recipientId); - - self = [super init]; - - if (self) { - _sessionStore = sessionStore; - _prekeyStore = preKeyStore; - _signedPreKeyStore = signedPreKeyStore; - _identityStore = identityKeyStore; - _recipientId = recipientId; - _deviceId = deviceId; - } - - return self; -} - -- (BOOL)processPrekeyBundle:(PreKeyBundle *)preKeyBundle - protocolContext:(nullable id)protocolContext - error:(NSError **)outError -{ - return [SCKExceptionWrapper - tryBlock:^{ - [self throws_processPrekeyBundle:preKeyBundle protocolContext:protocolContext]; - } - error:outError]; -} - -- (void)throws_processPrekeyBundle:(PreKeyBundle *)preKeyBundle protocolContext:(nullable id)protocolContext -{ - OWSAssert(preKeyBundle); - - NSData *theirIdentityKey = preKeyBundle.identityKey.throws_removeKeyType; - NSData *theirSignedPreKey = preKeyBundle.signedPreKeyPublic.throws_removeKeyType; - - if (![self.identityStore isTrustedIdentityKey:theirIdentityKey - recipientId:self.recipientId - direction:TSMessageDirectionOutgoing - protocolContext:protocolContext]) { - @throw [NSException exceptionWithName:UntrustedIdentityKeyException reason:@"Identity key is not valid" userInfo:@{}]; - } - - // NOTE: we use preKeyBundle.signedPreKeyPublic which has the key type byte. - if (![Ed25519 throws_verifySignature:preKeyBundle.signedPreKeySignature - publicKey:theirIdentityKey - data:preKeyBundle.signedPreKeyPublic]) { - @throw [NSException exceptionWithName:InvalidKeyException reason:@"KeyIsNotValidlySigned" userInfo:nil]; - } - - SessionRecord *sessionRecord = - [self.sessionStore loadSession:self.recipientId deviceId:preKeyBundle.deviceId protocolContext:protocolContext]; - ECKeyPair *ourBaseKey = [Curve25519 generateKeyPair]; - NSData *theirOneTimePreKey = preKeyBundle.preKeyPublic.throws_removeKeyType; - int theirOneTimePreKeyId = preKeyBundle.preKeyId; - int theirSignedPreKeyId = preKeyBundle.signedPreKeyId; - - - AliceAxolotlParameters *params = - [[AliceAxolotlParameters alloc] initWithIdentityKey:[self.identityStore identityKeyPair:protocolContext] - theirIdentityKey:theirIdentityKey - ourBaseKey:ourBaseKey - theirSignedPreKey:theirSignedPreKey - theirOneTimePreKey:theirOneTimePreKey - theirRatchetKey:theirSignedPreKey]; - - if (!sessionRecord.isFresh) { - [sessionRecord archiveCurrentState]; - } - - [RatchetingSession throws_initializeSession:[sessionRecord sessionState] - sessionVersion:CURRENT_VERSION - AliceParameters:params]; - - DDLogInfo(@"setUnacknowledgedPreKeyMessage for: %@ with preKeyId: %d", self.recipientId, theirOneTimePreKeyId); - - [sessionRecord.sessionState setUnacknowledgedPreKeyMessage:theirOneTimePreKeyId signedPreKey:theirSignedPreKeyId baseKey:ourBaseKey.publicKey]; - [sessionRecord.sessionState setLocalRegistrationId:[self.identityStore localRegistrationId:protocolContext]]; - [sessionRecord.sessionState setRemoteRegistrationId:preKeyBundle.registrationId]; - [sessionRecord.sessionState setAliceBaseKey:ourBaseKey.publicKey]; - - // Saving invalidates any existing sessions, so be sure to save *before* storing the new session. - BOOL previousIdentityExisted = [self.identityStore saveRemoteIdentity:theirIdentityKey - recipientId:self.recipientId - protocolContext:protocolContext]; - if (previousIdentityExisted) { - DDLogInfo(@"%@ PKBundle removing previous session states for changed identity for recipient:%@", - self.tag, - self.recipientId); - [sessionRecord removePreviousSessionStates]; - } - - [self.sessionStore storeSession:self.recipientId - deviceId:self.deviceId - session:sessionRecord - protocolContext:protocolContext]; -} - -- (int)throws_processPrekeyWhisperMessage:(PreKeyWhisperMessage *)message - withSession:(SessionRecord *)sessionRecord - protocolContext:(nullable id)protocolContext -{ - OWSAssert(message); - OWSAssert(sessionRecord); - - int messageVersion = message.version; - NSData *theirIdentityKey = message.identityKey.throws_removeKeyType; - - if (![self.identityStore isTrustedIdentityKey:theirIdentityKey - recipientId:self.recipientId - direction:TSMessageDirectionIncoming - protocolContext:protocolContext]) { - @throw [NSException exceptionWithName:UntrustedIdentityKeyException reason:@"There is a previously known identity key." userInfo:@{}]; - } - - int unSignedPrekeyId = -1; - - switch (messageVersion) { - case 3: - unSignedPrekeyId = - [self throws_processPrekeyV3:message withSession:sessionRecord protocolContext:protocolContext]; - break; - default: - @throw [NSException exceptionWithName:InvalidVersionException reason:@"Trying to initialize with unknown version" userInfo:@{}]; - break; - } - - [self.identityStore saveRemoteIdentity:theirIdentityKey - recipientId:self.recipientId - protocolContext:protocolContext]; - - return unSignedPrekeyId; -} - -- (int)throws_processPrekeyV3:(PreKeyWhisperMessage *)message - withSession:(SessionRecord *)sessionRecord - protocolContext:(nullable id)protocolContext -{ - OWSAssert(message); - OWSAssert(sessionRecord); - - NSData *baseKey = message.baseKey.throws_removeKeyType; - - if ([sessionRecord hasSessionState:message.version baseKey:baseKey]) { - return -1; - } - - ECKeyPair *ourSignedPrekey = [self.signedPreKeyStore throws_loadSignedPrekey:message.signedPrekeyId].keyPair; - - ECKeyPair *_Nullable ourOneTimePreKey; - if (message.prekeyID >= 0) { - ourOneTimePreKey = [self.prekeyStore throws_loadPreKey:message.prekeyID].keyPair; - } else { - DDLogWarn(@"%@ Processing PreKey message which had no one-time prekey.", self.tag); - } - - BobAxolotlParameters *params = - [[BobAxolotlParameters alloc] initWithMyIdentityKeyPair:[self.identityStore identityKeyPair:protocolContext] - theirIdentityKey:message.identityKey.throws_removeKeyType - ourSignedPrekey:ourSignedPrekey - ourRatchetKey:ourSignedPrekey - ourOneTimePrekey:ourOneTimePreKey - theirBaseKey:baseKey]; - - if (!sessionRecord.isFresh) { - [sessionRecord archiveCurrentState]; - } - - [RatchetingSession throws_initializeSession:sessionRecord.sessionState - sessionVersion:message.version - BobParameters:params]; - - [sessionRecord.sessionState setLocalRegistrationId:[self.identityStore localRegistrationId:protocolContext]]; - [sessionRecord.sessionState setRemoteRegistrationId:message.registrationId]; - [sessionRecord.sessionState setAliceBaseKey:baseKey]; - - // If we used a prekey and it wasn't the prekey of last resort - if (message.prekeyID >= 0 && message.prekeyID != kPreKeyOfLastResortId) { - return message.prekeyID; - } else { - return -1; - } -} - -#pragma mark - Logging - -+ (NSString *)tag -{ - return [NSString stringWithFormat:@"[%@]", self.class]; -} - -- (NSString *)tag -{ - return self.class.tag; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Sessions/SessionRecord.h b/SessionProtocolKit/Signal/Sessions/SessionRecord.h deleted file mode 100644 index d695c8057..000000000 --- a/SessionProtocolKit/Signal/Sessions/SessionRecord.h +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import -#import "SessionState.h" - -@interface SessionRecord : NSObject - -- (instancetype)init; - -- (BOOL)hasSessionState:(int)version baseKey:(NSData*)aliceBaseKey; -- (SessionState*)sessionState; -- (NSMutableArray *)previousSessionStates; - -- (void)removePreviousSessionStates; -- (BOOL)isFresh; -- (void)markAsUnFresh; -- (void)archiveCurrentState; -- (void)promoteState:(SessionState*)promotedState; -- (void)setState:(SessionState*)sessionState; - -@end diff --git a/SessionProtocolKit/Signal/Sessions/SessionRecord.m b/SessionProtocolKit/Signal/Sessions/SessionRecord.m deleted file mode 100644 index 32fc95da0..000000000 --- a/SessionProtocolKit/Signal/Sessions/SessionRecord.m +++ /dev/null @@ -1,115 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import "SessionRecord.h" -#import - -#define ARCHIVED_STATES_MAX_LENGTH 40 - -@interface SessionRecord() - -@property (nonatomic, retain) SessionState* sessionState; -@property (nonatomic, retain) NSMutableArray* previousStates; -@property (nonatomic) BOOL fresh; - -@end - -#define currentSessionStateKey @"currentSessionStateKey" -#define previousSessionsStateKey @"previousSessionStateKeys" - -@implementation SessionRecord - -- (instancetype)init{ - self = [super init]; - - if (self) { - _fresh = YES; - _sessionState = [SessionState new]; - _previousStates = [NSMutableArray new]; - } - - return self; -} - -#pragma mark Serialization - -+ (BOOL)supportsSecureCoding{ - return YES; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder{ - [aCoder encodeObject:self.previousStates forKey:previousSessionsStateKey]; - [aCoder encodeObject:self.sessionState forKey:currentSessionStateKey]; -} - -- (instancetype)initWithCoder:(NSCoder *)aDecoder{ - self = [self init]; - - self.fresh = false; - - self.previousStates = [aDecoder decodeObjectOfClass:[NSMutableArray class] forKey:previousSessionsStateKey]; - self.sessionState = [aDecoder decodeObjectOfClass:[SessionState class] forKey:currentSessionStateKey]; - - return self; -} - -- (BOOL)hasSessionState:(int)version baseKey:(NSData *)aliceBaseKey{ - if (self.sessionState.version == version && [aliceBaseKey isEqualToData:self.sessionState.aliceBaseKey]) { - return YES; - } - - for (SessionState *state in self.previousStates) { - if (state.version == version && [aliceBaseKey isEqualToData:self.sessionState.aliceBaseKey]) { - return YES; - } - } - - return NO; -} - -- (SessionState*)sessionState{ - return _sessionState; -} - -- (NSMutableArray *)previousSessionStates -{ - return _previousStates; -} - -- (void)removePreviousSessionStates -{ - [_previousStates removeAllObjects]; -} - -- (BOOL)isFresh{ - return _fresh; -} - -- (void)markAsUnFresh -{ - self.fresh = false; -} - -- (void)archiveCurrentState{ - [self promoteState:[SessionState new]]; -} - -- (void)promoteState:(SessionState *)promotedState{ - [self.previousStates insertObject:self.sessionState atIndex:0]; - self.sessionState = promotedState; - - if (self.previousStates.count > ARCHIVED_STATES_MAX_LENGTH) { - NSUInteger deleteCount; - ows_sub_overflow(self.previousStates.count, ARCHIVED_STATES_MAX_LENGTH, &deleteCount); - NSIndexSet *indexesToDelete = - [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(ARCHIVED_STATES_MAX_LENGTH, deleteCount)]; - [self.previousSessionStates removeObjectsAtIndexes:indexesToDelete]; - } -} - -- (void)setState:(SessionState *)sessionState{ - self.sessionState = sessionState; -} - -@end diff --git a/SessionProtocolKit/Signal/Sessions/SessionState.h b/SessionProtocolKit/Signal/Sessions/SessionState.h deleted file mode 100644 index 2344b055f..000000000 --- a/SessionProtocolKit/Signal/Sessions/SessionState.h +++ /dev/null @@ -1,71 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import -@class ECKeyPair; -#import "RKCK.h" -#import "MessageKeys.h" -#import "Chain.h" -#import "RootKey.h" - -/** - * Pending PreKeys - */ - -@interface PendingPreKey : NSObject - -@property (readonly) int preKeyId; -@property (readonly) int signedPreKeyId; -@property (readonly) NSData *baseKey; - --(instancetype)initWithBaseKey:(NSData*)baseKey preKeyId:(int)preKeyId signedPreKeyId:(int)signedPrekeyId; - -@end - -@interface SessionState : NSObject - -/** - * AxolotlSessions are either retreived from the database or initiated on new discussions. They are serialized before being stored to make storing abstractions significantly simpler. Because we propose no abstraction for a contact and TextSecure has multi-device (multiple sessions with same identity key) support, the identityKeys need to be added manually. - */ - -@property(nonatomic) int version; -@property(nonatomic, copy) NSData *aliceBaseKey; -@property(nonatomic) NSData *remoteIdentityKey; -@property(nonatomic) NSData *localIdentityKey; -@property(nonatomic) int previousCounter; -@property(nonatomic) RootKey *rootKey; - -@property(nonatomic)int remoteRegistrationId; -@property(nonatomic)int localRegistrationId; - -- (NSData*)senderRatchetKey; -- (ECKeyPair*)senderRatchetKeyPair; - -- (BOOL)hasReceiverChain:(NSData *)senderEphemeral; -- (BOOL)hasSenderChain; - -- (ChainKey *)receiverChainKey:(NSData *)senderEphemeral; - -- (void)setReceiverChainKey:(NSData*)senderEphemeral chainKey:(ChainKey*)chainKey; - -- (void)addReceiverChain:(NSData*)senderRatchetKey chainKey:(ChainKey*)chainKey; - -- (void)setSenderChain:(ECKeyPair*)senderRatcherKeyPair chainKey:(ChainKey*)chainKey; - -- (ChainKey*)senderChainKey; - -- (void)setSenderChainKey:(ChainKey*)nextChainKey; - -- (BOOL)hasMessageKeys:(NSData*)senderRatchetKey counter:(int)counter; - -- (MessageKeys*)removeMessageKeys:(NSData*)senderRatcherKey counter:(int)counter; - -- (void)setMessageKeys:(NSData*)senderRatchetKey messageKeys:(MessageKeys*)messageKeys; - -- (void)setUnacknowledgedPreKeyMessage:(int)preKeyId signedPreKey:(int)signedPreKeyId baseKey:(NSData*)baseKey; -- (BOOL)hasUnacknowledgedPreKeyMessage; -- (PendingPreKey*)unacknowledgedPreKeyMessageItems; -- (void)clearUnacknowledgedPreKeyMessage; - -@end diff --git a/SessionProtocolKit/Signal/Sessions/SessionState.m b/SessionProtocolKit/Signal/Sessions/SessionState.m deleted file mode 100644 index f877c539e..000000000 --- a/SessionProtocolKit/Signal/Sessions/SessionState.m +++ /dev/null @@ -1,313 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import -#import "SessionState.h" -#import "ReceivingChain.h" -#import "SendingChain.h" -#import "ChainAndIndex.h" -#import - -@implementation PendingPreKey - -static NSString* const kCoderPreKeyId = @"kCoderPreKeyId"; -static NSString* const kCoderSignedPreKeyId = @"kCoderSignedPreKeyId"; -static NSString* const kCoderBaseKey = @"kCoderBaseKey"; - - -+ (BOOL)supportsSecureCoding{ - return YES; -} - --(instancetype)initWithBaseKey:(NSData*)baseKey preKeyId:(int)preKeyId signedPreKeyId:(int)signedPrekeyId{ - OWSAssert(baseKey); - - self = [super init]; - if (self) { - _preKeyId = preKeyId; - _signedPreKeyId = signedPrekeyId; - _baseKey = baseKey; - } - return self; -} - -- (id)initWithCoder:(NSCoder *)aDecoder{ - self = [self initWithBaseKey:[aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderBaseKey] - preKeyId:[aDecoder decodeIntForKey:kCoderPreKeyId] - signedPreKeyId:[aDecoder decodeIntForKey:kCoderSignedPreKeyId]]; - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder{ - [aCoder encodeObject:_baseKey forKey:kCoderBaseKey]; - [aCoder encodeInt:_preKeyId forKey:kCoderPreKeyId]; - [aCoder encodeInt:_signedPreKeyId forKey:kCoderSignedPreKeyId]; -} - -@end - -@interface SessionState () - -@property SendingChain *sendingChain; // The outgoing sending chain -@property NSMutableArray *receivingChains; // NSArray of ReceivingChains -@property PendingPreKey *pendingPreKey; - -@end - -#pragma mark Keys for coder - -static NSString* const kCoderVersion = @"kCoderVersion"; -static NSString* const kCoderAliceBaseKey = @"kCoderAliceBaseKey"; -static NSString* const kCoderRemoteIDKey = @"kCoderRemoteIDKey"; -static NSString* const kCoderLocalIDKey = @"kCoderLocalIDKey"; -static NSString* const kCoderPreviousCounter = @"kCoderPreviousCounter"; -static NSString* const kCoderRootKey = @"kCoderRoot"; -static NSString* const kCoderLocalRegID = @"kCoderLocalRegID"; -static NSString* const kCoderRemoteRegID = @"kCoderRemoteRegID"; -static NSString* const kCoderReceiverChains = @"kCoderReceiverChains"; -static NSString* const kCoderSendingChain = @"kCoderSendingChain"; -static NSString* const kCoderPendingPrekey = @"kCoderPendingPrekey"; - -@implementation SessionState - -+ (BOOL)supportsSecureCoding{ - return YES; -} - -- (instancetype)init{ - self = [super init]; - - if (self) { - self.receivingChains = [NSMutableArray array]; - } - - return self; -} - -- (id)initWithCoder:(NSCoder *)aDecoder{ - self = [self init]; - - if (self) { - self.version = [aDecoder decodeIntForKey:kCoderVersion]; - self.aliceBaseKey = [aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderAliceBaseKey]; - self.remoteIdentityKey = [aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderRemoteIDKey]; - self.localIdentityKey = [aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderLocalIDKey]; - self.previousCounter = [aDecoder decodeIntForKey:kCoderPreviousCounter]; - self.rootKey = [aDecoder decodeObjectOfClass:[NSData class] forKey:kCoderRootKey]; - self.remoteRegistrationId = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:kCoderRemoteRegID] intValue]; - self.localRegistrationId = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:kCoderLocalRegID] intValue]; - self.sendingChain = [aDecoder decodeObjectOfClass:[SendingChain class] forKey:kCoderSendingChain]; - self.receivingChains = [aDecoder decodeObjectOfClass:[NSArray class] forKey:kCoderReceiverChains]; - self.pendingPreKey = [aDecoder decodeObjectOfClass:[PendingPreKey class] forKey:kCoderPendingPrekey]; - } - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder{ - [aCoder encodeInt:self.version forKey:kCoderVersion]; - [aCoder encodeObject:self.aliceBaseKey forKey:kCoderAliceBaseKey]; - [aCoder encodeObject:self.remoteIdentityKey forKey:kCoderRemoteIDKey]; - [aCoder encodeObject:self.localIdentityKey forKey:kCoderLocalIDKey]; - [aCoder encodeInt:self.previousCounter forKey:kCoderPreviousCounter]; - [aCoder encodeObject:self.rootKey forKey:kCoderRootKey]; - [aCoder encodeObject:[NSNumber numberWithInt:self.remoteRegistrationId] forKey:kCoderRemoteRegID]; - [aCoder encodeObject:[NSNumber numberWithInt:self.localRegistrationId] forKey:kCoderLocalRegID]; - [aCoder encodeObject:self.sendingChain forKey:kCoderSendingChain]; - [aCoder encodeObject:[self.receivingChains mutableCopy] forKey:kCoderReceiverChains]; - [aCoder encodeObject:self.pendingPreKey forKey:kCoderPendingPrekey]; -} - -- (NSData*)senderRatchetKey{ - return [[self senderRatchetKeyPair] publicKey]; -} - -- (ECKeyPair*)senderRatchetKeyPair{ - return [[self sendingChain] senderRatchetKeyPair]; -} - -- (BOOL)hasReceiverChain:(NSData *)senderEphemeral -{ - return [self receiverChain:senderEphemeral] != nil; -} - -- (BOOL)hasSenderChain{ - return self.sendingChain != nil; -} - -- (ChainAndIndex *)receiverChain:(NSData *)senderEphemeral -{ - int index = 0; - - for (ReceivingChain *receiverChain in self.receivingChains) { - NSData *chainSenderRatchetKey = receiverChain.senderRatchetKey; - - if ([chainSenderRatchetKey isEqualToData:senderEphemeral]) { - ChainAndIndex *cai = [[ChainAndIndex alloc] init]; - cai.chain = receiverChain; - cai.index = index; - return cai; - } - ows_add_overflow(index, 1, &index); - } - - return nil; -} - -- (ChainKey *)receiverChainKey:(NSData *)senderEphemeral -{ - OWSAssert(senderEphemeral); - - ChainAndIndex *receiverChainAndIndex = [self receiverChain:senderEphemeral]; - ReceivingChain *receiverChain = (ReceivingChain*)receiverChainAndIndex.chain; - - if (receiverChain == nil) { - return nil; - } else{ - OWSAssert(receiverChain.chainKey.key); - return [[ChainKey alloc] initWithData:receiverChain.chainKey.key index:receiverChain.chainKey.index]; - } -} - -- (void)setReceiverChainKey:(NSData*)senderEphemeral chainKey:(ChainKey*)nextChainKey{ - OWSAssert(senderEphemeral); - OWSAssert(nextChainKey); - - ChainAndIndex *chainAndIndex = [self receiverChain:senderEphemeral]; - ReceivingChain *chain = (ReceivingChain*)chainAndIndex.chain; - - ReceivingChain *newChain = chain; - newChain.chainKey = nextChainKey; - - [self.receivingChains replaceObjectAtIndex:chainAndIndex.index withObject:newChain]; -} - -- (void)addReceiverChain:(NSData*)senderRatchetKey chainKey:(ChainKey*)chainKey{ - OWSAssert(senderRatchetKey); - OWSAssert(chainKey); - ReceivingChain *receivingChain = [[ReceivingChain alloc] initWithChainKey:chainKey senderRatchetKey:senderRatchetKey]; - - [self.receivingChains addObject:receivingChain]; - - if ([self.receivingChains count] > 5) { - DDLogInfo( - @"%@ Trimming excessive receivingChain count: %lu", self.tag, (unsigned long)self.receivingChains.count); - // We keep 5 receiving chains to be able to decrypt out of order messages. - [self.receivingChains removeObjectAtIndex:0]; - } -} - -- (void)setSenderChain:(ECKeyPair*)senderRatchetKeyPair chainKey:(ChainKey*)chainKey{ - OWSAssert(senderRatchetKeyPair); - OWSAssert(chainKey); - - self.sendingChain = [[SendingChain alloc]initWithChainKey:chainKey senderRatchetKeyPair:senderRatchetKeyPair]; -} - -- (ChainKey*)senderChainKey{ - return self.sendingChain.chainKey; -} - -- (void)setSenderChainKey:(ChainKey*)nextChainKey{ - OWSAssert(nextChainKey); - - SendingChain *sendingChain = self.sendingChain; - sendingChain.chainKey = nextChainKey; - - self.sendingChain = sendingChain; -} - -- (BOOL)hasMessageKeys:(NSData*)senderRatchetKey counter:(int)counter{ - OWSAssert(senderRatchetKey); - ChainAndIndex *chainAndIndex = [self receiverChain:senderRatchetKey]; - ReceivingChain *receivingChain = (ReceivingChain*)chainAndIndex.chain; - - if (!receivingChain) { - return NO; - } - - NSArray *messageKeyArray = receivingChain.messageKeysList; - - for (MessageKeys *keys in messageKeyArray) { - if (keys.index == counter) { - return YES; - } - } - - return NO; -} - -- (MessageKeys*)removeMessageKeys:(NSData*)senderRatcherKey counter:(int)counter{ - ChainAndIndex *chainAndIndex = [self receiverChain:senderRatcherKey]; - ReceivingChain *receivingChain = (ReceivingChain*)chainAndIndex.chain; - - if (!receivingChain) { - return nil; - } - - NSMutableArray *messageList = receivingChain.messageKeysList; - - MessageKeys *result; - - for(MessageKeys *messageKeys in messageList){ - if (messageKeys.index == counter) { - result = messageKeys; - break; - } - } - - [messageList removeObject:result]; - - return result; -} - --(void)setReceiverChain:(int)index updatedChain:(ReceivingChain*)recvchain{ - OWSAssert(recvchain); - - [self.receivingChains replaceObjectAtIndex:index withObject:recvchain]; -} - -- (void)setMessageKeys:(NSData*)senderRatchetKey messageKeys:(MessageKeys*)messageKeys{ - OWSAssert(senderRatchetKey); - OWSAssert(messageKeys); - - ChainAndIndex *chainAndIndex = [self receiverChain:senderRatchetKey]; - ReceivingChain *chain = (ReceivingChain*)chainAndIndex.chain; - [chain.messageKeysList addObject:messageKeys]; - - [self setReceiverChain:chainAndIndex.index updatedChain:chain]; -} - -- (void)setUnacknowledgedPreKeyMessage:(int)preKeyId signedPreKey:(int)signedPreKeyId baseKey:(NSData*)baseKey{ - OWSAssert(baseKey); - - PendingPreKey *pendingPreKey = [[PendingPreKey alloc] initWithBaseKey:baseKey preKeyId:preKeyId signedPreKeyId:signedPreKeyId]; - - self.pendingPreKey = pendingPreKey; -} - -- (BOOL)hasUnacknowledgedPreKeyMessage{ - return self.pendingPreKey?YES:NO; -} - -- (PendingPreKey*)unacknowledgedPreKeyMessageItems{ - return self.pendingPreKey; -} -- (void)clearUnacknowledgedPreKeyMessage{ - self.pendingPreKey = nil; -} - -#pragma mark - Logging - -+ (NSString *)tag -{ - return [NSString stringWithFormat:@"[%@]", self.class]; -} - -- (NSString *)tag -{ - return self.class.tag; -} - -@end diff --git a/SessionProtocolKit/Signal/State/AxolotlStore.h b/SessionProtocolKit/Signal/State/AxolotlStore.h deleted file mode 100644 index 357598460..000000000 --- a/SessionProtocolKit/Signal/State/AxolotlStore.h +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "IdentityKeyStore.h" -#import "PreKeyStore.h" -#import "SessionStore.h" -#import "SignedPreKeyStore.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -/** - * The Session Store defines the interface of the storage of sesssions. - */ - -@protocol AxolotlStore - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/State/IdentityKeyStore.h b/SessionProtocolKit/Signal/State/IdentityKeyStore.h deleted file mode 100644 index 7dc88859b..000000000 --- a/SessionProtocolKit/Signal/State/IdentityKeyStore.h +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@class ECKeyPair; - -typedef NS_ENUM(NSInteger, TSMessageDirection) { - TSMessageDirectionUnknown = 0, - TSMessageDirectionIncoming, - TSMessageDirectionOutgoing -}; - -// See a discussion of the protocolContext in SessionCipher.h. -@protocol IdentityKeyStore - -- (nullable ECKeyPair *)identityKeyPair:(nullable id)protocolContext; - -- (int)localRegistrationId:(nullable id)protocolContext; - -/** - * Record a recipients identity key - * - * @param identityKey key data used to identify the recipient - * @param recipientId unique stable identifier for the recipient, e.g. e164 phone number - * - * @returns YES if we are replacing an existing known identity key for recipientId. - * NO if there was no previously stored identity key for the recipient. - */ -- (BOOL)saveRemoteIdentity:(NSData *)identityKey - recipientId:(NSString *)recipientId - protocolContext:(nullable id)protocolContext; - -/** - * @param identityKey key data used to identify the recipient - * @param recipientId unique stable identifier for the recipient, e.g. e164 phone number - * @param direction whether the key is being used in a sending or receiving context, as this could affect the - * decision to trust the key. - * - * @returns YES if the key is trusted - * NO if the key is not trusted - */ -- (BOOL)isTrustedIdentityKey:(NSData *)identityKey - recipientId:(NSString *)recipientId - direction:(TSMessageDirection)direction - protocolContext:(nullable id)protocolContext; - -- (nullable NSData *)identityKeyForRecipientId:(NSString *)recipientId; - -- (nullable NSData *)identityKeyForRecipientId:(NSString *)recipientId protocolContext:(nullable id)protocolContext; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/State/PreKeyStore.h b/SessionProtocolKit/Signal/State/PreKeyStore.h deleted file mode 100644 index 863222908..000000000 --- a/SessionProtocolKit/Signal/State/PreKeyStore.h +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "PreKeyRecord.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol PreKeyStore - -- (PreKeyRecord *)throws_loadPreKey:(int)preKeyId NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -- (void)storePreKey:(int)preKeyId preKeyRecord:(PreKeyRecord *)record; - -- (BOOL)containsPreKey:(int)preKeyId; - -- (void)removePreKey:(int)preKeyId protocolContext:(nullable id)protocolContext; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/State/SessionStore.h b/SessionProtocolKit/Signal/State/SessionStore.h deleted file mode 100644 index ce3a37eea..000000000 --- a/SessionProtocolKit/Signal/State/SessionStore.h +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "SessionRecord.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -// See a discussion of the protocolContext in SessionCipher.h. -@protocol SessionStore - -/** - * Returns a copy of the SessionRecord corresponding to the recipientId + deviceId tuple or a new SessionRecord if one does not currently exist. - * - * @param contactIdentifier The recipientId of the remote client. - * @param deviceId The deviceId of the remote client. - * - * @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple. - */ -- (SessionRecord *)loadSession:(NSString *)contactIdentifier - deviceId:(int)deviceId - protocolContext:(nullable id)protocolContext; - -- (NSArray *)subDevicesSessions:(NSString *)contactIdentifier protocolContext:(nullable id)protocolContext __attribute__((deprecated)); - -- (void)storeSession:(NSString *)contactIdentifier - deviceId:(int)deviceId - session:(SessionRecord *)session - protocolContext:(nullable id)protocolContext; - -- (BOOL)containsSession:(NSString *)contactIdentifier - deviceId:(int)deviceId - protocolContext:(nullable id)protocolContext; - -- (void)deleteSessionForContact:(NSString *)contactIdentifier - deviceId:(int)deviceId - protocolContext:(nullable id)protocolContext; - -- (void)deleteAllSessionsForContact:(NSString *)contactIdentifier protocolContext:(nullable id)protocolContext; - -- (void)archiveAllSessionsForContact:(NSString *)contactIdentifier protocolContext:(nullable id)protocolContext; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/State/SignedPreKeyStore.h b/SessionProtocolKit/Signal/State/SignedPreKeyStore.h deleted file mode 100644 index 1efb143c0..000000000 --- a/SessionProtocolKit/Signal/State/SignedPreKeyStore.h +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "SignedPrekeyRecord.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -@protocol SignedPreKeyStore - -- (SignedPreKeyRecord *)throws_loadSignedPrekey:(int)signedPreKeyId NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -- (nullable SignedPreKeyRecord *)loadSignedPrekeyOrNil:(int)signedPreKeyId; - -- (NSArray *)loadSignedPreKeys; - -- (void)storeSignedPreKey:(int)signedPreKeyId signedPreKeyRecord:(SignedPreKeyRecord *)signedPreKeyRecord; - -- (BOOL)containsSignedPreKey:(int)signedPreKeyId; - -- (void)removeSignedPreKey:(int)signedPrekeyId; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/NSData+keyVersionByte.h b/SessionProtocolKit/Signal/Utility/NSData+keyVersionByte.h deleted file mode 100644 index a4c6f1b50..000000000 --- a/SessionProtocolKit/Signal/Utility/NSData+keyVersionByte.h +++ /dev/null @@ -1,14 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -@interface NSData (keyVersionByte) - -- (instancetype)prependKeyType; - -- (instancetype)throws_removeKeyType NS_SWIFT_UNAVAILABLE("throws objc exceptions"); -- (nullable instancetype)removeKeyTypeAndReturnError:(NSError **)outError; - -@end diff --git a/SessionProtocolKit/Signal/Utility/NSData+keyVersionByte.m b/SessionProtocolKit/Signal/Utility/NSData+keyVersionByte.m deleted file mode 100644 index 24c0f8648..000000000 --- a/SessionProtocolKit/Signal/Utility/NSData+keyVersionByte.m +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "NSData+keyVersionByte.h" -#import "AxolotlExceptions.h" -#import -#import - -@implementation NSData (keyVersionByte) - -const Byte DJB_TYPE = 0x05; - -- (instancetype)prependKeyType { - if (self.length == 32) { - NSMutableData *data = [NSMutableData dataWithBytes:&DJB_TYPE length:1]; - [data appendData:self.copy]; - return data; - } else { - OWSLogDebug(@"key length: %lu", (unsigned long)self.length); - } - return self; -} - -- (nullable instancetype)removeKeyTypeAndReturnError:(NSError **)outError -{ - @try { - return self.throws_removeKeyType; - } @catch (NSException *exception) { - *outError = SCKExceptionWrapperErrorMake(exception); - return nil; - } -} - -- (instancetype)throws_removeKeyType -{ - if (self.length == 33) { - if ([[self subdataWithRange:NSMakeRange(0, 1)] isEqualToData:[NSData dataWithBytes:&DJB_TYPE length:1]]) { - return [self subdataWithRange:NSMakeRange(1, 32)]; - } else{ - @throw [NSException exceptionWithName:InvalidKeyException reason:@"Key type is incorrect" userInfo:@{}]; - } - } else { - OWSLogDebug(@"key length: %lu", (unsigned long)self.length); - return self; - } -} - -@end diff --git a/SessionProtocolKit/Signal/Utility/SerializationUtilities.h b/SessionProtocolKit/Signal/Utility/SerializationUtilities.h deleted file mode 100644 index a108969cc..000000000 --- a/SessionProtocolKit/Signal/Utility/SerializationUtilities.h +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -#define MAC_LENGTH 8 - -@interface SerializationUtilities : NSObject - -+ (int)highBitsToIntFromByte:(Byte)byte; - -+ (int)lowBitsToIntFromByte:(Byte)byte; - -+ (Byte)intsToByteHigh:(int)highValue low:(int)lowValue; - -+ (NSData *)throws_macWithVersion:(int)version - identityKey:(NSData *)senderIdentityKey - receiverIdentityKey:(NSData *)receiverIdentityKey - macKey:(NSData *)macKey - serialized:(NSData *)serialized NS_SWIFT_UNAVAILABLE("throws objc exceptions"); - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Signal/Utility/SerializationUtilities.m b/SessionProtocolKit/Signal/Utility/SerializationUtilities.m deleted file mode 100644 index c8dd2729f..000000000 --- a/SessionProtocolKit/Signal/Utility/SerializationUtilities.m +++ /dev/null @@ -1,81 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "SerializationUtilities.h" -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@implementation SerializationUtilities - -+ (int)highBitsToIntFromByte:(Byte)byte -{ - return (byte & 0xFF) >> 4; -} - -+ (int)lowBitsToIntFromByte:(Byte)byte -{ - return (byte & 0xF); -} - -+ (Byte)intsToByteHigh:(int)highValue low:(int)lowValue -{ - return (Byte)((highValue << 4 | lowValue) & 0xFF); -} - -+ (NSData *)throws_macWithVersion:(int)version - identityKey:(NSData *)senderIdentityKey - receiverIdentityKey:(NSData *)receiverIdentityKey - macKey:(NSData *)macKey - serialized:(NSData *)serialized -{ - if (!macKey) { - @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Missing macKey." userInfo:nil]; - } - if (macKey.length >= SIZE_MAX) { - @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Oversize macKey." userInfo:nil]; - } - if (!senderIdentityKey) { - @throw - [NSException exceptionWithName:NSInvalidArgumentException reason:@"Missing senderIdentityKey" userInfo:nil]; - } - if (senderIdentityKey.length >= SIZE_MAX) { - @throw [NSException exceptionWithName:NSInvalidArgumentException - reason:@"Oversize senderIdentityKey" - userInfo:nil]; - } - if (!receiverIdentityKey) { - @throw [NSException exceptionWithName:NSInvalidArgumentException - reason:@"Missing receiverIdentityKey" - userInfo:nil]; - } - if (receiverIdentityKey.length >= SIZE_MAX) { - @throw [NSException exceptionWithName:NSInvalidArgumentException - reason:@"Oversize receiverIdentityKey" - userInfo:nil]; - } - if (!serialized) { - @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Missing serialized." userInfo:nil]; - } - if (serialized.length >= SIZE_MAX) { - @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Oversize serialized." userInfo:nil]; - } - - NSMutableData *_Nullable bufferData = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH]; - OWSAssert(bufferData); - - CCHmacContext context; - CCHmacInit(&context, kCCHmacAlgSHA256, [macKey bytes], [macKey length]); - CCHmacUpdate(&context, [senderIdentityKey bytes], [senderIdentityKey length]); - CCHmacUpdate(&context, [receiverIdentityKey bytes], [receiverIdentityKey length]); - CCHmacUpdate(&context, [serialized bytes], [serialized length]); - CCHmacFinal(&context, bufferData.mutableBytes); - - return [bufferData subdataWithRange:NSMakeRange(0, MAC_LENGTH)]; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SessionProtocolKit/Storage.swift b/SessionProtocolKit/Storage.swift index 1b13064ae..9f8419dc7 100644 --- a/SessionProtocolKit/Storage.swift +++ b/SessionProtocolKit/Storage.swift @@ -1,3 +1,4 @@ +import Curve25519Kit public enum ClosedGroupRatchetCollectionType { case old, current diff --git a/SessionShareExtension/ShareViewController.swift b/SessionShareExtension/ShareViewController.swift index df273462d..6383cf785 100644 --- a/SessionShareExtension/ShareViewController.swift +++ b/SessionShareExtension/ShareViewController.swift @@ -173,9 +173,6 @@ public class ShareViewController: UIViewController, ShareViewDelegate, SAEFailed ensureRootViewController() - // Always check prekeys after app launches, and sometimes check on app activation. - TSPreKeyManager.checkPreKeysIfNecessary() - // We don't need to use RTCInitializeSSL() in the SAE. if tsAccountManager.isRegistered() { diff --git a/Signal.xcodeproj/project.pbxproj b/Signal.xcodeproj/project.pbxproj index cd70f99dd..a8ffc9c6c 100644 --- a/Signal.xcodeproj/project.pbxproj +++ b/Signal.xcodeproj/project.pbxproj @@ -159,7 +159,6 @@ 45C0DC1E1E69011F00E04C47 /* UIStoryboard+OWS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45C0DC1D1E69011F00E04C47 /* UIStoryboard+OWS.swift */; }; 45CB2FA81CB7146C00E1B343 /* Launch Screen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 45CB2FA71CB7146C00E1B343 /* Launch Screen.storyboard */; }; 45CD81EF1DC030E7004C9430 /* SyncPushTokensJob.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45CD81EE1DC030E7004C9430 /* SyncPushTokensJob.swift */; }; - 45D231771DC7E8F10034FA89 /* SessionResetJob.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45D231761DC7E8F10034FA89 /* SessionResetJob.swift */; }; 45E5A6991F61E6DE001E4A8A /* MarqueeLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45E5A6981F61E6DD001E4A8A /* MarqueeLabel.swift */; }; 45F32C222057297A00A300D5 /* MediaDetailViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 45B9EE9B200E91FB005D2F2D /* MediaDetailViewController.m */; }; 45F32C232057297A00A300D5 /* MediaPageViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45F32C1D205718B000A300D5 /* MediaPageViewController.swift */; }; @@ -293,6 +292,11 @@ B8C2B2C82563685C00551B4D /* CircleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8C2B2C72563685C00551B4D /* CircleView.swift */; }; B8C2B332256376F000551B4D /* ThreadUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = B8C2B331256376F000551B4D /* ThreadUtil.m */; }; B8C2B3442563782400551B4D /* ThreadUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = B8C2B33B2563770800551B4D /* ThreadUtil.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B8CA010125A293260091AF73 /* ClosedGroupSenderKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8CA010025A293260091AF73 /* ClosedGroupSenderKey.swift */; }; + B8CA010B25A293530091AF73 /* ClosedGroupRatchet.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8CA010A25A293530091AF73 /* ClosedGroupRatchet.swift */; }; + B8CA011525A293800091AF73 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8CA011425A293800091AF73 /* Configuration.swift */; }; + B8CA011F25A2939F0091AF73 /* SharedSenderKeys.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8CA011E25A2939F0091AF73 /* SharedSenderKeys.swift */; }; + B8CA014125A293EE0091AF73 /* Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8CA014025A293EE0091AF73 /* Storage.swift */; }; B8CCF6352396005F0091D419 /* SpaceMono-Regular.ttf in Resources */ = {isa = PBXBuildFile; fileRef = B8CCF6342396005F0091D419 /* SpaceMono-Regular.ttf */; }; B8CCF63723961D6D0091D419 /* NewPrivateChatVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8CCF63623961D6D0091D419 /* NewPrivateChatVC.swift */; }; B8CCF63F23975CFB0091D419 /* JoinPublicChatVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8CCF63E23975CFB0091D419 /* JoinPublicChatVC.swift */; }; @@ -301,7 +305,6 @@ B9EB5ABD1884C002007CBB57 /* MessageUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B9EB5ABC1884C002007CBB57 /* MessageUI.framework */; }; C300A5B22554AF9800555489 /* VisibleMessage+Profile.swift in Sources */ = {isa = PBXBuildFile; fileRef = C300A5B12554AF9800555489 /* VisibleMessage+Profile.swift */; }; C300A5BD2554B00D00555489 /* ReadReceipt.swift in Sources */ = {isa = PBXBuildFile; fileRef = C300A5BC2554B00D00555489 /* ReadReceipt.swift */; }; - C300A5C92554B04E00555489 /* SessionRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = C300A5C82554B04E00555489 /* SessionRequest.swift */; }; C300A5D32554B05A00555489 /* TypingIndicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = C300A5D22554B05A00555489 /* TypingIndicator.swift */; }; C300A5DD2554B06600555489 /* ClosedGroupUpdate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C300A5DC2554B06600555489 /* ClosedGroupUpdate.swift */; }; C300A5E72554B07300555489 /* ExpirationTimerUpdate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C300A5E62554B07300555489 /* ExpirationTimerUpdate.swift */; }; @@ -377,7 +380,6 @@ C32C5C4F256DCC36003C73A2 /* Storage+OpenGroups.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8D8F18825661BA50092EF10 /* Storage+OpenGroups.swift */; }; C32C5C88256DD0D2003C73A2 /* Storage+Messaging.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8D8F19225661BF80092EF10 /* Storage+Messaging.swift */; }; C32C5C89256DD0D2003C73A2 /* Storage+Jobs.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8D8F17625661AFA0092EF10 /* Storage+Jobs.swift */; }; - C32C5C93256DD12D003C73A2 /* OWSUDManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = C32C5C92256DD12D003C73A2 /* OWSUDManager.swift */; }; C32C5CA4256DD1DC003C73A2 /* TSAccountManager.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB88255A581200E217F9 /* TSAccountManager.m */; }; C32C5CAD256DD1DF003C73A2 /* TSAccountManager.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDB94255A581300E217F9 /* TSAccountManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; C32C5CBE256DD282003C73A2 /* Storage+OnionRequests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8D8F1BC25661C6F0092EF10 /* Storage+OnionRequests.swift */; }; @@ -417,10 +419,6 @@ C32C5F1A256DFCAD003C73A2 /* TSErrorMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDAE7255A580500E217F9 /* TSErrorMessage.m */; }; C32C5F23256DFCC0003C73A2 /* TSErrorMessage_privateConstructor.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDB5D255A580E00E217F9 /* TSErrorMessage_privateConstructor.h */; settings = {ATTRIBUTES = (Public, ); }; }; C32C5F34256DFCC4003C73A2 /* TSErrorMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDBB0255A581500E217F9 /* TSErrorMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C32C5F45256DFD2B003C73A2 /* TSInvalidIdentityKeyReceivingErrorMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDBCB255A581800E217F9 /* TSInvalidIdentityKeyReceivingErrorMessage.m */; }; - C32C5F4E256DFD58003C73A2 /* TSInvalidIdentityKeyReceivingErrorMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDA7B255A57FB00E217F9 /* TSInvalidIdentityKeyReceivingErrorMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C32C5F5F256DFD90003C73A2 /* TSInvalidIdentityKeyErrorMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB74255A581000E217F9 /* TSInvalidIdentityKeyErrorMessage.m */; }; - C32C5F68256DFDAA003C73A2 /* TSInvalidIdentityKeyErrorMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDB8C255A581200E217F9 /* TSInvalidIdentityKeyErrorMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; C32C5FA1256DFED5003C73A2 /* NSArray+Functional.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDAB8255A580100E217F9 /* NSArray+Functional.m */; }; C32C5FAA256DFED9003C73A2 /* NSArray+Functional.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDB5C255A580E00E217F9 /* NSArray+Functional.h */; settings = {ATTRIBUTES = (Public, ); }; }; C32C5FBB256E0206003C73A2 /* OWSBackgroundTask.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDC1B255A581F00E217F9 /* OWSBackgroundTask.m */; }; @@ -467,10 +465,8 @@ C33FDC39255A581F00E217F9 /* OWSRecordTranscriptJob.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDA7F255A57FC00E217F9 /* OWSRecordTranscriptJob.m */; }; C33FDC45255A581F00E217F9 /* AppVersion.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDA8B255A57FD00E217F9 /* AppVersion.m */; }; C33FDC50255A582000E217F9 /* OWSDispatch.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDA96255A57FE00E217F9 /* OWSDispatch.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C33FDC52255A582000E217F9 /* RotateSignedKeyOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDA98255A57FE00E217F9 /* RotateSignedKeyOperation.swift */; }; C33FDC53255A582000E217F9 /* OutageDetection.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDA99255A57FE00E217F9 /* OutageDetection.swift */; }; C33FDC58255A582000E217F9 /* ReverseDispatchQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDA9E255A57FF00E217F9 /* ReverseDispatchQueue.swift */; }; - C33FDC61255A582000E217F9 /* OWSPrimaryStorage+SignedPreKeyStore.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDAA7255A57FF00E217F9 /* OWSPrimaryStorage+SignedPreKeyStore.h */; settings = {ATTRIBUTES = (Public, ); }; }; C33FDC64255A582000E217F9 /* NSObject+Casting.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDAAA255A580000E217F9 /* NSObject+Casting.m */; }; C33FDC71255A582000E217F9 /* OWSFailedMessagesJob.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDAB7255A580100E217F9 /* OWSFailedMessagesJob.m */; }; C33FDC78255A582000E217F9 /* TSConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDABE255A580100E217F9 /* TSConstants.m */; }; @@ -483,43 +479,29 @@ C33FDC99255A582000E217F9 /* PublicChatManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDADF255A580400E217F9 /* PublicChatManager.swift */; }; C33FDC9A255A582000E217F9 /* ByteParser.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDAE0255A580400E217F9 /* ByteParser.m */; }; C33FDCA2255A582000E217F9 /* OWSMessageUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDAE8255A580500E217F9 /* OWSMessageUtils.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C33FDCAD255A582000E217F9 /* OWSPrimaryStorage+SessionStore.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDAF3255A580500E217F9 /* OWSPrimaryStorage+SessionStore.m */; }; - C33FDCB1255A582000E217F9 /* OWSPrimaryStorage+SignedPreKeyStore.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDAF7255A580600E217F9 /* OWSPrimaryStorage+SignedPreKeyStore.m */; }; - C33FDCBD255A582000E217F9 /* OWSPrimaryStorage+SessionStore.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDB03255A580700E217F9 /* OWSPrimaryStorage+SessionStore.h */; settings = {ATTRIBUTES = (Public, ); }; }; C33FDCC7255A582000E217F9 /* NSArray+OWS.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB0D255A580800E217F9 /* NSArray+OWS.m */; }; C33FDCD1255A582000E217F9 /* FunctionalUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB17255A580800E217F9 /* FunctionalUtil.m */; }; C33FDCD3255A582000E217F9 /* GroupUtilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB19255A580900E217F9 /* GroupUtilities.swift */; }; C33FDCFA255A582000E217F9 /* SignalIOSProto.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB40255A580C00E217F9 /* SignalIOSProto.swift */; }; - C33FDD01255A582000E217F9 /* OWSPrimaryStorage+PreKeyStore.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDB47255A580C00E217F9 /* OWSPrimaryStorage+PreKeyStore.h */; settings = {ATTRIBUTES = (Public, ); }; }; C33FDD03255A582000E217F9 /* WeakTimer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB49255A580C00E217F9 /* WeakTimer.swift */; }; C33FDD06255A582000E217F9 /* AppVersion.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDB4C255A580D00E217F9 /* AppVersion.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C33FDD0A255A582000E217F9 /* OWSPrimaryStorage+PreKeyStore.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB50255A580D00E217F9 /* OWSPrimaryStorage+PreKeyStore.m */; }; - C33FDD0D255A582000E217F9 /* PreKeyBundle+jsonDict.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDB53255A580D00E217F9 /* PreKeyBundle+jsonDict.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C33FDD0F255A582000E217F9 /* TSInvalidIdentityKeySendingErrorMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB55255A580D00E217F9 /* TSInvalidIdentityKeySendingErrorMessage.m */; }; C33FDD12255A582000E217F9 /* OWSPrimaryStorage+Loki.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB58255A580E00E217F9 /* OWSPrimaryStorage+Loki.m */; }; C33FDD13255A582000E217F9 /* OWSFailedAttachmentDownloadsJob.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB59255A580E00E217F9 /* OWSFailedAttachmentDownloadsJob.m */; }; - C33FDD14255A582000E217F9 /* OWSUDManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB5A255A580E00E217F9 /* OWSUDManager.swift */; }; - C33FDD1E255A582000E217F9 /* PreKeyRefreshOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB64255A580E00E217F9 /* PreKeyRefreshOperation.swift */; }; C33FDD23255A582000E217F9 /* FeatureFlags.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB69255A580F00E217F9 /* FeatureFlags.swift */; }; - C33FDD27255A582000E217F9 /* TSPreKeyManager.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDB6D255A580F00E217F9 /* TSPreKeyManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; C33FDD32255A582000E217F9 /* OWSOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB78255A581000E217F9 /* OWSOperation.m */; }; - C33FDD38255A582000E217F9 /* TSPreKeyManager.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB7E255A581100E217F9 /* TSPreKeyManager.m */; }; C33FDD3A255A582000E217F9 /* Notification+Loki.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB80255A581100E217F9 /* Notification+Loki.swift */; }; C33FDD41255A582000E217F9 /* JobQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB87255A581100E217F9 /* JobQueue.swift */; }; C33FDD45255A582000E217F9 /* Storage+SessionManagement.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB8B255A581200E217F9 /* Storage+SessionManagement.swift */; }; C33FDD49255A582000E217F9 /* ParamParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB8F255A581200E217F9 /* ParamParser.swift */; }; - C33FDD4D255A582000E217F9 /* PreKeyBundle+jsonDict.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB93255A581200E217F9 /* PreKeyBundle+jsonDict.m */; }; C33FDD53255A582000E217F9 /* OWSPrimaryStorage+keyFromIntLong.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDB99255A581300E217F9 /* OWSPrimaryStorage+keyFromIntLong.m */; }; C33FDD5A255A582000E217F9 /* TSStorageHeaders.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDBA0255A581400E217F9 /* TSStorageHeaders.h */; settings = {ATTRIBUTES = (Public, ); }; }; C33FDD5B255A582000E217F9 /* OWSOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDBA1255A581400E217F9 /* OWSOperation.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C33FDD60255A582000E217F9 /* TSInvalidIdentityKeySendingErrorMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDBA6255A581400E217F9 /* TSInvalidIdentityKeySendingErrorMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; C33FDD67255A582000E217F9 /* OWSRecordTranscriptJob.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDBAD255A581500E217F9 /* OWSRecordTranscriptJob.h */; settings = {ATTRIBUTES = (Public, ); }; }; C33FDD68255A582000E217F9 /* SignalAccount.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDBAE255A581500E217F9 /* SignalAccount.h */; settings = {ATTRIBUTES = (Public, ); }; }; C33FDD6E255A582000E217F9 /* NSURLSessionDataTask+StatusCode.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDBB4255A581600E217F9 /* NSURLSessionDataTask+StatusCode.m */; }; C33FDD74255A582000E217F9 /* OWSPrimaryStorage+keyFromIntLong.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDBBA255A581600E217F9 /* OWSPrimaryStorage+keyFromIntLong.h */; settings = {ATTRIBUTES = (Public, ); }; }; C33FDD75255A582000E217F9 /* OWSPrimaryStorage+Loki.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDBBB255A581600E217F9 /* OWSPrimaryStorage+Loki.h */; settings = {ATTRIBUTES = (Public, ); }; }; C33FDD7C255A582000E217F9 /* SSKAsserts.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDBC2255A581700E217F9 /* SSKAsserts.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C33FDD83255A582000E217F9 /* CreatePreKeysOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDBC9255A581700E217F9 /* CreatePreKeysOperation.swift */; }; C33FDD8D255A582000E217F9 /* OWSSignalAddress.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDBD3255A581800E217F9 /* OWSSignalAddress.swift */; }; C33FDD91255A582000E217F9 /* OWSMessageUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDBD7255A581900E217F9 /* OWSMessageUtils.m */; }; C33FDD92255A582000E217F9 /* SignalIOS.pb.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDBD8255A581900E217F9 /* SignalIOS.pb.swift */; }; @@ -535,7 +517,6 @@ C33FDDCD255A582000E217F9 /* OWSAttachmentDownloads.m in Sources */ = {isa = PBXBuildFile; fileRef = C33FDC13255A581E00E217F9 /* OWSAttachmentDownloads.m */; }; C33FDDD0255A582000E217F9 /* FunctionalUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDC16255A581E00E217F9 /* FunctionalUtil.h */; settings = {ATTRIBUTES = (Public, ); }; }; C33FDDD3255A582000E217F9 /* OWSQueues.h in Headers */ = {isa = PBXBuildFile; fileRef = C33FDC19255A581F00E217F9 /* OWSQueues.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C33FDDD9255A582000E217F9 /* LokiSessionRestorationImplementation.swift in Sources */ = {isa = PBXBuildFile; fileRef = C33FDC1F255A581F00E217F9 /* LokiSessionRestorationImplementation.swift */; }; C33FDEF8255A656D00E217F9 /* Promise+Delaying.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A5D32553860900C340D1 /* Promise+Delaying.swift */; }; C3402FE52559036600EA6424 /* SessionUIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C331FF1B2558F9D300070591 /* SessionUIKit.framework */; }; C3471ECB2555356A00297E91 /* MessageSender+Encryption.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3471ECA2555356A00297E91 /* MessageSender+Encryption.swift */; }; @@ -730,22 +711,8 @@ C3A71D0B2558989C0043A11F /* MessageWrapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D0A2558989C0043A11F /* MessageWrapper.swift */; }; C3A71D1E25589AC30043A11F /* WebSocketProto.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D1C25589AC30043A11F /* WebSocketProto.swift */; }; C3A71D1F25589AC30043A11F /* WebSocketResources.pb.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D1D25589AC30043A11F /* WebSocketResources.pb.swift */; }; - C3A71D2925589EBF0043A11F /* SessionRestorationProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D2825589EBF0043A11F /* SessionRestorationProtocol.swift */; }; - C3A71D3B25589F2B0043A11F /* SessionRestorationStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D3A25589F2B0043A11F /* SessionRestorationStatus.swift */; }; - C3A71D5025589FF30043A11F /* SMKUDAccessKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4425589FF10043A11F /* SMKUDAccessKey.swift */; }; - C3A71D5225589FF30043A11F /* SMKError.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4625589FF10043A11F /* SMKError.swift */; }; C3A71D5425589FF30043A11F /* NSData+messagePadding.m in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4825589FF20043A11F /* NSData+messagePadding.m */; }; - C3A71D5525589FF30043A11F /* SMKSenderCertificate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4925589FF20043A11F /* SMKSenderCertificate.swift */; }; - C3A71D5625589FF30043A11F /* SMKServerCertificate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4A25589FF20043A11F /* SMKServerCertificate.swift */; }; - C3A71D5725589FF30043A11F /* SMKCertificateValidator.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4B25589FF20043A11F /* SMKCertificateValidator.swift */; }; - C3A71D5825589FF30043A11F /* SMKSecretSessionCipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4C25589FF30043A11F /* SMKSecretSessionCipher.swift */; }; - C3A71D5925589FF30043A11F /* SMKUnidentifiedSenderMessageContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4D25589FF30043A11F /* SMKUnidentifiedSenderMessageContent.swift */; }; C3A71D5A25589FF30043A11F /* NSData+messagePadding.h in Headers */ = {isa = PBXBuildFile; fileRef = C3A71D4E25589FF30043A11F /* NSData+messagePadding.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3A71D5B25589FF30043A11F /* SMKUnidentifiedSenderMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D4F25589FF30043A11F /* SMKUnidentifiedSenderMessage.swift */; }; - C3A71D672558A0170043A11F /* FallbackSessionCipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D642558A0170043A11F /* FallbackSessionCipher.swift */; }; - C3A71D682558A0170043A11F /* LokiSessionCipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D652558A0170043A11F /* LokiSessionCipher.swift */; }; - C3A71D742558A0F60043A11F /* SMKProto.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D722558A0F60043A11F /* SMKProto.swift */; }; - C3A71D752558A0F60043A11F /* OWSUnidentifiedDelivery.pb.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D732558A0F60043A11F /* OWSUnidentifiedDelivery.pb.swift */; }; C3A71F892558BA9F0043A11F /* Mnemonic.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71F882558BA9F0043A11F /* Mnemonic.swift */; }; C3A7211A2558BCA10043A11F /* DiffieHellman.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A71D662558A0170043A11F /* DiffieHellman.swift */; }; C3A721382558BDFA0043A11F /* OpenGroupMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A721342558BDF90043A11F /* OpenGroupMessage.swift */; }; @@ -797,82 +764,14 @@ C3C2A7852553AAF300C340D1 /* SessionProtos.pb.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A7832553AAF300C340D1 /* SessionProtos.pb.swift */; }; C3C2A8662553B41A00C340D1 /* SessionProtocolKit.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8642553B41A00C340D1 /* SessionProtocolKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; C3C2A86A2553B41A00C340D1 /* SessionProtocolKit.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = C3C2A8622553B41A00C340D1 /* SessionProtocolKit.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - C3C2A8882553B4CC00C340D1 /* AxolotlExceptions.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8872553B4CC00C340D1 /* AxolotlExceptions.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A89C2553B4F600C340D1 /* PreKeyWhisperMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8932553B4F500C340D1 /* PreKeyWhisperMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A89D2553B4F600C340D1 /* ClosedGroupCiphertextMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8942553B4F500C340D1 /* ClosedGroupCiphertextMessage.m */; }; - C3C2A89E2553B4F600C340D1 /* WhisperMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8952553B4F500C340D1 /* WhisperMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A89F2553B4F600C340D1 /* ClosedGroupCiphertextMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8962553B4F500C340D1 /* ClosedGroupCiphertextMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A8A02553B4F600C340D1 /* PreKeyWhisperMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8972553B4F500C340D1 /* PreKeyWhisperMessage.m */; }; - C3C2A8A12553B4F600C340D1 /* WhisperMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8982553B4F600C340D1 /* WhisperMessage.m */; }; - C3C2A8A22553B4F600C340D1 /* CipherMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8992553B4F600C340D1 /* CipherMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A8A32553B4F600C340D1 /* FallbackMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A89A2553B4F600C340D1 /* FallbackMessage.m */; }; - C3C2A8A42553B4F600C340D1 /* FallbackMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A89B2553B4F600C340D1 /* FallbackMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A8B62553B53800C340D1 /* Constants.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8B52553B53700C340D1 /* Constants.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A8C22553B55600C340D1 /* AES-CBC.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8C02553B55600C340D1 /* AES-CBC.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A8C32553B55600C340D1 /* AES-CBC.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8C12553B55600C340D1 /* AES-CBC.m */; }; - C3C2A8D42553B57C00C340D1 /* SignedPrekeyRecord.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8CE2553B57C00C340D1 /* SignedPrekeyRecord.m */; }; - C3C2A8D52553B57C00C340D1 /* PreKeyBundle.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8CF2553B57C00C340D1 /* PreKeyBundle.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A8D62553B57C00C340D1 /* PreKeyBundle.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8D02553B57C00C340D1 /* PreKeyBundle.m */; }; - C3C2A8D72553B57C00C340D1 /* SignedPrekeyRecord.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8D12553B57C00C340D1 /* SignedPrekeyRecord.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A8D82553B57C00C340D1 /* PreKeyRecord.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8D22553B57C00C340D1 /* PreKeyRecord.m */; }; - C3C2A8D92553B57C00C340D1 /* PreKeyRecord.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8D32553B57C00C340D1 /* PreKeyRecord.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A8E62553B59B00C340D1 /* WhisperTextProtocol.pb.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8E42553B59B00C340D1 /* WhisperTextProtocol.pb.swift */; }; - C3C2A8E72553B59B00C340D1 /* SPKProto.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8E52553B59B00C340D1 /* SPKProto.swift */; }; - C3C2A9092553B5B200C340D1 /* RatchetingSession.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8F12553B5B000C340D1 /* RatchetingSession.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A90A2553B5B200C340D1 /* Chain.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8F22553B5B000C340D1 /* Chain.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A90B2553B5B200C340D1 /* MessageKeys.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8F32553B5B000C340D1 /* MessageKeys.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A90C2553B5B200C340D1 /* RKCK.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8F42553B5B000C340D1 /* RKCK.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A90D2553B5B200C340D1 /* RKCK.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8F52553B5B000C340D1 /* RKCK.m */; }; - C3C2A90E2553B5B200C340D1 /* TSDerivedSecrets.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8F62553B5B000C340D1 /* TSDerivedSecrets.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A90F2553B5B200C340D1 /* RatchetingSession.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8F72553B5B000C340D1 /* RatchetingSession.m */; }; - C3C2A9102553B5B200C340D1 /* AliceAxolotlParameters.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8F82553B5B000C340D1 /* AliceAxolotlParameters.m */; }; - C3C2A9112553B5B200C340D1 /* ChainKey.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8F92553B5B000C340D1 /* ChainKey.m */; }; - C3C2A9122553B5B200C340D1 /* ReceivingChain.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8FA2553B5B000C340D1 /* ReceivingChain.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9132553B5B200C340D1 /* RootKey.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8FB2553B5B000C340D1 /* RootKey.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9142553B5B200C340D1 /* ChainKey.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8FC2553B5B100C340D1 /* ChainKey.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9152553B5B200C340D1 /* BobAxolotlParameters.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8FD2553B5B100C340D1 /* BobAxolotlParameters.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9162553B5B200C340D1 /* ChainAndIndex.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A8FE2553B5B100C340D1 /* ChainAndIndex.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9172553B5B200C340D1 /* RootKey.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A8FF2553B5B100C340D1 /* RootKey.m */; }; - C3C2A9182553B5B200C340D1 /* SendingChain.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9002553B5B100C340D1 /* SendingChain.m */; }; - C3C2A9192553B5B200C340D1 /* MessageKeys.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9012553B5B100C340D1 /* MessageKeys.m */; }; - C3C2A91A2553B5B200C340D1 /* TSDerivedSecrets.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9022553B5B100C340D1 /* TSDerivedSecrets.m */; }; - C3C2A91B2553B5B200C340D1 /* BobAxolotlParameters.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9032553B5B100C340D1 /* BobAxolotlParameters.m */; }; - C3C2A91C2553B5B200C340D1 /* ReceivingChain.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9042553B5B100C340D1 /* ReceivingChain.m */; }; - C3C2A91D2553B5B200C340D1 /* AliceAxolotlParameters.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9052553B5B200C340D1 /* AliceAxolotlParameters.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A91E2553B5B200C340D1 /* ChainAndIndex.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9062553B5B200C340D1 /* ChainAndIndex.m */; }; - C3C2A91F2553B5B200C340D1 /* AxolotlParameters.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9072553B5B200C340D1 /* AxolotlParameters.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9202553B5B200C340D1 /* SendingChain.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9082553B5B200C340D1 /* SendingChain.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A92B2553B5BE00C340D1 /* SessionCipher.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9292553B5BD00C340D1 /* SessionCipher.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A92C2553B5BE00C340D1 /* SessionCipher.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A92A2553B5BE00C340D1 /* SessionCipher.m */; }; - C3C2A93C2553B5D700C340D1 /* SessionBuilder.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9362553B5D600C340D1 /* SessionBuilder.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A93D2553B5D700C340D1 /* SessionBuilder.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9372553B5D600C340D1 /* SessionBuilder.m */; }; - C3C2A93E2553B5D700C340D1 /* SessionRecord.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9382553B5D600C340D1 /* SessionRecord.m */; }; - C3C2A93F2553B5D700C340D1 /* SessionState.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A9392553B5D600C340D1 /* SessionState.m */; }; - C3C2A9402553B5D700C340D1 /* SessionRecord.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A93A2553B5D600C340D1 /* SessionRecord.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9412553B5D700C340D1 /* SessionState.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A93B2553B5D700C340D1 /* SessionState.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A95C2553B62400C340D1 /* AxolotlStore.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9572553B62300C340D1 /* AxolotlStore.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A95D2553B62400C340D1 /* PreKeyStore.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9582553B62400C340D1 /* PreKeyStore.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A95E2553B62400C340D1 /* IdentityKeyStore.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A9592553B62400C340D1 /* IdentityKeyStore.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A95F2553B62400C340D1 /* SessionStore.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A95A2553B62400C340D1 /* SessionStore.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9602553B62400C340D1 /* SignedPreKeyStore.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A95B2553B62400C340D1 /* SignedPreKeyStore.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A96E2553B63C00C340D1 /* NSData+keyVersionByte.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A96A2553B63B00C340D1 /* NSData+keyVersionByte.m */; }; - C3C2A96F2553B63C00C340D1 /* NSData+keyVersionByte.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A96B2553B63C00C340D1 /* NSData+keyVersionByte.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9702553B63C00C340D1 /* SerializationUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = C3C2A96C2553B63C00C340D1 /* SerializationUtilities.h */; settings = {ATTRIBUTES = (Public, ); }; }; - C3C2A9712553B63C00C340D1 /* SerializationUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = C3C2A96D2553B63C00C340D1 /* SerializationUtilities.m */; }; C3C2AAC82553C25300C340D1 /* SessionProtocolKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C3C2A8622553B41A00C340D1 /* SessionProtocolKit.framework */; }; - C3C2AB642553C5FF00C340D1 /* SharedSenderKeys.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2AB632553C5FF00C340D1 /* SharedSenderKeys.swift */; }; C3C2ABD22553C6C900C340D1 /* Data+SecureRandom.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2ABD12553C6C900C340D1 /* Data+SecureRandom.swift */; }; - C3C2ABE42553C74400C340D1 /* ClosedGroupRatchet.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2ABE32553C74400C340D1 /* ClosedGroupRatchet.swift */; }; - C3C2ABEE2553C76900C340D1 /* ClosedGroupSenderKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2ABED2553C76900C340D1 /* ClosedGroupSenderKey.swift */; }; - C3C2ABF82553C8A300C340D1 /* Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2ABF72553C8A300C340D1 /* Storage.swift */; }; - C3C2AC0A2553C9A100C340D1 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2AC092553C9A100C340D1 /* Configuration.swift */; }; C3C2AC2E2553CBEB00C340D1 /* String+Trimming.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2AC2D2553CBEB00C340D1 /* String+Trimming.swift */; }; C3C2AC372553CCE600C340D1 /* SessionUtilitiesKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C3C2A679255388CC00C340D1 /* SessionUtilitiesKit.framework */; }; C3CA3AA2255CDADA00F4C6D4 /* english.txt in Resources */ = {isa = PBXBuildFile; fileRef = C3CA3AA1255CDADA00F4C6D4 /* english.txt */; }; C3CA3AB4255CDAE600F4C6D4 /* japanese.txt in Resources */ = {isa = PBXBuildFile; fileRef = C3CA3AB3255CDAE600F4C6D4 /* japanese.txt */; }; C3CA3ABE255CDB0D00F4C6D4 /* portuguese.txt in Resources */ = {isa = PBXBuildFile; fileRef = C3CA3ABD255CDB0D00F4C6D4 /* portuguese.txt */; }; C3CA3AC8255CDB2900F4C6D4 /* spanish.txt in Resources */ = {isa = PBXBuildFile; fileRef = C3CA3AC7255CDB2900F4C6D4 /* spanish.txt */; }; - C3CA3B2F255CF84E00F4C6D4 /* NullMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3CA3B2E255CF84E00F4C6D4 /* NullMessage.swift */; }; C3D0972B2510499C00F6E3E4 /* BackgroundPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3D0972A2510499C00F6E3E4 /* BackgroundPoller.swift */; }; C3D90A1125773888002C9DF5 /* Colors.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C39DD28724F3318C008590FC /* Colors.xcassets */; }; C3D90A5C25773A25002C9DF5 /* SessionUtilitiesKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C3C2A679255388CC00C340D1 /* SessionUtilitiesKit.framework */; }; @@ -1249,7 +1148,6 @@ 45C0DC1D1E69011F00E04C47 /* UIStoryboard+OWS.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIStoryboard+OWS.swift"; sourceTree = ""; }; 45CB2FA71CB7146C00E1B343 /* Launch Screen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = "Launch Screen.storyboard"; path = "Session/Signal/Launch Screen.storyboard"; sourceTree = SOURCE_ROOT; }; 45CD81EE1DC030E7004C9430 /* SyncPushTokensJob.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SyncPushTokensJob.swift; sourceTree = ""; }; - 45D231761DC7E8F10034FA89 /* SessionResetJob.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionResetJob.swift; sourceTree = ""; }; 45E5A6981F61E6DD001E4A8A /* MarqueeLabel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MarqueeLabel.swift; sourceTree = ""; }; 45F32C1D205718B000A300D5 /* MediaPageViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MediaPageViewController.swift; path = Session/Signal/MediaPageViewController.swift; sourceTree = SOURCE_ROOT; }; 4C043929220A9EC800BAEA63 /* VoiceNoteLock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceNoteLock.swift; sourceTree = ""; }; @@ -1399,6 +1297,11 @@ B8C2B331256376F000551B4D /* ThreadUtil.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ThreadUtil.m; sourceTree = ""; }; B8C2B33B2563770800551B4D /* ThreadUtil.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ThreadUtil.h; sourceTree = ""; }; B8C9689023FA1401005F64E0 /* AppMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppMode.swift; sourceTree = ""; }; + B8CA010025A293260091AF73 /* ClosedGroupSenderKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClosedGroupSenderKey.swift; sourceTree = ""; }; + B8CA010A25A293530091AF73 /* ClosedGroupRatchet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClosedGroupRatchet.swift; sourceTree = ""; }; + B8CA011425A293800091AF73 /* Configuration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = ""; }; + B8CA011E25A2939F0091AF73 /* SharedSenderKeys.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedSenderKeys.swift; sourceTree = ""; }; + B8CA014025A293EE0091AF73 /* Storage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Storage.swift; sourceTree = ""; }; B8CCF6342396005F0091D419 /* SpaceMono-Regular.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "SpaceMono-Regular.ttf"; sourceTree = ""; }; B8CCF63623961D6D0091D419 /* NewPrivateChatVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewPrivateChatVC.swift; sourceTree = ""; }; B8CCF638239721E20091D419 /* TabBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TabBar.swift; sourceTree = ""; }; @@ -1417,7 +1320,6 @@ C1A746BC424B531D8ED478F6 /* Pods-SessionUIKit.app store release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SessionUIKit.app store release.xcconfig"; path = "Pods/Target Support Files/Pods-SessionUIKit/Pods-SessionUIKit.app store release.xcconfig"; sourceTree = ""; }; C300A5B12554AF9800555489 /* VisibleMessage+Profile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "VisibleMessage+Profile.swift"; sourceTree = ""; }; C300A5BC2554B00D00555489 /* ReadReceipt.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReadReceipt.swift; sourceTree = ""; }; - C300A5C82554B04E00555489 /* SessionRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionRequest.swift; sourceTree = ""; }; C300A5D22554B05A00555489 /* TypingIndicator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TypingIndicator.swift; sourceTree = ""; }; C300A5DC2554B06600555489 /* ClosedGroupUpdate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClosedGroupUpdate.swift; sourceTree = ""; }; C300A5E62554B07300555489 /* ExpirationTimerUpdate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExpirationTimerUpdate.swift; sourceTree = ""; }; @@ -1435,7 +1337,6 @@ C329FEEB24F7277900B1C64C /* LightModeSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LightModeSheet.swift; sourceTree = ""; }; C32C5A87256DBCF9003C73A2 /* MessageReceiver+Handling.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MessageReceiver+Handling.swift"; sourceTree = ""; }; C32C5B3E256DC1DF003C73A2 /* TSQuotedMessage+Conversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "TSQuotedMessage+Conversion.swift"; sourceTree = ""; }; - C32C5C92256DD12D003C73A2 /* OWSUDManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OWSUDManager.swift; sourceTree = ""; }; C32C5FD5256E0346003C73A2 /* Notification+Thread.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Notification+Thread.swift"; sourceTree = ""; }; C33100132558FFC200070591 /* UIImage+Tinting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIImage+Tinting.swift"; sourceTree = ""; }; C33100272559000A00070591 /* UIView+Rendering.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIView+Rendering.swift"; sourceTree = ""; }; @@ -1460,7 +1361,6 @@ C33FDA75255A57FB00E217F9 /* OWSSyncManagerProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OWSSyncManagerProtocol.h; sourceTree = ""; }; C33FDA79255A57FB00E217F9 /* TSGroupThread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSGroupThread.h; sourceTree = ""; }; C33FDA7A255A57FB00E217F9 /* NSRegularExpression+SSK.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "NSRegularExpression+SSK.swift"; sourceTree = ""; }; - C33FDA7B255A57FB00E217F9 /* TSInvalidIdentityKeyReceivingErrorMessage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSInvalidIdentityKeyReceivingErrorMessage.h; sourceTree = ""; }; C33FDA7E255A57FB00E217F9 /* Mention.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mention.swift; sourceTree = ""; }; C33FDA7F255A57FC00E217F9 /* OWSRecordTranscriptJob.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OWSRecordTranscriptJob.m; sourceTree = ""; }; C33FDA80255A57FC00E217F9 /* OWSDisappearingMessagesJob.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OWSDisappearingMessagesJob.h; sourceTree = ""; }; @@ -1474,12 +1374,10 @@ C33FDA90255A57FD00E217F9 /* TSYapDatabaseObject.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSYapDatabaseObject.m; sourceTree = ""; }; C33FDA96255A57FE00E217F9 /* OWSDispatch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OWSDispatch.h; sourceTree = ""; }; C33FDA97255A57FE00E217F9 /* TSIncomingMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSIncomingMessage.m; sourceTree = ""; }; - C33FDA98255A57FE00E217F9 /* RotateSignedKeyOperation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RotateSignedKeyOperation.swift; sourceTree = ""; }; C33FDA99255A57FE00E217F9 /* OutageDetection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OutageDetection.swift; sourceTree = ""; }; C33FDA9E255A57FF00E217F9 /* ReverseDispatchQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReverseDispatchQueue.swift; sourceTree = ""; }; C33FDAA0255A57FF00E217F9 /* OWSRecipientIdentity.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OWSRecipientIdentity.h; sourceTree = ""; }; C33FDAA1255A57FF00E217F9 /* TSYapDatabaseObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSYapDatabaseObject.h; sourceTree = ""; }; - C33FDAA7255A57FF00E217F9 /* OWSPrimaryStorage+SignedPreKeyStore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "OWSPrimaryStorage+SignedPreKeyStore.h"; sourceTree = ""; }; C33FDAA8255A57FF00E217F9 /* BuildConfiguration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BuildConfiguration.swift; sourceTree = ""; }; C33FDAAA255A580000E217F9 /* NSObject+Casting.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSObject+Casting.m"; sourceTree = ""; }; C33FDAB1255A580000E217F9 /* OWSStorage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OWSStorage.m; sourceTree = ""; }; @@ -1516,15 +1414,12 @@ C33FDAEF255A580500E217F9 /* NSData+Image.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSData+Image.m"; sourceTree = ""; }; C33FDAF1255A580500E217F9 /* OWSThumbnailService.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OWSThumbnailService.swift; sourceTree = ""; }; C33FDAF2255A580500E217F9 /* ProxiedContentDownloader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ProxiedContentDownloader.swift; sourceTree = ""; }; - C33FDAF3255A580500E217F9 /* OWSPrimaryStorage+SessionStore.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "OWSPrimaryStorage+SessionStore.m"; sourceTree = ""; }; C33FDAF4255A580600E217F9 /* SSKEnvironment.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SSKEnvironment.m; sourceTree = ""; }; - C33FDAF7255A580600E217F9 /* OWSPrimaryStorage+SignedPreKeyStore.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "OWSPrimaryStorage+SignedPreKeyStore.m"; sourceTree = ""; }; C33FDAF9255A580600E217F9 /* TSContactThread.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSContactThread.m; sourceTree = ""; }; C33FDAFC255A580600E217F9 /* MIMETypeUtil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MIMETypeUtil.h; sourceTree = ""; }; C33FDAFD255A580600E217F9 /* LRUCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LRUCache.swift; sourceTree = ""; }; C33FDAFE255A580600E217F9 /* OWSStorage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OWSStorage.h; sourceTree = ""; }; C33FDB01255A580700E217F9 /* AppReadiness.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppReadiness.h; sourceTree = ""; }; - C33FDB03255A580700E217F9 /* OWSPrimaryStorage+SessionStore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "OWSPrimaryStorage+SessionStore.h"; sourceTree = ""; }; C33FDB07255A580700E217F9 /* OWSBackupFragment.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OWSBackupFragment.m; sourceTree = ""; }; C33FDB0A255A580700E217F9 /* TSGroupModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSGroupModel.h; sourceTree = ""; }; C33FDB0D255A580800E217F9 /* NSArray+OWS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSArray+OWS.m"; sourceTree = ""; }; @@ -1553,41 +1448,32 @@ C33FDB43255A580C00E217F9 /* YapDatabaseConnection+OWS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "YapDatabaseConnection+OWS.m"; sourceTree = ""; }; C33FDB45255A580C00E217F9 /* NSString+SSK.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+SSK.m"; sourceTree = ""; }; C33FDB46255A580C00E217F9 /* TSDatabaseView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSDatabaseView.m; sourceTree = ""; }; - C33FDB47255A580C00E217F9 /* OWSPrimaryStorage+PreKeyStore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "OWSPrimaryStorage+PreKeyStore.h"; sourceTree = ""; }; C33FDB48255A580C00E217F9 /* TSOutgoingMessage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSOutgoingMessage.h; sourceTree = ""; }; C33FDB49255A580C00E217F9 /* WeakTimer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WeakTimer.swift; sourceTree = ""; }; C33FDB4C255A580D00E217F9 /* AppVersion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppVersion.h; sourceTree = ""; }; C33FDB4F255A580D00E217F9 /* SSKJobRecord.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SSKJobRecord.h; sourceTree = ""; }; - C33FDB50255A580D00E217F9 /* OWSPrimaryStorage+PreKeyStore.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "OWSPrimaryStorage+PreKeyStore.m"; sourceTree = ""; }; C33FDB51255A580D00E217F9 /* NSUserDefaults+OWS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSUserDefaults+OWS.h"; sourceTree = ""; }; - C33FDB53255A580D00E217F9 /* PreKeyBundle+jsonDict.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "PreKeyBundle+jsonDict.h"; sourceTree = ""; }; C33FDB54255A580D00E217F9 /* DataSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DataSource.h; sourceTree = ""; }; - C33FDB55255A580D00E217F9 /* TSInvalidIdentityKeySendingErrorMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSInvalidIdentityKeySendingErrorMessage.m; sourceTree = ""; }; C33FDB56255A580D00E217F9 /* TSOutgoingMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSOutgoingMessage.m; sourceTree = ""; }; C33FDB58255A580E00E217F9 /* OWSPrimaryStorage+Loki.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "OWSPrimaryStorage+Loki.m"; sourceTree = ""; }; C33FDB59255A580E00E217F9 /* OWSFailedAttachmentDownloadsJob.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OWSFailedAttachmentDownloadsJob.m; sourceTree = ""; }; - C33FDB5A255A580E00E217F9 /* OWSUDManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OWSUDManager.swift; sourceTree = ""; }; C33FDB5B255A580E00E217F9 /* YapDatabaseTransaction+OWS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "YapDatabaseTransaction+OWS.m"; sourceTree = ""; }; C33FDB5C255A580E00E217F9 /* NSArray+Functional.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSArray+Functional.h"; sourceTree = ""; }; C33FDB5D255A580E00E217F9 /* TSErrorMessage_privateConstructor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSErrorMessage_privateConstructor.h; sourceTree = ""; }; C33FDB5F255A580E00E217F9 /* YapDatabaseConnection+OWS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "YapDatabaseConnection+OWS.h"; sourceTree = ""; }; C33FDB60255A580E00E217F9 /* TSMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSMessage.m; sourceTree = ""; }; - C33FDB64255A580E00E217F9 /* PreKeyRefreshOperation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PreKeyRefreshOperation.swift; sourceTree = ""; }; C33FDB67255A580F00E217F9 /* OWSMediaGalleryFinder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OWSMediaGalleryFinder.h; sourceTree = ""; }; C33FDB68255A580F00E217F9 /* ContentProxy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ContentProxy.swift; sourceTree = ""; }; C33FDB69255A580F00E217F9 /* FeatureFlags.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FeatureFlags.swift; sourceTree = ""; }; C33FDB6B255A580F00E217F9 /* LKUserDefaults.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LKUserDefaults.swift; sourceTree = ""; }; C33FDB6C255A580F00E217F9 /* NSNotificationCenter+OWS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSNotificationCenter+OWS.m"; sourceTree = ""; }; - C33FDB6D255A580F00E217F9 /* TSPreKeyManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSPreKeyManager.h; sourceTree = ""; }; C33FDB6F255A580F00E217F9 /* OWSOutgoingReceiptManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OWSOutgoingReceiptManager.m; sourceTree = ""; }; C33FDB71255A581000E217F9 /* OWSMediaGalleryFinder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OWSMediaGalleryFinder.m; sourceTree = ""; }; C33FDB73255A581000E217F9 /* TSGroupModel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSGroupModel.m; sourceTree = ""; }; - C33FDB74255A581000E217F9 /* TSInvalidIdentityKeyErrorMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSInvalidIdentityKeyErrorMessage.m; sourceTree = ""; }; C33FDB75255A581000E217F9 /* AppReadiness.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppReadiness.m; sourceTree = ""; }; C33FDB77255A581000E217F9 /* NSUserDefaults+OWS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSUserDefaults+OWS.m"; sourceTree = ""; }; C33FDB78255A581000E217F9 /* OWSOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OWSOperation.m; sourceTree = ""; }; C33FDB7A255A581000E217F9 /* NotificationsProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NotificationsProtocol.h; sourceTree = ""; }; - C33FDB7E255A581100E217F9 /* TSPreKeyManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSPreKeyManager.m; sourceTree = ""; }; C33FDB7F255A581100E217F9 /* FullTextSearchFinder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FullTextSearchFinder.swift; sourceTree = ""; }; C33FDB80255A581100E217F9 /* Notification+Loki.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Notification+Loki.swift"; sourceTree = ""; }; C33FDB81255A581100E217F9 /* UIImage+OWS.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImage+OWS.m"; sourceTree = ""; }; @@ -1597,10 +1483,8 @@ C33FDB88255A581200E217F9 /* TSAccountManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSAccountManager.m; sourceTree = ""; }; C33FDB8A255A581200E217F9 /* AppContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppContext.h; sourceTree = ""; }; C33FDB8B255A581200E217F9 /* Storage+SessionManagement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Storage+SessionManagement.swift"; sourceTree = ""; }; - C33FDB8C255A581200E217F9 /* TSInvalidIdentityKeyErrorMessage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSInvalidIdentityKeyErrorMessage.h; sourceTree = ""; }; C33FDB8F255A581200E217F9 /* ParamParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ParamParser.swift; sourceTree = ""; }; C33FDB91255A581200E217F9 /* ProtoUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ProtoUtils.h; sourceTree = ""; }; - C33FDB93255A581200E217F9 /* PreKeyBundle+jsonDict.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "PreKeyBundle+jsonDict.m"; sourceTree = ""; }; C33FDB94255A581300E217F9 /* TSAccountManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSAccountManager.h; sourceTree = ""; }; C33FDB99255A581300E217F9 /* OWSPrimaryStorage+keyFromIntLong.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "OWSPrimaryStorage+keyFromIntLong.m"; sourceTree = ""; }; C33FDB9C255A581300E217F9 /* TSIncomingMessage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSIncomingMessage.h; sourceTree = ""; }; @@ -1608,7 +1492,6 @@ C33FDBA0255A581400E217F9 /* TSStorageHeaders.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSStorageHeaders.h; sourceTree = ""; }; C33FDBA1255A581400E217F9 /* OWSOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OWSOperation.h; sourceTree = ""; }; C33FDBA4255A581400E217F9 /* OWSDisappearingMessagesConfiguration.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OWSDisappearingMessagesConfiguration.m; sourceTree = ""; }; - C33FDBA6255A581400E217F9 /* TSInvalidIdentityKeySendingErrorMessage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSInvalidIdentityKeySendingErrorMessage.h; sourceTree = ""; }; C33FDBA8255A581500E217F9 /* OWSLinkPreview.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OWSLinkPreview.swift; sourceTree = ""; }; C33FDBA9255A581500E217F9 /* OWSIdentityManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OWSIdentityManager.m; sourceTree = ""; }; C33FDBAB255A581500E217F9 /* OWSFileSystem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OWSFileSystem.h; sourceTree = ""; }; @@ -1625,9 +1508,7 @@ C33FDBBC255A581600E217F9 /* SSKKeychainStorage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SSKKeychainStorage.swift; sourceTree = ""; }; C33FDBC1255A581700E217F9 /* General.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = General.swift; sourceTree = ""; }; C33FDBC2255A581700E217F9 /* SSKAsserts.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SSKAsserts.h; sourceTree = ""; }; - C33FDBC9255A581700E217F9 /* CreatePreKeysOperation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CreatePreKeysOperation.swift; sourceTree = ""; }; C33FDBCA255A581700E217F9 /* LKGroupUtilities.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LKGroupUtilities.h; sourceTree = ""; }; - C33FDBCB255A581800E217F9 /* TSInvalidIdentityKeyReceivingErrorMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TSInvalidIdentityKeyReceivingErrorMessage.m; sourceTree = ""; }; C33FDBD3255A581800E217F9 /* OWSSignalAddress.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OWSSignalAddress.swift; sourceTree = ""; }; C33FDBD7255A581900E217F9 /* OWSMessageUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OWSMessageUtils.m; sourceTree = ""; }; C33FDBD8255A581900E217F9 /* SignalIOS.pb.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SignalIOS.pb.swift; sourceTree = ""; }; @@ -1657,7 +1538,6 @@ C33FDC18255A581F00E217F9 /* TSAttachmentPointer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TSAttachmentPointer.h; sourceTree = ""; }; C33FDC19255A581F00E217F9 /* OWSQueues.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OWSQueues.h; sourceTree = ""; }; C33FDC1B255A581F00E217F9 /* OWSBackgroundTask.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OWSBackgroundTask.m; sourceTree = ""; }; - C33FDC1F255A581F00E217F9 /* LokiSessionRestorationImplementation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LokiSessionRestorationImplementation.swift; sourceTree = ""; }; C3471ECA2555356A00297E91 /* MessageSender+Encryption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MessageSender+Encryption.swift"; sourceTree = ""; }; C3471F4B25553AB000297E91 /* MessageReceiver+Decryption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MessageReceiver+Decryption.swift"; sourceTree = ""; }; C3471FA32555439E00297E91 /* Notification+MessageSender.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Notification+MessageSender.swift"; sourceTree = ""; }; @@ -1861,23 +1741,9 @@ C3A71D0A2558989C0043A11F /* MessageWrapper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageWrapper.swift; sourceTree = ""; }; C3A71D1C25589AC30043A11F /* WebSocketProto.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WebSocketProto.swift; sourceTree = ""; }; C3A71D1D25589AC30043A11F /* WebSocketResources.pb.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WebSocketResources.pb.swift; sourceTree = ""; }; - C3A71D2825589EBF0043A11F /* SessionRestorationProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionRestorationProtocol.swift; sourceTree = ""; }; - C3A71D3A25589F2B0043A11F /* SessionRestorationStatus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionRestorationStatus.swift; sourceTree = ""; }; - C3A71D4425589FF10043A11F /* SMKUDAccessKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKUDAccessKey.swift; sourceTree = ""; }; - C3A71D4625589FF10043A11F /* SMKError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKError.swift; sourceTree = ""; }; C3A71D4825589FF20043A11F /* NSData+messagePadding.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSData+messagePadding.m"; sourceTree = ""; }; - C3A71D4925589FF20043A11F /* SMKSenderCertificate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKSenderCertificate.swift; sourceTree = ""; }; - C3A71D4A25589FF20043A11F /* SMKServerCertificate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKServerCertificate.swift; sourceTree = ""; }; - C3A71D4B25589FF20043A11F /* SMKCertificateValidator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKCertificateValidator.swift; sourceTree = ""; }; - C3A71D4C25589FF30043A11F /* SMKSecretSessionCipher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKSecretSessionCipher.swift; sourceTree = ""; }; - C3A71D4D25589FF30043A11F /* SMKUnidentifiedSenderMessageContent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKUnidentifiedSenderMessageContent.swift; sourceTree = ""; }; C3A71D4E25589FF30043A11F /* NSData+messagePadding.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSData+messagePadding.h"; sourceTree = ""; }; - C3A71D4F25589FF30043A11F /* SMKUnidentifiedSenderMessage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SMKUnidentifiedSenderMessage.swift; sourceTree = ""; }; - C3A71D642558A0170043A11F /* FallbackSessionCipher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FallbackSessionCipher.swift; sourceTree = ""; }; - C3A71D652558A0170043A11F /* LokiSessionCipher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LokiSessionCipher.swift; sourceTree = ""; }; C3A71D662558A0170043A11F /* DiffieHellman.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DiffieHellman.swift; sourceTree = ""; }; - C3A71D722558A0F60043A11F /* SMKProto.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SMKProto.swift; path = Protos/SMKProto.swift; sourceTree = ""; }; - C3A71D732558A0F60043A11F /* OWSUnidentifiedDelivery.pb.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = OWSUnidentifiedDelivery.pb.swift; path = Protos/OWSUnidentifiedDelivery.pb.swift; sourceTree = ""; }; C3A71F882558BA9F0043A11F /* Mnemonic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mnemonic.swift; sourceTree = ""; }; C3A721342558BDF90043A11F /* OpenGroupMessage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OpenGroupMessage.swift; sourceTree = ""; }; C3A721352558BDF90043A11F /* OpenGroupAPI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OpenGroupAPI.swift; sourceTree = ""; }; @@ -1936,81 +1802,13 @@ C3C2A8622553B41A00C340D1 /* SessionProtocolKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SessionProtocolKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; C3C2A8642553B41A00C340D1 /* SessionProtocolKit.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SessionProtocolKit.h; sourceTree = ""; }; C3C2A8652553B41A00C340D1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - C3C2A8872553B4CC00C340D1 /* AxolotlExceptions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AxolotlExceptions.h; sourceTree = ""; }; - C3C2A8932553B4F500C340D1 /* PreKeyWhisperMessage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PreKeyWhisperMessage.h; path = SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.h; sourceTree = SOURCE_ROOT; }; - C3C2A8942553B4F500C340D1 /* ClosedGroupCiphertextMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = ClosedGroupCiphertextMessage.m; path = SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.m; sourceTree = SOURCE_ROOT; }; - C3C2A8952553B4F500C340D1 /* WhisperMessage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = WhisperMessage.h; path = SessionProtocolKit/Signal/CipherMessage/WhisperMessage.h; sourceTree = SOURCE_ROOT; }; - C3C2A8962553B4F500C340D1 /* ClosedGroupCiphertextMessage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ClosedGroupCiphertextMessage.h; path = SessionProtocolKit/Signal/CipherMessage/ClosedGroupCiphertextMessage.h; sourceTree = SOURCE_ROOT; }; - C3C2A8972553B4F500C340D1 /* PreKeyWhisperMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = PreKeyWhisperMessage.m; path = SessionProtocolKit/Signal/CipherMessage/PreKeyWhisperMessage.m; sourceTree = SOURCE_ROOT; }; - C3C2A8982553B4F600C340D1 /* WhisperMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = WhisperMessage.m; path = SessionProtocolKit/Signal/CipherMessage/WhisperMessage.m; sourceTree = SOURCE_ROOT; }; - C3C2A8992553B4F600C340D1 /* CipherMessage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CipherMessage.h; path = SessionProtocolKit/Signal/CipherMessage/CipherMessage.h; sourceTree = SOURCE_ROOT; }; - C3C2A89A2553B4F600C340D1 /* FallbackMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FallbackMessage.m; path = SessionProtocolKit/Signal/CipherMessage/FallbackMessage.m; sourceTree = SOURCE_ROOT; }; - C3C2A89B2553B4F600C340D1 /* FallbackMessage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FallbackMessage.h; path = SessionProtocolKit/Signal/CipherMessage/FallbackMessage.h; sourceTree = SOURCE_ROOT; }; - C3C2A8B52553B53700C340D1 /* Constants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Constants.h; sourceTree = ""; }; - C3C2A8C02553B55600C340D1 /* AES-CBC.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "AES-CBC.h"; path = "Crypto/AES-CBC.h"; sourceTree = ""; }; - C3C2A8C12553B55600C340D1 /* AES-CBC.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "AES-CBC.m"; path = "Crypto/AES-CBC.m"; sourceTree = ""; }; - C3C2A8CE2553B57C00C340D1 /* SignedPrekeyRecord.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SignedPrekeyRecord.m; path = Prekeys/SignedPrekeyRecord.m; sourceTree = ""; }; - C3C2A8CF2553B57C00C340D1 /* PreKeyBundle.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PreKeyBundle.h; path = Prekeys/PreKeyBundle.h; sourceTree = ""; }; - C3C2A8D02553B57C00C340D1 /* PreKeyBundle.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = PreKeyBundle.m; path = Prekeys/PreKeyBundle.m; sourceTree = ""; }; - C3C2A8D12553B57C00C340D1 /* SignedPrekeyRecord.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SignedPrekeyRecord.h; path = Prekeys/SignedPrekeyRecord.h; sourceTree = ""; }; - C3C2A8D22553B57C00C340D1 /* PreKeyRecord.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = PreKeyRecord.m; path = Prekeys/PreKeyRecord.m; sourceTree = ""; }; - C3C2A8D32553B57C00C340D1 /* PreKeyRecord.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PreKeyRecord.h; path = Prekeys/PreKeyRecord.h; sourceTree = ""; }; - C3C2A8E42553B59B00C340D1 /* WhisperTextProtocol.pb.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = WhisperTextProtocol.pb.swift; path = Protos/WhisperTextProtocol.pb.swift; sourceTree = ""; }; - C3C2A8E52553B59B00C340D1 /* SPKProto.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SPKProto.swift; path = Protos/SPKProto.swift; sourceTree = ""; }; - C3C2A8F12553B5B000C340D1 /* RatchetingSession.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RatchetingSession.h; path = Ratchet/RatchetingSession.h; sourceTree = ""; }; - C3C2A8F22553B5B000C340D1 /* Chain.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Chain.h; path = Ratchet/Chain.h; sourceTree = ""; }; - C3C2A8F32553B5B000C340D1 /* MessageKeys.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = MessageKeys.h; path = Ratchet/MessageKeys.h; sourceTree = ""; }; - C3C2A8F42553B5B000C340D1 /* RKCK.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RKCK.h; path = Ratchet/RKCK.h; sourceTree = ""; }; - C3C2A8F52553B5B000C340D1 /* RKCK.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = RKCK.m; path = Ratchet/RKCK.m; sourceTree = ""; }; - C3C2A8F62553B5B000C340D1 /* TSDerivedSecrets.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TSDerivedSecrets.h; path = Ratchet/TSDerivedSecrets.h; sourceTree = ""; }; - C3C2A8F72553B5B000C340D1 /* RatchetingSession.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = RatchetingSession.m; path = Ratchet/RatchetingSession.m; sourceTree = ""; }; - C3C2A8F82553B5B000C340D1 /* AliceAxolotlParameters.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AliceAxolotlParameters.m; path = Ratchet/AliceAxolotlParameters.m; sourceTree = ""; }; - C3C2A8F92553B5B000C340D1 /* ChainKey.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = ChainKey.m; path = Ratchet/ChainKey.m; sourceTree = ""; }; - C3C2A8FA2553B5B000C340D1 /* ReceivingChain.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ReceivingChain.h; path = Ratchet/ReceivingChain.h; sourceTree = ""; }; - C3C2A8FB2553B5B000C340D1 /* RootKey.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RootKey.h; path = Ratchet/RootKey.h; sourceTree = ""; }; - C3C2A8FC2553B5B100C340D1 /* ChainKey.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ChainKey.h; path = Ratchet/ChainKey.h; sourceTree = ""; }; - C3C2A8FD2553B5B100C340D1 /* BobAxolotlParameters.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = BobAxolotlParameters.h; path = Ratchet/BobAxolotlParameters.h; sourceTree = ""; }; - C3C2A8FE2553B5B100C340D1 /* ChainAndIndex.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ChainAndIndex.h; path = Ratchet/ChainAndIndex.h; sourceTree = ""; }; - C3C2A8FF2553B5B100C340D1 /* RootKey.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = RootKey.m; path = Ratchet/RootKey.m; sourceTree = ""; }; - C3C2A9002553B5B100C340D1 /* SendingChain.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SendingChain.m; path = Ratchet/SendingChain.m; sourceTree = ""; }; - C3C2A9012553B5B100C340D1 /* MessageKeys.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = MessageKeys.m; path = Ratchet/MessageKeys.m; sourceTree = ""; }; - C3C2A9022553B5B100C340D1 /* TSDerivedSecrets.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = TSDerivedSecrets.m; path = Ratchet/TSDerivedSecrets.m; sourceTree = ""; }; - C3C2A9032553B5B100C340D1 /* BobAxolotlParameters.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = BobAxolotlParameters.m; path = Ratchet/BobAxolotlParameters.m; sourceTree = ""; }; - C3C2A9042553B5B100C340D1 /* ReceivingChain.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = ReceivingChain.m; path = Ratchet/ReceivingChain.m; sourceTree = ""; }; - C3C2A9052553B5B200C340D1 /* AliceAxolotlParameters.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AliceAxolotlParameters.h; path = Ratchet/AliceAxolotlParameters.h; sourceTree = ""; }; - C3C2A9062553B5B200C340D1 /* ChainAndIndex.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = ChainAndIndex.m; path = Ratchet/ChainAndIndex.m; sourceTree = ""; }; - C3C2A9072553B5B200C340D1 /* AxolotlParameters.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AxolotlParameters.h; path = Ratchet/AxolotlParameters.h; sourceTree = ""; }; - C3C2A9082553B5B200C340D1 /* SendingChain.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SendingChain.h; path = Ratchet/SendingChain.h; sourceTree = ""; }; - C3C2A9292553B5BD00C340D1 /* SessionCipher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SessionCipher.h; sourceTree = ""; }; - C3C2A92A2553B5BE00C340D1 /* SessionCipher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SessionCipher.m; sourceTree = ""; }; - C3C2A9362553B5D600C340D1 /* SessionBuilder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SessionBuilder.h; path = Sessions/SessionBuilder.h; sourceTree = ""; }; - C3C2A9372553B5D600C340D1 /* SessionBuilder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SessionBuilder.m; path = Sessions/SessionBuilder.m; sourceTree = ""; }; - C3C2A9382553B5D600C340D1 /* SessionRecord.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SessionRecord.m; path = Sessions/SessionRecord.m; sourceTree = ""; }; - C3C2A9392553B5D600C340D1 /* SessionState.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SessionState.m; path = Sessions/SessionState.m; sourceTree = ""; }; - C3C2A93A2553B5D600C340D1 /* SessionRecord.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SessionRecord.h; path = Sessions/SessionRecord.h; sourceTree = ""; }; - C3C2A93B2553B5D700C340D1 /* SessionState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SessionState.h; path = Sessions/SessionState.h; sourceTree = ""; }; - C3C2A9572553B62300C340D1 /* AxolotlStore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AxolotlStore.h; sourceTree = ""; }; - C3C2A9582553B62400C340D1 /* PreKeyStore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PreKeyStore.h; sourceTree = ""; }; - C3C2A9592553B62400C340D1 /* IdentityKeyStore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IdentityKeyStore.h; sourceTree = ""; }; - C3C2A95A2553B62400C340D1 /* SessionStore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SessionStore.h; sourceTree = ""; }; - C3C2A95B2553B62400C340D1 /* SignedPreKeyStore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SignedPreKeyStore.h; sourceTree = ""; }; - C3C2A96A2553B63B00C340D1 /* NSData+keyVersionByte.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSData+keyVersionByte.m"; path = "Utility/NSData+keyVersionByte.m"; sourceTree = ""; }; - C3C2A96B2553B63C00C340D1 /* NSData+keyVersionByte.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSData+keyVersionByte.h"; path = "Utility/NSData+keyVersionByte.h"; sourceTree = ""; }; - C3C2A96C2553B63C00C340D1 /* SerializationUtilities.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SerializationUtilities.h; path = Utility/SerializationUtilities.h; sourceTree = ""; }; - C3C2A96D2553B63C00C340D1 /* SerializationUtilities.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SerializationUtilities.m; path = Utility/SerializationUtilities.m; sourceTree = ""; }; - C3C2AB632553C5FF00C340D1 /* SharedSenderKeys.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedSenderKeys.swift; sourceTree = ""; }; C3C2ABD12553C6C900C340D1 /* Data+SecureRandom.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Data+SecureRandom.swift"; sourceTree = ""; }; - C3C2ABE32553C74400C340D1 /* ClosedGroupRatchet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClosedGroupRatchet.swift; sourceTree = ""; }; - C3C2ABED2553C76900C340D1 /* ClosedGroupSenderKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClosedGroupSenderKey.swift; sourceTree = ""; }; - C3C2ABF72553C8A300C340D1 /* Storage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Storage.swift; sourceTree = ""; }; - C3C2AC092553C9A100C340D1 /* Configuration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = ""; }; C3C2AC2D2553CBEB00C340D1 /* String+Trimming.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+Trimming.swift"; sourceTree = ""; }; C3C3CF8824D8EED300E1CCE7 /* TextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextView.swift; sourceTree = ""; }; C3CA3AA1255CDADA00F4C6D4 /* english.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = english.txt; sourceTree = ""; }; C3CA3AB3255CDAE600F4C6D4 /* japanese.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = japanese.txt; sourceTree = ""; }; C3CA3ABD255CDB0D00F4C6D4 /* portuguese.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = portuguese.txt; sourceTree = ""; }; C3CA3AC7255CDB2900F4C6D4 /* spanish.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = spanish.txt; sourceTree = ""; }; - C3CA3B2E255CF84E00F4C6D4 /* NullMessage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NullMessage.swift; sourceTree = ""; }; C3D0972A2510499C00F6E3E4 /* BackgroundPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackgroundPoller.swift; sourceTree = ""; }; C3D9E40B25676C100040E4F3 /* Storage+Conformances.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Storage+Conformances.swift"; sourceTree = ""; }; C3D9E41E25676C870040E4F3 /* OWSPrimaryStorageProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OWSPrimaryStorageProtocol.swift; sourceTree = ""; }; @@ -2347,7 +2145,6 @@ 346129971FD1E4D900532771 /* SignalApp.m */, 34C4E2552118957600BEA353 /* OWSWebRTCDataProtos.pb.swift */, 34C4E2562118957600BEA353 /* WebRTCProto.swift */, - 45D231761DC7E8F10034FA89 /* SessionResetJob.swift */, 45CD81EE1DC030E7004C9430 /* SyncPushTokensJob.swift */, 45CB2FA71CB7146C00E1B343 /* Launch Screen.storyboard */, A5509EC91A69AB8B00ABA4BC /* Main.storyboard */, @@ -2771,7 +2568,6 @@ C300A5C72554B03900555489 /* Control Messages */ = { isa = PBXGroup; children = ( - C379DD172567458A0002D4EB /* Unused */, C3C2A7702553A41E00C340D1 /* ControlMessage.swift */, C300A5BC2554B00D00555489 /* ReadReceipt.swift */, C300A5D22554B05A00555489 /* TypingIndicator.swift */, @@ -2882,10 +2678,6 @@ C33FDC0C255A581E00E217F9 /* TSInfoMessage.m */, C33FDAE6255A580400E217F9 /* TSInteraction.h */, C33FDBE9255A581A00E217F9 /* TSInteraction.m */, - C33FDB8C255A581200E217F9 /* TSInvalidIdentityKeyErrorMessage.h */, - C33FDB74255A581000E217F9 /* TSInvalidIdentityKeyErrorMessage.m */, - C33FDA7B255A57FB00E217F9 /* TSInvalidIdentityKeyReceivingErrorMessage.h */, - C33FDBCB255A581800E217F9 /* TSInvalidIdentityKeyReceivingErrorMessage.m */, C33FDA70255A57FA00E217F9 /* TSMessage.h */, C33FDB60255A580E00E217F9 /* TSMessage.m */, C33FDB48255A580C00E217F9 /* TSOutgoingMessage.h */, @@ -2952,7 +2744,6 @@ C33FDBEC255A581B00E217F9 /* OWSRecipientIdentity.m */, C38EF2D3255B6DAF007E1867 /* OWSUserProfile.h */, C38EF2D1255B6DAF007E1867 /* OWSUserProfile.m */, - C32C5C92256DD12D003C73A2 /* OWSUDManager.swift */, C33FDBB9255A581600E217F9 /* ProfileManagerProtocol.h */, C33FDAEC255A580500E217F9 /* SignalRecipient.h */, C33FDBB7255A581600E217F9 /* SignalRecipient.m */, @@ -3099,11 +2890,9 @@ C38EF287255B6D85007E1867 /* AppSetup.m */, B8856D5F256F129B001CE70E /* OWSAlerts.swift */, C3F0A52F255C80BC007BE2A3 /* NoopNotificationsManager.swift */, - C33FDC1F255A581F00E217F9 /* LokiSessionRestorationImplementation.swift */, C38EF283255B6D84007E1867 /* VersionMigrations.h */, C38EF286255B6D85007E1867 /* VersionMigrations.m */, C33FDA8B255A57FD00E217F9 /* AppVersion.m */, - C33FDBC9255A581700E217F9 /* CreatePreKeysOperation.swift */, C33FDB69255A580F00E217F9 /* FeatureFlags.swift */, C33FDB87255A581100E217F9 /* JobQueue.swift */, C33FDA99255A57FE00E217F9 /* OutageDetection.swift */, @@ -3124,20 +2913,13 @@ C33FDA7F255A57FC00E217F9 /* OWSRecordTranscriptJob.m */, C33FDBD3255A581800E217F9 /* OWSSignalAddress.swift */, C33FDA75255A57FB00E217F9 /* OWSSyncManagerProtocol.h */, - C33FDB5A255A580E00E217F9 /* OWSUDManager.swift */, - C33FDB53255A580D00E217F9 /* PreKeyBundle+jsonDict.h */, - C33FDB93255A581200E217F9 /* PreKeyBundle+jsonDict.m */, - C33FDB64255A580E00E217F9 /* PreKeyRefreshOperation.swift */, C33FDA6F255A57FA00E217F9 /* ReachabilityManager.swift */, - C33FDA98255A57FE00E217F9 /* RotateSignedKeyOperation.swift */, C33FDBAE255A581500E217F9 /* SignalAccount.h */, C33FDC06255A581D00E217F9 /* SignalAccount.m */, C33FDBD8255A581900E217F9 /* SignalIOS.pb.swift */, C33FDB40255A580C00E217F9 /* SignalIOSProto.swift */, C33FDC12255A581E00E217F9 /* TSConstants.h */, C33FDABE255A580100E217F9 /* TSConstants.m */, - C33FDB6D255A580F00E217F9 /* TSPreKeyManager.h */, - C33FDB7E255A581100E217F9 /* TSPreKeyManager.m */, ); path = SignalUtilitiesKit; sourceTree = ""; @@ -3235,15 +3017,6 @@ path = "Attachment Approval"; sourceTree = ""; }; - C379DD172567458A0002D4EB /* Unused */ = { - isa = PBXGroup; - children = ( - C300A5C82554B04E00555489 /* SessionRequest.swift */, - C3CA3B2E255CF84E00F4C6D4 /* NullMessage.swift */, - ); - path = Unused; - sourceTree = ""; - }; C3851CD225624B060061EEB0 /* UI */ = { isa = PBXGroup; children = ( @@ -3337,8 +3110,6 @@ C38BBA0D255E321C0041B9A3 /* Messaging */ = { isa = PBXGroup; children = ( - C33FDBA6255A581400E217F9 /* TSInvalidIdentityKeySendingErrorMessage.h */, - C33FDB55255A580D00E217F9 /* TSInvalidIdentityKeySendingErrorMessage.m */, C33FDAE8255A580500E217F9 /* OWSMessageUtils.h */, C33FDBD7255A581900E217F9 /* OWSMessageUtils.m */, ); @@ -3351,12 +3122,6 @@ C379DCE82567330E0002D4EB /* Migration */, C33FDBBA255A581600E217F9 /* OWSPrimaryStorage+keyFromIntLong.h */, C33FDB99255A581300E217F9 /* OWSPrimaryStorage+keyFromIntLong.m */, - C33FDB47255A580C00E217F9 /* OWSPrimaryStorage+PreKeyStore.h */, - C33FDB50255A580D00E217F9 /* OWSPrimaryStorage+PreKeyStore.m */, - C33FDB03255A580700E217F9 /* OWSPrimaryStorage+SessionStore.h */, - C33FDAF3255A580500E217F9 /* OWSPrimaryStorage+SessionStore.m */, - C33FDAA7255A57FF00E217F9 /* OWSPrimaryStorage+SignedPreKeyStore.h */, - C33FDAF7255A580600E217F9 /* OWSPrimaryStorage+SignedPreKeyStore.m */, C3D9E40B25676C100040E4F3 /* Storage+Conformances.swift */, C33FDB8B255A581200E217F9 /* Storage+SessionManagement.swift */, C38EF3D2255B6DEE007E1867 /* ThreadViewHelper.h */, @@ -3384,27 +3149,6 @@ path = SwiftCSV; sourceTree = ""; }; - C3A71DB12558B25F0043A11F /* Metadata */ = { - isa = PBXGroup; - children = ( - C3A71D4E25589FF30043A11F /* NSData+messagePadding.h */, - C3A71D4825589FF20043A11F /* NSData+messagePadding.m */, - C3A71D4B25589FF20043A11F /* SMKCertificateValidator.swift */, - C3A71D4625589FF10043A11F /* SMKError.swift */, - C3A71D4C25589FF30043A11F /* SMKSecretSessionCipher.swift */, - C3A71D4925589FF20043A11F /* SMKSenderCertificate.swift */, - C3A71D4A25589FF20043A11F /* SMKServerCertificate.swift */, - C3A71D4425589FF10043A11F /* SMKUDAccessKey.swift */, - C3A71D4F25589FF30043A11F /* SMKUnidentifiedSenderMessage.swift */, - C3A71D4D25589FF30043A11F /* SMKUnidentifiedSenderMessageContent.swift */, - C3A71D642558A0170043A11F /* FallbackSessionCipher.swift */, - C3A71D652558A0170043A11F /* LokiSessionCipher.swift */, - C3A71D2825589EBF0043A11F /* SessionRestorationProtocol.swift */, - C3A71D3A25589F2B0043A11F /* SessionRestorationStatus.swift */, - ); - name = Metadata; - sourceTree = ""; - }; C3A721332558BDDF0043A11F /* Open Groups */ = { isa = PBXGroup; children = ( @@ -3597,10 +3341,13 @@ isa = PBXGroup; children = ( C3C2A8762553B42C00C340D1 /* Meta */, - C3C2AC092553C9A100C340D1 /* Configuration.swift */, - C3C2ABF72553C8A300C340D1 /* Storage.swift */, - C3C2AB622553C5D400C340D1 /* Shared Sender Keys */, - C3C2AB492553C4A800C340D1 /* Signal */, + B8CA010A25A293530091AF73 /* ClosedGroupRatchet.swift */, + B8CA010025A293260091AF73 /* ClosedGroupSenderKey.swift */, + B8CA011425A293800091AF73 /* Configuration.swift */, + C3A71D4E25589FF30043A11F /* NSData+messagePadding.h */, + C3A71D4825589FF20043A11F /* NSData+messagePadding.m */, + B8CA011E25A2939F0091AF73 /* SharedSenderKeys.swift */, + B8CA014025A293EE0091AF73 /* Storage.swift */, ); path = SessionProtocolKit; sourceTree = ""; @@ -3614,152 +3361,6 @@ path = Meta; sourceTree = ""; }; - C3C2A8922553B4E400C340D1 /* CipherMessage */ = { - isa = PBXGroup; - children = ( - C3C2A8992553B4F600C340D1 /* CipherMessage.h */, - C3C2A8962553B4F500C340D1 /* ClosedGroupCiphertextMessage.h */, - C3C2A8942553B4F500C340D1 /* ClosedGroupCiphertextMessage.m */, - C3C2A89B2553B4F600C340D1 /* FallbackMessage.h */, - C3C2A89A2553B4F600C340D1 /* FallbackMessage.m */, - C3C2A8932553B4F500C340D1 /* PreKeyWhisperMessage.h */, - C3C2A8972553B4F500C340D1 /* PreKeyWhisperMessage.m */, - C3C2A8952553B4F500C340D1 /* WhisperMessage.h */, - C3C2A8982553B4F600C340D1 /* WhisperMessage.m */, - ); - path = CipherMessage; - sourceTree = ""; - }; - C3C2A8BF2553B54600C340D1 /* Crypto */ = { - isa = PBXGroup; - children = ( - C3C2A8C02553B55600C340D1 /* AES-CBC.h */, - C3C2A8C12553B55600C340D1 /* AES-CBC.m */, - ); - name = Crypto; - sourceTree = ""; - }; - C3C2A8CD2553B56400C340D1 /* Prekeys */ = { - isa = PBXGroup; - children = ( - C3C2A8CF2553B57C00C340D1 /* PreKeyBundle.h */, - C3C2A8D02553B57C00C340D1 /* PreKeyBundle.m */, - C3C2A8D32553B57C00C340D1 /* PreKeyRecord.h */, - C3C2A8D22553B57C00C340D1 /* PreKeyRecord.m */, - C3C2A8D12553B57C00C340D1 /* SignedPrekeyRecord.h */, - C3C2A8CE2553B57C00C340D1 /* SignedPrekeyRecord.m */, - ); - name = Prekeys; - sourceTree = ""; - }; - C3C2A8E32553B58B00C340D1 /* Protos */ = { - isa = PBXGroup; - children = ( - C3C2A8E52553B59B00C340D1 /* SPKProto.swift */, - C3C2A8E42553B59B00C340D1 /* WhisperTextProtocol.pb.swift */, - C3A71D722558A0F60043A11F /* SMKProto.swift */, - C3A71D732558A0F60043A11F /* OWSUnidentifiedDelivery.pb.swift */, - ); - name = Protos; - sourceTree = ""; - }; - C3C2A8F02553B5A100C340D1 /* Ratchet */ = { - isa = PBXGroup; - children = ( - C3C2A9052553B5B200C340D1 /* AliceAxolotlParameters.h */, - C3C2A8F82553B5B000C340D1 /* AliceAxolotlParameters.m */, - C3C2A9072553B5B200C340D1 /* AxolotlParameters.h */, - C3C2A8FD2553B5B100C340D1 /* BobAxolotlParameters.h */, - C3C2A9032553B5B100C340D1 /* BobAxolotlParameters.m */, - C3C2A8F22553B5B000C340D1 /* Chain.h */, - C3C2A8FE2553B5B100C340D1 /* ChainAndIndex.h */, - C3C2A9062553B5B200C340D1 /* ChainAndIndex.m */, - C3C2A8FC2553B5B100C340D1 /* ChainKey.h */, - C3C2A8F92553B5B000C340D1 /* ChainKey.m */, - C3C2A8F32553B5B000C340D1 /* MessageKeys.h */, - C3C2A9012553B5B100C340D1 /* MessageKeys.m */, - C3C2A8F12553B5B000C340D1 /* RatchetingSession.h */, - C3C2A8F72553B5B000C340D1 /* RatchetingSession.m */, - C3C2A8FA2553B5B000C340D1 /* ReceivingChain.h */, - C3C2A9042553B5B100C340D1 /* ReceivingChain.m */, - C3C2A8F42553B5B000C340D1 /* RKCK.h */, - C3C2A8F52553B5B000C340D1 /* RKCK.m */, - C3C2A8FB2553B5B000C340D1 /* RootKey.h */, - C3C2A8FF2553B5B100C340D1 /* RootKey.m */, - C3C2A9082553B5B200C340D1 /* SendingChain.h */, - C3C2A9002553B5B100C340D1 /* SendingChain.m */, - C3C2A8F62553B5B000C340D1 /* TSDerivedSecrets.h */, - C3C2A9022553B5B100C340D1 /* TSDerivedSecrets.m */, - ); - name = Ratchet; - sourceTree = ""; - }; - C3C2A9352553B5C300C340D1 /* Sessions */ = { - isa = PBXGroup; - children = ( - C3C2A9362553B5D600C340D1 /* SessionBuilder.h */, - C3C2A9372553B5D600C340D1 /* SessionBuilder.m */, - C3C2A93A2553B5D600C340D1 /* SessionRecord.h */, - C3C2A9382553B5D600C340D1 /* SessionRecord.m */, - C3C2A93B2553B5D700C340D1 /* SessionState.h */, - C3C2A9392553B5D600C340D1 /* SessionState.m */, - ); - name = Sessions; - sourceTree = ""; - }; - C3C2A9562553B5F600C340D1 /* State */ = { - isa = PBXGroup; - children = ( - C3C2A9572553B62300C340D1 /* AxolotlStore.h */, - C3C2A9592553B62400C340D1 /* IdentityKeyStore.h */, - C3C2A9582553B62400C340D1 /* PreKeyStore.h */, - C3C2A95A2553B62400C340D1 /* SessionStore.h */, - C3C2A95B2553B62400C340D1 /* SignedPreKeyStore.h */, - ); - path = State; - sourceTree = ""; - }; - C3C2A9692553B62B00C340D1 /* Utility */ = { - isa = PBXGroup; - children = ( - C3C2A96B2553B63C00C340D1 /* NSData+keyVersionByte.h */, - C3C2A96A2553B63B00C340D1 /* NSData+keyVersionByte.m */, - C3C2A96C2553B63C00C340D1 /* SerializationUtilities.h */, - C3C2A96D2553B63C00C340D1 /* SerializationUtilities.m */, - ); - name = Utility; - sourceTree = ""; - }; - C3C2AB492553C4A800C340D1 /* Signal */ = { - isa = PBXGroup; - children = ( - C3C2A8872553B4CC00C340D1 /* AxolotlExceptions.h */, - C3C2A8922553B4E400C340D1 /* CipherMessage */, - C3C2A8B52553B53700C340D1 /* Constants.h */, - C3C2A8BF2553B54600C340D1 /* Crypto */, - C3C2A8CD2553B56400C340D1 /* Prekeys */, - C3C2A8E32553B58B00C340D1 /* Protos */, - C3C2A8F02553B5A100C340D1 /* Ratchet */, - C3C2A9292553B5BD00C340D1 /* SessionCipher.h */, - C3C2A92A2553B5BE00C340D1 /* SessionCipher.m */, - C3C2A9352553B5C300C340D1 /* Sessions */, - C3C2A9562553B5F600C340D1 /* State */, - C3C2A9692553B62B00C340D1 /* Utility */, - C3A71DB12558B25F0043A11F /* Metadata */, - ); - path = Signal; - sourceTree = ""; - }; - C3C2AB622553C5D400C340D1 /* Shared Sender Keys */ = { - isa = PBXGroup; - children = ( - C3C2ABE32553C74400C340D1 /* ClosedGroupRatchet.swift */, - C3C2ABED2553C76900C340D1 /* ClosedGroupSenderKey.swift */, - C3C2AB632553C5FF00C340D1 /* SharedSenderKeys.swift */, - ); - path = "Shared Sender Keys"; - sourceTree = ""; - }; C3CA3AA0255CDA7000F4C6D4 /* Mnemonic */ = { isa = PBXGroup; children = ( @@ -3993,7 +3594,6 @@ C38EF35D255B6DCC007E1867 /* OWSNavigationController.h in Headers */, C38EF249255B6D67007E1867 /* UIColor+OWS.h in Headers */, C38EF216255B6D3B007E1867 /* Theme.h in Headers */, - C33FDCBD255A582000E217F9 /* OWSPrimaryStorage+SessionStore.h in Headers */, C38EF3F0255B6DF7007E1867 /* ThreadViewHelper.h in Headers */, C38EF274255B6D7A007E1867 /* OWSResaveCollectionDBMigration.h in Headers */, C33FDC95255A582000E217F9 /* OWSFailedMessagesJob.h in Headers */, @@ -4017,18 +3617,13 @@ C38EF2D7255B6DAF007E1867 /* OWSProfileManager.h in Headers */, C38EF290255B6D86007E1867 /* AppSetup.h in Headers */, C37F5385255B94F6002AEA92 /* SelectRecipientViewController.h in Headers */, - C33FDC61255A582000E217F9 /* OWSPrimaryStorage+SignedPreKeyStore.h in Headers */, C38EF367255B6DCC007E1867 /* OWSTableViewController.h in Headers */, C38EF246255B6D67007E1867 /* UIFont+OWS.h in Headers */, - C33FDD0D255A582000E217F9 /* PreKeyBundle+jsonDict.h in Headers */, - C33FDD60255A582000E217F9 /* TSInvalidIdentityKeySendingErrorMessage.h in Headers */, C33FD9AF255A548A00E217F9 /* SignalUtilitiesKit.h in Headers */, C33FDC50255A582000E217F9 /* OWSDispatch.h in Headers */, C33FDD06255A582000E217F9 /* AppVersion.h in Headers */, - C33FDD27255A582000E217F9 /* TSPreKeyManager.h in Headers */, C33FDD5A255A582000E217F9 /* TSStorageHeaders.h in Headers */, C33FDCA2255A582000E217F9 /* OWSMessageUtils.h in Headers */, - C33FDD01255A582000E217F9 /* OWSPrimaryStorage+PreKeyStore.h in Headers */, C38EF28F255B6D86007E1867 /* VersionMigrations.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; @@ -4084,7 +3679,6 @@ C3D9E487256775D20040E4F3 /* TSAttachmentStream.h in Headers */, B8856CB1256F0F47001CE70E /* OWSBackupFragment.h in Headers */, C3A3A122256E1A97004D228D /* OWSDisappearingMessagesFinder.h in Headers */, - C32C5F4E256DFD58003C73A2 /* TSInvalidIdentityKeyReceivingErrorMessage.h in Headers */, C3A3A12B256E1AD5004D228D /* TSDatabaseSecondaryIndexes.h in Headers */, C32C5FC4256E0209003C73A2 /* OWSBackgroundTask.h in Headers */, C32C5C24256DCB30003C73A2 /* NotificationsProtocol.h in Headers */, @@ -4122,7 +3716,6 @@ C3A3A145256E1B49004D228D /* OWSMediaGalleryFinder.h in Headers */, B8856E33256F18D5001CE70E /* OWSStorage+Subclass.h in Headers */, C32C5C0A256DC9B4003C73A2 /* OWSIdentityManager.h in Headers */, - C32C5F68256DFDAA003C73A2 /* TSInvalidIdentityKeyErrorMessage.h in Headers */, B8856E9D256F1C3D001CE70E /* OWSSounds.h in Headers */, C32C5E64256DDFD6003C73A2 /* OWSStorage.h in Headers */, ); @@ -4132,43 +3725,8 @@ isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - C3C2A95E2553B62400C340D1 /* IdentityKeyStore.h in Headers */, - C3C2A95D2553B62400C340D1 /* PreKeyStore.h in Headers */, - C3C2A91F2553B5B200C340D1 /* AxolotlParameters.h in Headers */, - C3C2A95F2553B62400C340D1 /* SessionStore.h in Headers */, - C3C2A8D52553B57C00C340D1 /* PreKeyBundle.h in Headers */, - C3C2A9092553B5B200C340D1 /* RatchetingSession.h in Headers */, - C3C2A96F2553B63C00C340D1 /* NSData+keyVersionByte.h in Headers */, - C3C2A91D2553B5B200C340D1 /* AliceAxolotlParameters.h in Headers */, - C3C2A9402553B5D700C340D1 /* SessionRecord.h in Headers */, - C3C2A90A2553B5B200C340D1 /* Chain.h in Headers */, - C3C2A8882553B4CC00C340D1 /* AxolotlExceptions.h in Headers */, C3A71D5A25589FF30043A11F /* NSData+messagePadding.h in Headers */, - C3C2A89E2553B4F600C340D1 /* WhisperMessage.h in Headers */, - C3C2A8D92553B57C00C340D1 /* PreKeyRecord.h in Headers */, - C3C2A90B2553B5B200C340D1 /* MessageKeys.h in Headers */, - C3C2A90C2553B5B200C340D1 /* RKCK.h in Headers */, - C3C2A92B2553B5BE00C340D1 /* SessionCipher.h in Headers */, - C3C2A9152553B5B200C340D1 /* BobAxolotlParameters.h in Headers */, - C3C2A9412553B5D700C340D1 /* SessionState.h in Headers */, - C3C2A9142553B5B200C340D1 /* ChainKey.h in Headers */, C3C2A8662553B41A00C340D1 /* SessionProtocolKit.h in Headers */, - C3C2A89F2553B4F600C340D1 /* ClosedGroupCiphertextMessage.h in Headers */, - C3C2A95C2553B62400C340D1 /* AxolotlStore.h in Headers */, - C3C2A9602553B62400C340D1 /* SignedPreKeyStore.h in Headers */, - C3C2A9702553B63C00C340D1 /* SerializationUtilities.h in Headers */, - C3C2A8A42553B4F600C340D1 /* FallbackMessage.h in Headers */, - C3C2A9122553B5B200C340D1 /* ReceivingChain.h in Headers */, - C3C2A9202553B5B200C340D1 /* SendingChain.h in Headers */, - C3C2A89C2553B4F600C340D1 /* PreKeyWhisperMessage.h in Headers */, - C3C2A8B62553B53800C340D1 /* Constants.h in Headers */, - C3C2A8C22553B55600C340D1 /* AES-CBC.h in Headers */, - C3C2A93C2553B5D700C340D1 /* SessionBuilder.h in Headers */, - C3C2A9162553B5B200C340D1 /* ChainAndIndex.h in Headers */, - C3C2A8A22553B4F600C340D1 /* CipherMessage.h in Headers */, - C3C2A8D72553B57C00C340D1 /* SignedPrekeyRecord.h in Headers */, - C3C2A9132553B5B200C340D1 /* RootKey.h in Headers */, - C3C2A90E2553B5B200C340D1 /* TSDerivedSecrets.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -4427,7 +3985,7 @@ C3C2A8612553B41A00C340D1 = { CreatedOnToolsVersion = 12.1; DevelopmentTeam = SUQ8J2PCT7; - LastSwiftMigration = 1210; + LastSwiftMigration = 1220; ProvisioningStyle = Automatic; }; D221A088169C9E5E00537ABF = { @@ -4985,7 +4543,6 @@ C38EF35F255B6DCC007E1867 /* SelectRecipientViewController.m in Sources */, C38EF3C5255B6DE7007E1867 /* OWSViewController+ImageEditor.swift in Sources */, C33FDDCD255A582000E217F9 /* OWSAttachmentDownloads.m in Sources */, - C33FDD0F255A582000E217F9 /* TSInvalidIdentityKeySendingErrorMessage.m in Sources */, C38EF320255B6DBF007E1867 /* OWSScrubbingLogFormatter.m in Sources */, C38EF39B255B6DDA007E1867 /* ThreadViewModel.swift in Sources */, C38EF2A5255B6D93007E1867 /* Identicon+ObjC.swift in Sources */, @@ -4998,7 +4555,6 @@ C38EF385255B6DD2007E1867 /* AttachmentTextToolbar.swift in Sources */, C33FDD23255A582000E217F9 /* FeatureFlags.swift in Sources */, C38EF389255B6DD2007E1867 /* AttachmentTextView.swift in Sources */, - C33FDD0A255A582000E217F9 /* OWSPrimaryStorage+PreKeyStore.m in Sources */, C38EF3FF255B6DF7007E1867 /* TappableView.swift in Sources */, C38EF3C2255B6DE7007E1867 /* ImageEditorPaletteView.swift in Sources */, C38EF245255B6D67007E1867 /* UIFont+OWS.m in Sources */, @@ -5008,7 +4564,6 @@ C38EF30C255B6DBF007E1867 /* OWSScreenLock.swift in Sources */, C38EF363255B6DCC007E1867 /* ModalActivityIndicatorViewController.swift in Sources */, C38EF38A255B6DD2007E1867 /* AttachmentCaptionToolbar.swift in Sources */, - C33FDD83255A582000E217F9 /* CreatePreKeysOperation.swift in Sources */, C38EF40A255B6DF7007E1867 /* OWSFlatButton.swift in Sources */, C33FDCD1255A582000E217F9 /* FunctionalUtil.m in Sources */, C38EF402255B6DF7007E1867 /* CommonStrings.swift in Sources */, @@ -5020,11 +4575,9 @@ C3F0A530255C80BC007BE2A3 /* NoopNotificationsManager.swift in Sources */, C3D90A7A25773A93002C9DF5 /* Configuration.swift in Sources */, C33FDD8D255A582000E217F9 /* OWSSignalAddress.swift in Sources */, - C33FDCB1255A582000E217F9 /* OWSPrimaryStorage+SignedPreKeyStore.m in Sources */, C33FDC64255A582000E217F9 /* NSObject+Casting.m in Sources */, C38EF388255B6DD2007E1867 /* AttachmentApprovalViewController.swift in Sources */, C33FDD53255A582000E217F9 /* OWSPrimaryStorage+keyFromIntLong.m in Sources */, - C33FDD38255A582000E217F9 /* TSPreKeyManager.m in Sources */, C38EF2A7255B6D93007E1867 /* ProfilePictureView.swift in Sources */, C38EF22C255B6D5D007E1867 /* OWSVideoPlayer.swift in Sources */, C33FDC29255A581F00E217F9 /* ReachabilityManager.swift in Sources */, @@ -5032,7 +4585,6 @@ C38EF38C255B6DD2007E1867 /* ApprovalRailCellView.swift in Sources */, C38EF409255B6DF7007E1867 /* ContactTableViewCell.m in Sources */, C38EF32A255B6DBF007E1867 /* UIUtil.m in Sources */, - C33FDC52255A582000E217F9 /* RotateSignedKeyOperation.swift in Sources */, C38EF335255B6DBF007E1867 /* BlockListCache.swift in Sources */, C38EF2A6255B6D93007E1867 /* PlaceholderIcon.swift in Sources */, C38EF371255B6DCC007E1867 /* MessageApprovalViewController.swift in Sources */, @@ -5055,7 +4607,6 @@ C33FDCFA255A582000E217F9 /* SignalIOSProto.swift in Sources */, C33FDD13255A582000E217F9 /* OWSFailedAttachmentDownloadsJob.m in Sources */, C38EF24D255B6D67007E1867 /* UIView+OWS.swift in Sources */, - C33FDD4D255A582000E217F9 /* PreKeyBundle+jsonDict.m in Sources */, C38EF408255B6DF7007E1867 /* OWSSearchBar.m in Sources */, C38EF327255B6DBF007E1867 /* BlockListUIUtils.m in Sources */, C38EF310255B6DBF007E1867 /* DebugLogger.m in Sources */, @@ -5072,12 +4623,9 @@ C38EF36B255B6DCC007E1867 /* ScreenLockViewController.m in Sources */, C33FDC39255A581F00E217F9 /* OWSRecordTranscriptJob.m in Sources */, C38EF228255B6D5D007E1867 /* AttachmentSharing.m in Sources */, - C33FDD1E255A582000E217F9 /* PreKeyRefreshOperation.swift in Sources */, C38EF40C255B6DF7007E1867 /* GradientView.swift in Sources */, - C33FDD14255A582000E217F9 /* OWSUDManager.swift in Sources */, C38EF35C255B6DCC007E1867 /* SelectThreadViewController.m in Sources */, C38EF30E255B6DBF007E1867 /* FullTextSearcher.swift in Sources */, - C33FDDD9255A582000E217F9 /* LokiSessionRestorationImplementation.swift in Sources */, C38EF3FA255B6DF7007E1867 /* DirectionalPanGestureRecognizer.swift in Sources */, C38EF3BB255B6DE7007E1867 /* ImageEditorStrokeItem.swift in Sources */, C38EF3C0255B6DE7007E1867 /* ImageEditorCropViewController.swift in Sources */, @@ -5110,7 +4658,6 @@ C38EF40B255B6DF7007E1867 /* TappableStackView.swift in Sources */, C38EF31D255B6DBF007E1867 /* UIImage+OWS.swift in Sources */, C38EF359255B6DCC007E1867 /* SheetViewController.swift in Sources */, - C33FDCAD255A582000E217F9 /* OWSPrimaryStorage+SessionStore.m in Sources */, C38EF386255B6DD2007E1867 /* AttachmentApprovalInputAccessoryView.swift in Sources */, C38EF28E255B6D86007E1867 /* SignalKeyingStorage.m in Sources */, B8C2B2C82563685C00551B4D /* CircleView.swift in Sources */, @@ -5210,7 +4757,6 @@ C3471F4C25553AB000297E91 /* MessageReceiver+Decryption.swift in Sources */, C300A5D32554B05A00555489 /* TypingIndicator.swift in Sources */, C3A3A156256E1B91004D228D /* ProtoUtils.m in Sources */, - C3CA3B2F255CF84E00F4C6D4 /* NullMessage.swift in Sources */, C3471ECB2555356A00297E91 /* MessageSender+Encryption.swift in Sources */, C352A32F2557549C00338F3E /* NotifyPNServerJob.swift in Sources */, C300A5F22554B09800555489 /* MessageSender.swift in Sources */, @@ -5234,7 +4780,6 @@ C3BBE0B52554F0E10050F1E3 /* ProofOfWork.swift in Sources */, C3A721902558C0CD0043A11F /* FileServerAPI.swift in Sources */, C32C59C1256DB41F003C73A2 /* TSGroupThread.m in Sources */, - C32C5F45256DFD2B003C73A2 /* TSInvalidIdentityKeyReceivingErrorMessage.m in Sources */, C3A3A08F256E1728004D228D /* FullTextSearchFinder.swift in Sources */, B8856D1A256F114D001CE70E /* ProximityMonitoringManager.swift in Sources */, C32C5B9F256DC739003C73A2 /* OWSBlockingManager.m in Sources */, @@ -5276,7 +4821,6 @@ C3BBE0762554CDA60050F1E3 /* Configuration.swift in Sources */, B8B32033258B235D0020074B /* Storage+Contacts.swift in Sources */, B8856D69256F141F001CE70E /* OWSWindowManager.m in Sources */, - C32C5F5F256DFD90003C73A2 /* TSInvalidIdentityKeyErrorMessage.m in Sources */, C3D9E3BE25676AD70040E4F3 /* TSAttachmentPointer.m in Sources */, C3ECBF7B257056B700EA7FCE /* Threading.swift in Sources */, C32C5AAB256DBE8F003C73A2 /* TSIncomingMessage+Conversion.swift in Sources */, @@ -5310,7 +4854,6 @@ B8856D11256F112A001CE70E /* OWSAudioSession.swift in Sources */, C3C2A75F2553A3C500C340D1 /* VisibleMessage+LinkPreview.swift in Sources */, C32C5FBB256E0206003C73A2 /* OWSBackgroundTask.m in Sources */, - C32C5C93256DD12D003C73A2 /* OWSUDManager.swift in Sources */, B8856CA8256F0F42001CE70E /* OWSBackupFragment.m in Sources */, C32C5C3D256DCBAF003C73A2 /* AppReadiness.m in Sources */, C3A3A18A256E2092004D228D /* SignalRecipient.m in Sources */, @@ -5318,7 +4861,6 @@ C32C5F11256DF79A003C73A2 /* SSKIncrementingIdFinder.swift in Sources */, C32C5DBF256DD743003C73A2 /* ClosedGroupPoller.swift in Sources */, C32C5EEE256DF54E003C73A2 /* TSDatabaseView.m in Sources */, - C300A5C92554B04E00555489 /* SessionRequest.swift in Sources */, C3A7213A2558BDFA0043A11F /* OpenGroupInfo.swift in Sources */, C352A35B2557824E00338F3E /* AttachmentUploadJob.swift in Sources */, C3A3A13C256E1B27004D228D /* OWSMediaGalleryFinder.m in Sources */, @@ -5346,53 +4888,12 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - C3C2A91B2553B5B200C340D1 /* BobAxolotlParameters.m in Sources */, - C3C2A8D82553B57C00C340D1 /* PreKeyRecord.m in Sources */, - C3A71D3B25589F2B0043A11F /* SessionRestorationStatus.swift in Sources */, - C3A71D5825589FF30043A11F /* SMKSecretSessionCipher.swift in Sources */, - C3C2A9712553B63C00C340D1 /* SerializationUtilities.m in Sources */, - C3A71D5925589FF30043A11F /* SMKUnidentifiedSenderMessageContent.swift in Sources */, - C3C2ABEE2553C76900C340D1 /* ClosedGroupSenderKey.swift in Sources */, - C3C2A9172553B5B200C340D1 /* RootKey.m in Sources */, - C3C2A9112553B5B200C340D1 /* ChainKey.m in Sources */, - C3C2A8C32553B55600C340D1 /* AES-CBC.m in Sources */, - C3A71D682558A0170043A11F /* LokiSessionCipher.swift in Sources */, - C3A71D5B25589FF30043A11F /* SMKUnidentifiedSenderMessage.swift in Sources */, - C3C2A9182553B5B200C340D1 /* SendingChain.m in Sources */, - C3C2A8A02553B4F600C340D1 /* PreKeyWhisperMessage.m in Sources */, - C3A71D5225589FF30043A11F /* SMKError.swift in Sources */, - C3C2A93F2553B5D700C340D1 /* SessionState.m in Sources */, - C3C2ABF82553C8A300C340D1 /* Storage.swift in Sources */, - C3C2A90D2553B5B200C340D1 /* RKCK.m in Sources */, - C3C2A8E72553B59B00C340D1 /* SPKProto.swift in Sources */, - C3A71D5525589FF30043A11F /* SMKSenderCertificate.swift in Sources */, - C3C2A91E2553B5B200C340D1 /* ChainAndIndex.m in Sources */, - C3C2A91A2553B5B200C340D1 /* TSDerivedSecrets.m in Sources */, - C3A71D5025589FF30043A11F /* SMKUDAccessKey.swift in Sources */, - C3C2A91C2553B5B200C340D1 /* ReceivingChain.m in Sources */, - C3C2A8A32553B4F600C340D1 /* FallbackMessage.m in Sources */, + B8CA010125A293260091AF73 /* ClosedGroupSenderKey.swift in Sources */, + B8CA011525A293800091AF73 /* Configuration.swift in Sources */, C3A71D5425589FF30043A11F /* NSData+messagePadding.m in Sources */, - C3C2ABE42553C74400C340D1 /* ClosedGroupRatchet.swift in Sources */, - C3C2A93E2553B5D700C340D1 /* SessionRecord.m in Sources */, - C3A71D742558A0F60043A11F /* SMKProto.swift in Sources */, - C3A71D2925589EBF0043A11F /* SessionRestorationProtocol.swift in Sources */, - C3C2A8D62553B57C00C340D1 /* PreKeyBundle.m in Sources */, - C3C2A89D2553B4F600C340D1 /* ClosedGroupCiphertextMessage.m in Sources */, - C3A71D672558A0170043A11F /* FallbackSessionCipher.swift in Sources */, - C3C2AC0A2553C9A100C340D1 /* Configuration.swift in Sources */, - C3C2A96E2553B63C00C340D1 /* NSData+keyVersionByte.m in Sources */, - C3C2A8E62553B59B00C340D1 /* WhisperTextProtocol.pb.swift in Sources */, - C3C2AB642553C5FF00C340D1 /* SharedSenderKeys.swift in Sources */, - C3C2A9102553B5B200C340D1 /* AliceAxolotlParameters.m in Sources */, - C3C2A92C2553B5BE00C340D1 /* SessionCipher.m in Sources */, - C3C2A8D42553B57C00C340D1 /* SignedPrekeyRecord.m in Sources */, - C3A71D752558A0F60043A11F /* OWSUnidentifiedDelivery.pb.swift in Sources */, - C3A71D5625589FF30043A11F /* SMKServerCertificate.swift in Sources */, - C3C2A8A12553B4F600C340D1 /* WhisperMessage.m in Sources */, - C3C2A9192553B5B200C340D1 /* MessageKeys.m in Sources */, - C3C2A90F2553B5B200C340D1 /* RatchetingSession.m in Sources */, - C3A71D5725589FF30043A11F /* SMKCertificateValidator.swift in Sources */, - C3C2A93D2553B5D700C340D1 /* SessionBuilder.m in Sources */, + B8CA011F25A2939F0091AF73 /* SharedSenderKeys.swift in Sources */, + B8CA010B25A293530091AF73 /* ClosedGroupRatchet.swift in Sources */, + B8CA014125A293EE0091AF73 /* Storage.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -5457,7 +4958,6 @@ 4CB5F26720F6E1E2004D1B42 /* MenuActionsViewController.swift in Sources */, B85A68B12587141A008CC492 /* Storage+Resetting.swift in Sources */, 3496955E219B605E00DCFE74 /* PhotoLibrary.swift in Sources */, - 45D231771DC7E8F10034FA89 /* SessionResetJob.swift in Sources */, 340FC8A9204DAC8D007AEB0F /* NotificationSettingsOptionsViewController.m in Sources */, C3D0972B2510499C00F6E3E4 /* BackgroundPoller.swift in Sources */, C3548F0624456447009433A8 /* PNModeVC.swift in Sources */, diff --git a/SignalUtilitiesKit/AppSetup.m b/SignalUtilitiesKit/AppSetup.m index b053609c5..3f503ece5 100644 --- a/SignalUtilitiesKit/AppSetup.m +++ b/SignalUtilitiesKit/AppSetup.m @@ -56,7 +56,6 @@ NS_ASSUME_NONNULL_BEGIN OWSProfileManager *profileManager = [[OWSProfileManager alloc] initWithPrimaryStorage:primaryStorage]; OWSBlockingManager *blockingManager = [[OWSBlockingManager alloc] initWithPrimaryStorage:primaryStorage]; OWSIdentityManager *identityManager = [[OWSIdentityManager alloc] initWithPrimaryStorage:primaryStorage]; - id udManager = [[OWSUDManagerImpl alloc] initWithPrimaryStorage:primaryStorage]; TSAccountManager *tsAccountManager = [[TSAccountManager alloc] initWithPrimaryStorage:primaryStorage]; OWSDisappearingMessagesJob *disappearingMessagesJob = [[OWSDisappearingMessagesJob alloc] initWithPrimaryStorage:primaryStorage]; @@ -82,7 +81,6 @@ NS_ASSUME_NONNULL_BEGIN primaryStorage:primaryStorage blockingManager:blockingManager identityManager:identityManager - udManager:udManager tsAccountManager:tsAccountManager disappearingMessagesJob:disappearingMessagesJob readReceiptManager:readReceiptManager diff --git a/SignalUtilitiesKit/Configuration.swift b/SignalUtilitiesKit/Configuration.swift index e45b98e87..30384df3b 100644 --- a/SignalUtilitiesKit/Configuration.swift +++ b/SignalUtilitiesKit/Configuration.swift @@ -8,14 +8,7 @@ extension OWSPrimaryStorage : OWSPrimaryStorageProtocol { } public final class Configuration : NSObject { @objc public static func performMainSetup() { - SNMessagingKit.configure( - storage: Storage.shared, - signalStorage: OWSPrimaryStorage.shared(), - identityKeyStore: OWSIdentityManager.shared(), - sessionRestorationImplementation: SessionRestorationImplementation(), - certificateValidator: SMKCertificateDefaultValidator(trustRoot: OWSUDManagerImpl.trustRoot()) - ) - SNProtocolKit.configure(storage: Storage.shared, sharedSenderKeysDelegate: MessageSender.shared) + SNMessagingKit.configure(storage: Storage.shared) SNSnodeKit.configure(storage: Storage.shared) SNUtilitiesKit.configure(owsPrimaryStorage: OWSPrimaryStorage.shared(), maxFileSize: UInt(Double(FileServerAPI.maxFileSize) / FileServerAPI.fileSizeORMultiplier)) } diff --git a/SignalUtilitiesKit/CreatePreKeysOperation.swift b/SignalUtilitiesKit/CreatePreKeysOperation.swift deleted file mode 100644 index aa342c29e..000000000 --- a/SignalUtilitiesKit/CreatePreKeysOperation.swift +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation -import PromiseKit - -@objc(SSKCreatePreKeysOperation) -public class CreatePreKeysOperation: OWSOperation { - - private var storage: OWSPrimaryStorage { - return OWSPrimaryStorage.shared() - } - - private var identityKeyManager: OWSIdentityManager { - return OWSIdentityManager.shared() - } - - public override func run() { - Logger.debug("") - - if identityKeyManager.identityKeyPair() == nil { - identityKeyManager.generateNewIdentityKeyPair() - } - - let signedPreKeyRecord = storage.generateRandomSignedRecord() - signedPreKeyRecord.markAsAcceptedByService() - storage.storeSignedPreKey(signedPreKeyRecord.id, signedPreKeyRecord: signedPreKeyRecord) - storage.setCurrentSignedPrekeyId(signedPreKeyRecord.id) - SNLog("Pre keys created successfully.") - reportSuccess() - } -} diff --git a/SignalUtilitiesKit/Database/OWSPrimaryStorage+PreKeyStore.h b/SignalUtilitiesKit/Database/OWSPrimaryStorage+PreKeyStore.h deleted file mode 100644 index abbc0a555..000000000 --- a/SignalUtilitiesKit/Database/OWSPrimaryStorage+PreKeyStore.h +++ /dev/null @@ -1,18 +0,0 @@ -// -// Copyright (c) 2019 Open Whisper Systems. All rights reserved. -// - -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface OWSPrimaryStorage (PreKeyStore) - -- (NSArray *)generatePreKeyRecords; -- (NSArray *)generatePreKeyRecords:(int)batchSize; -- (void)storePreKeyRecords:(NSArray *)preKeyRecords NS_SWIFT_NAME(storePreKeyRecords(_:)); - -@end - -NS_ASSUME_NONNULL_END diff --git a/SignalUtilitiesKit/Database/OWSPrimaryStorage+PreKeyStore.m b/SignalUtilitiesKit/Database/OWSPrimaryStorage+PreKeyStore.m deleted file mode 100644 index 20f345f27..000000000 --- a/SignalUtilitiesKit/Database/OWSPrimaryStorage+PreKeyStore.m +++ /dev/null @@ -1,112 +0,0 @@ -// -// Copyright (c) 2019 Open Whisper Systems. All rights reserved. -// - -#import "OWSPrimaryStorage+PreKeyStore.h" -#import "OWSPrimaryStorage+keyFromIntLong.h" -#import "TSStorageKeys.h" -#import "YapDatabaseConnection+OWS.h" -#import - -#define OWSPrimaryStoragePreKeyStoreCollection @"TSStorageManagerPreKeyStoreCollection" -#define TSNextPrekeyIdKey @"TSStorageInternalSettingsNextPreKeyId" -#define BATCH_SIZE 100 - -NS_ASSUME_NONNULL_BEGIN - -@implementation OWSPrimaryStorage (PreKeyStore) - -- (NSArray *)generatePreKeyRecords -{ - return [self generatePreKeyRecords:BATCH_SIZE]; -} - -- (NSArray *)generatePreKeyRecords:(int)batchSize -{ - NSMutableArray *preKeyRecords = [NSMutableArray array]; - - @synchronized(self) - { - int preKeyId = [self nextPreKeyId:batchSize]; - - OWSLogInfo(@"building %d new preKeys starting from preKeyId: %d", batchSize, preKeyId); - for (int i = 0; i < batchSize; i++) { - ECKeyPair *keyPair = [Curve25519 generateKeyPair]; - PreKeyRecord *record = [[PreKeyRecord alloc] initWithId:preKeyId keyPair:keyPair]; - - [preKeyRecords addObject:record]; - preKeyId++; - } - - [self.dbReadWriteConnection setInt:preKeyId - forKey:TSNextPrekeyIdKey - inCollection:TSStorageInternalSettingsCollection]; - } - return preKeyRecords; -} - -- (void)storePreKeyRecords:(NSArray *)preKeyRecords -{ - for (PreKeyRecord *record in preKeyRecords) { - [self.dbReadWriteConnection setObject:record - forKey:[self keyFromInt:record.Id] - inCollection:OWSPrimaryStoragePreKeyStoreCollection]; - } -} - -- (PreKeyRecord *)throws_loadPreKey:(int)preKeyId -{ - PreKeyRecord *preKeyRecord = [self.dbReadConnection preKeyRecordForKey:[self keyFromInt:preKeyId] - inCollection:OWSPrimaryStoragePreKeyStoreCollection]; - - if (!preKeyRecord) { - OWSRaiseException(InvalidKeyIdException, @"No pre key found matching key id"); - } else { - return preKeyRecord; - } -} - -- (void)storePreKey:(int)preKeyId preKeyRecord:(PreKeyRecord *)record -{ - [self.dbReadWriteConnection setObject:record - forKey:[self keyFromInt:preKeyId] - inCollection:OWSPrimaryStoragePreKeyStoreCollection]; -} - -- (BOOL)containsPreKey:(int)preKeyId -{ - PreKeyRecord *preKeyRecord = [self.dbReadConnection preKeyRecordForKey:[self keyFromInt:preKeyId] - inCollection:OWSPrimaryStoragePreKeyStoreCollection]; - return (preKeyRecord != nil); -} - -- (void)removePreKey:(int)preKeyId protocolContext:(nullable id)protocolContext -{ - if ([protocolContext isKindOfClass:YapDatabaseReadWriteTransaction.class]) { - [(YapDatabaseReadWriteTransaction *)protocolContext removeObjectForKey:[self keyFromInt:preKeyId] inCollection:OWSPrimaryStoragePreKeyStoreCollection]; - } else { - [self.dbReadWriteConnection removeObjectForKey:[self keyFromInt:preKeyId] inCollection:OWSPrimaryStoragePreKeyStoreCollection]; - } -} - -- (int)nextPreKeyId:(int)batchSize -{ - int lastPreKeyId = - [self.dbReadConnection intForKey:TSNextPrekeyIdKey inCollection:TSStorageInternalSettingsCollection]; - - if (lastPreKeyId < 1) { - // One-time prekey ids must be > 0 and < kPreKeyOfLastResortId. - lastPreKeyId = 1 + arc4random_uniform(kPreKeyOfLastResortId - (batchSize + 1)); - } else if (lastPreKeyId > kPreKeyOfLastResortId - batchSize) { - // We want to "overflow" to 1 when we reach the "prekey of last resort" id - // to avoid biasing towards higher values. - lastPreKeyId = 1; - } - OWSCAssertDebug(lastPreKeyId > 0 && lastPreKeyId < kPreKeyOfLastResortId); - - return lastPreKeyId; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SignalUtilitiesKit/Database/OWSPrimaryStorage+SessionStore.h b/SignalUtilitiesKit/Database/OWSPrimaryStorage+SessionStore.h deleted file mode 100644 index 40b11fdfb..000000000 --- a/SignalUtilitiesKit/Database/OWSPrimaryStorage+SessionStore.h +++ /dev/null @@ -1,25 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface OWSPrimaryStorage (SessionStore) - -#pragma mark - Debug - -- (void)resetSessionStore:(YapDatabaseReadWriteTransaction *)transaction; - -#if DEBUG -- (void)snapshotSessionStore:(YapDatabaseReadWriteTransaction *)transaction; -- (void)restoreSessionStore:(YapDatabaseReadWriteTransaction *)transaction; -#endif - -- (void)printAllSessions; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SignalUtilitiesKit/Database/OWSPrimaryStorage+SessionStore.m b/SignalUtilitiesKit/Database/OWSPrimaryStorage+SessionStore.m deleted file mode 100644 index 8501b263a..000000000 --- a/SignalUtilitiesKit/Database/OWSPrimaryStorage+SessionStore.m +++ /dev/null @@ -1,273 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "OWSPrimaryStorage+SessionStore.h" -#import "OWSFileSystem.h" -#import "SSKEnvironment.h" -#import "YapDatabaseConnection+OWS.h" -#import "YapDatabaseTransaction+OWS.h" -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -NSString *const OWSPrimaryStorageSessionStoreCollection = @"TSStorageManagerSessionStoreCollection"; -NSString *const kSessionStoreDBConnectionKey = @"kSessionStoreDBConnectionKey"; - -@implementation OWSPrimaryStorage (SessionStore) - -/** - * Special purpose dbConnection which disables the object cache to better enforce transaction semantics on the store. - * Note that it's still technically possible to access this collection from a different collection, - * but that should be considered a bug. - */ -+ (YapDatabaseConnection *)sessionStoreDBConnection -{ - return SSKEnvironment.shared.sessionStoreDBConnection; -} - -- (YapDatabaseConnection *)sessionStoreDBConnection -{ - return [[self class] sessionStoreDBConnection]; -} - -#pragma mark - SessionStore - -- (SessionRecord *)loadSession:(NSString *)contactIdentifier - deviceId:(int)deviceId - protocolContext:(nullable id)protocolContext -{ - OWSAssertDebug(contactIdentifier.length > 0); - OWSAssertDebug(deviceId >= 0); - OWSAssertDebug([protocolContext isKindOfClass:[YapDatabaseReadWriteTransaction class]]); - - YapDatabaseReadWriteTransaction *transaction = protocolContext; - - NSDictionary *_Nullable dictionary = - [transaction objectForKey:contactIdentifier inCollection:OWSPrimaryStorageSessionStoreCollection]; - - SessionRecord *record; - - if (dictionary) { - record = [dictionary objectForKey:@(deviceId)]; - } - - if (!record) { - return [SessionRecord new]; - } - - return record; -} - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-implementations" -- (NSArray *)subDevicesSessions:(NSString *)contactIdentifier protocolContext:(nullable id)protocolContext -{ - OWSAssertDebug(contactIdentifier.length > 0); - OWSAssertDebug([protocolContext isKindOfClass:[YapDatabaseReadWriteTransaction class]]); - - // Deprecated. We aren't currently using this anywhere, but it's "required" by the SessionStore protocol. - // If we are going to start using it I'd want to re-verify it works as intended. - OWSFailDebug(@"subDevicesSessions is deprecated"); - - YapDatabaseReadWriteTransaction *transaction = protocolContext; - - NSDictionary *_Nullable dictionary = - [transaction objectForKey:contactIdentifier inCollection:OWSPrimaryStorageSessionStoreCollection]; - - return dictionary ? dictionary.allKeys : @[]; -} -#pragma clang diagnostic pop - -- (void)storeSession:(NSString *)contactIdentifier - deviceId:(int)deviceId - session:(SessionRecord *)session - protocolContext:protocolContext -{ - OWSAssertDebug(contactIdentifier.length > 0); - OWSAssertDebug(deviceId >= 0); - OWSAssertDebug([protocolContext isKindOfClass:[YapDatabaseReadWriteTransaction class]]); - - YapDatabaseReadWriteTransaction *transaction = protocolContext; - - // We need to ensure subsequent usage of this SessionRecord does not consider this session as "fresh". Normally this - // is achieved by marking things as "not fresh" at the point of deserialization - when we fetch a SessionRecord from - // YapDB (initWithCoder:). However, because YapDB has an object cache, rather than fetching/deserializing, it's - // possible we'd get back *this* exact instance of the object (which, at this point, is still potentially "fresh"), - // thus we explicitly mark this instance as "unfresh", any time we save. - // NOTE: this may no longer be necessary now that we have a non-caching session db connection. - [session markAsUnFresh]; - - NSDictionary *immutableDictionary = - [transaction objectForKey:contactIdentifier inCollection:OWSPrimaryStorageSessionStoreCollection]; - - NSMutableDictionary *dictionary - = (immutableDictionary ? [immutableDictionary mutableCopy] : [NSMutableDictionary new]); - - [dictionary setObject:session forKey:@(deviceId)]; - - [transaction setObject:[dictionary copy] - forKey:contactIdentifier - inCollection:OWSPrimaryStorageSessionStoreCollection]; -} - -- (BOOL)containsSession:(NSString *)contactIdentifier - deviceId:(int)deviceId - protocolContext:(nullable id)protocolContext -{ - OWSAssertDebug(contactIdentifier.length > 0); - OWSAssertDebug(deviceId >= 0); - OWSAssertDebug([protocolContext isKindOfClass:[YapDatabaseReadWriteTransaction class]]); - - return [self loadSession:contactIdentifier deviceId:deviceId protocolContext:protocolContext] - .sessionState.hasSenderChain; -} - -- (void)deleteSessionForContact:(NSString *)contactIdentifier - deviceId:(int)deviceId - protocolContext:(nullable id)protocolContext -{ - OWSAssertDebug(contactIdentifier.length > 0); - OWSAssertDebug(deviceId >= 0); - OWSAssertDebug([protocolContext isKindOfClass:[YapDatabaseReadWriteTransaction class]]); - - YapDatabaseReadWriteTransaction *transaction = protocolContext; - - OWSLogInfo( - @"[OWSPrimaryStorage (SessionStore)] deleting session for contact: %@ device: %d", contactIdentifier, deviceId); - - NSDictionary *immutableDictionary = - [transaction objectForKey:contactIdentifier inCollection:OWSPrimaryStorageSessionStoreCollection]; - - NSMutableDictionary *dictionary - = (immutableDictionary ? [immutableDictionary mutableCopy] : [NSMutableDictionary new]); - - [dictionary removeObjectForKey:@(deviceId)]; - - [transaction setObject:[dictionary copy] - forKey:contactIdentifier - inCollection:OWSPrimaryStorageSessionStoreCollection]; -} - -- (void)deleteAllSessionsForContact:(NSString *)contactIdentifier protocolContext:(nullable id)protocolContext -{ - OWSAssertDebug(contactIdentifier.length > 0); - OWSAssertDebug([protocolContext isKindOfClass:[YapDatabaseReadWriteTransaction class]]); - - YapDatabaseReadWriteTransaction *transaction = protocolContext; - - OWSLogInfo(@"[OWSPrimaryStorage (SessionStore)] deleting all sessions for contact:%@", contactIdentifier); - - [transaction removeObjectForKey:contactIdentifier inCollection:OWSPrimaryStorageSessionStoreCollection]; -} - -- (void)archiveAllSessionsForContact:(NSString *)contactIdentifier protocolContext:(nullable id)protocolContext -{ - OWSAssertDebug(contactIdentifier.length > 0); - OWSAssertDebug([protocolContext isKindOfClass:[YapDatabaseReadWriteTransaction class]]); - - YapDatabaseReadWriteTransaction *transaction = protocolContext; - - OWSLogInfo(@"[OWSPrimaryStorage (SessionStore)] archiving all sessions for contact: %@", contactIdentifier); - - __block NSDictionary *sessionRecords = - [transaction objectForKey:contactIdentifier inCollection:OWSPrimaryStorageSessionStoreCollection]; - - for (id deviceId in sessionRecords) { - id object = sessionRecords[deviceId]; - if (![object isKindOfClass:[SessionRecord class]]) { - OWSFailDebug(@"Unexpected object in session dict: %@", [object class]); - continue; - } - - SessionRecord *sessionRecord = (SessionRecord *)object; - [sessionRecord archiveCurrentState]; - } - - [transaction setObject:sessionRecords - forKey:contactIdentifier - inCollection:OWSPrimaryStorageSessionStoreCollection]; -} - -#pragma mark - debug - -- (void)resetSessionStore:(YapDatabaseReadWriteTransaction *)transaction -{ - OWSAssertDebug(transaction); - - OWSLogWarn(@"resetting session store"); - - [transaction removeAllObjectsInCollection:OWSPrimaryStorageSessionStoreCollection]; -} - -- (void)printAllSessions -{ - NSString *tag = @"[OWSPrimaryStorage (SessionStore)]"; - [self.sessionStoreDBConnection readWithBlock:^(YapDatabaseReadTransaction *_Nonnull transaction) { - OWSLogDebug(@"%@ All Sessions:", tag); - [transaction - enumerateKeysAndObjectsInCollection:OWSPrimaryStorageSessionStoreCollection - usingBlock:^(NSString *_Nonnull key, - id _Nonnull deviceSessionsObject, - BOOL *_Nonnull stop) { - if (![deviceSessionsObject isKindOfClass:[NSDictionary class]]) { - OWSFailDebug(@"%@ Unexpected type: %@ in collection.", - tag, - [deviceSessionsObject class]); - return; - } - NSDictionary *deviceSessions = (NSDictionary *)deviceSessionsObject; - - OWSLogDebug(@"%@ Sessions for recipient: %@", tag, key); - [deviceSessions enumerateKeysAndObjectsUsingBlock:^( - id _Nonnull key, id _Nonnull sessionRecordObject, BOOL *_Nonnull stop) { - if (![sessionRecordObject isKindOfClass:[SessionRecord class]]) { - OWSFailDebug(@"%@ Unexpected type: %@ in collection.", - tag, - [sessionRecordObject class]); - return; - } - SessionRecord *sessionRecord = (SessionRecord *)sessionRecordObject; - SessionState *activeState = [sessionRecord sessionState]; - NSArray *previousStates = - [sessionRecord previousSessionStates]; - OWSLogDebug(@"%@ Device: %@ SessionRecord: %@ activeSessionState: " - @"%@ previousSessionStates: %@", - tag, - key, - sessionRecord, - activeState, - previousStates); - }]; - }]; - }]; -} - -#if DEBUG -- (NSString *)snapshotFilePath -{ - // Prefix name with period "." so that backups will ignore these snapshots. - NSString *dirPath = [OWSFileSystem appDocumentDirectoryPath]; - return [dirPath stringByAppendingPathComponent:@".session-snapshot"]; -} - -- (void)snapshotSessionStore:(YapDatabaseReadWriteTransaction *)transaction -{ - OWSAssertDebug(transaction); - - [transaction snapshotCollection:OWSPrimaryStorageSessionStoreCollection snapshotFilePath:self.snapshotFilePath]; -} - -- (void)restoreSessionStore:(YapDatabaseReadWriteTransaction *)transaction -{ - OWSAssertDebug(transaction); - - [transaction restoreSnapshotOfCollection:OWSPrimaryStorageSessionStoreCollection - snapshotFilePath:self.snapshotFilePath]; -} -#endif - -@end - -NS_ASSUME_NONNULL_END diff --git a/SignalUtilitiesKit/Database/OWSPrimaryStorage+SignedPreKeyStore.h b/SignalUtilitiesKit/Database/OWSPrimaryStorage+SignedPreKeyStore.h deleted file mode 100644 index a994d2e18..000000000 --- a/SignalUtilitiesKit/Database/OWSPrimaryStorage+SignedPreKeyStore.h +++ /dev/null @@ -1,40 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -// Used for testing -extern NSString *const OWSPrimaryStorageSignedPreKeyStoreCollection; - -@interface OWSPrimaryStorage (SignedPreKeyStore) - -- (SignedPreKeyRecord *)generateRandomSignedRecord; - -- (nullable SignedPreKeyRecord *)loadSignedPrekeyOrNil:(int)signedPreKeyId; - -// Returns nil if no current signed prekey id is found. -- (nullable NSNumber *)currentSignedPrekeyId; -- (void)setCurrentSignedPrekeyId:(int)value; -- (nullable SignedPreKeyRecord *)currentSignedPreKey; - -#pragma mark - Prekey update failures - -- (int)prekeyUpdateFailureCount; -- (void)clearPrekeyUpdateFailureCount; -- (int)incrementPrekeyUpdateFailureCount; - -- (nullable NSDate *)firstPrekeyUpdateFailureDate; -- (void)setFirstPrekeyUpdateFailureDate:(nonnull NSDate *)value; -- (void)clearFirstPrekeyUpdateFailureDate; - -#pragma mark - Debugging - -- (void)logSignedPreKeyReport; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SignalUtilitiesKit/Database/OWSPrimaryStorage+SignedPreKeyStore.m b/SignalUtilitiesKit/Database/OWSPrimaryStorage+SignedPreKeyStore.m deleted file mode 100644 index 468a05f50..000000000 --- a/SignalUtilitiesKit/Database/OWSPrimaryStorage+SignedPreKeyStore.m +++ /dev/null @@ -1,224 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "OWSPrimaryStorage+SignedPreKeyStore.h" -#import "OWSIdentityManager.h" -#import "OWSPrimaryStorage+PreKeyStore.h" -#import "OWSPrimaryStorage+keyFromIntLong.h" -#import "YapDatabaseConnection+OWS.h" -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -NSString *const OWSPrimaryStorageSignedPreKeyStoreCollection = @"TSStorageManagerSignedPreKeyStoreCollection"; -NSString *const OWSPrimaryStorageSignedPreKeyMetadataCollection = @"TSStorageManagerSignedPreKeyMetadataCollection"; -NSString *const OWSPrimaryStorageKeyPrekeyUpdateFailureCount = @"prekeyUpdateFailureCount"; -NSString *const OWSPrimaryStorageKeyFirstPrekeyUpdateFailureDate = @"firstPrekeyUpdateFailureDate"; -NSString *const OWSPrimaryStorageKeyPrekeyCurrentSignedPrekeyId = @"currentSignedPrekeyId"; - -@implementation OWSPrimaryStorage (SignedPreKeyStore) - -- (SignedPreKeyRecord *)generateRandomSignedRecord -{ - ECKeyPair *keyPair = [Curve25519 generateKeyPair]; - - // Signed prekey ids must be > 0. - int preKeyId = 1 + arc4random_uniform(INT32_MAX - 1); - ECKeyPair *_Nullable identityKeyPair = [[OWSIdentityManager sharedManager] identityKeyPair]; - OWSAssert(identityKeyPair); - - @try { - NSData *signature = [Ed25519 throws_sign:keyPair.publicKey.prependKeyType withKeyPair:identityKeyPair]; - return [[SignedPreKeyRecord alloc] initWithId:preKeyId - keyPair:keyPair - signature:signature - generatedAt:[NSDate date]]; - } @catch (NSException *exception) { - // throws_sign only throws when the data to sign is empty or `keyPair` is nil. - // Neither of which should happen. - OWSFail(@"exception: %@", exception); - return nil; - } -} - -- (SignedPreKeyRecord *)throws_loadSignedPrekey:(int)signedPreKeyId -{ - SignedPreKeyRecord *preKeyRecord = - [self.dbReadConnection signedPreKeyRecordForKey:[self keyFromInt:signedPreKeyId] - inCollection:OWSPrimaryStorageSignedPreKeyStoreCollection]; - - if (!preKeyRecord) { - OWSRaiseException(InvalidKeyIdException, @"No signed pre key found matching key id"); - } else { - return preKeyRecord; - } -} - -- (nullable SignedPreKeyRecord *)loadSignedPrekeyOrNil:(int)signedPreKeyId -{ - return [self.dbReadConnection signedPreKeyRecordForKey:[self keyFromInt:signedPreKeyId] - inCollection:OWSPrimaryStorageSignedPreKeyStoreCollection]; -} - -- (NSArray *)loadSignedPreKeys -{ - NSMutableArray *signedPreKeyRecords = [NSMutableArray array]; - - YapDatabaseConnection *conn = [self newDatabaseConnection]; - - [conn readWithBlock:^(YapDatabaseReadTransaction *transaction) { - [transaction enumerateRowsInCollection:OWSPrimaryStorageSignedPreKeyStoreCollection - usingBlock:^(NSString *key, id object, id metadata, BOOL *stop) { - [signedPreKeyRecords addObject:object]; - }]; - }]; - - return signedPreKeyRecords; -} - -- (void)storeSignedPreKey:(int)signedPreKeyId signedPreKeyRecord:(SignedPreKeyRecord *)signedPreKeyRecord -{ - [self.dbReadWriteConnection setObject:signedPreKeyRecord - forKey:[self keyFromInt:signedPreKeyId] - inCollection:OWSPrimaryStorageSignedPreKeyStoreCollection]; -} - -- (BOOL)containsSignedPreKey:(int)signedPreKeyId -{ - PreKeyRecord *preKeyRecord = - [self.dbReadConnection signedPreKeyRecordForKey:[self keyFromInt:signedPreKeyId] - inCollection:OWSPrimaryStorageSignedPreKeyStoreCollection]; - return (preKeyRecord != nil); -} - -- (void)removeSignedPreKey:(int)signedPrekeyId -{ - [self.dbReadWriteConnection removeObjectForKey:[self keyFromInt:signedPrekeyId] - inCollection:OWSPrimaryStorageSignedPreKeyStoreCollection]; -} - -- (nullable NSNumber *)currentSignedPrekeyId -{ - return [self.dbReadConnection objectForKey:OWSPrimaryStorageKeyPrekeyCurrentSignedPrekeyId - inCollection:OWSPrimaryStorageSignedPreKeyMetadataCollection]; -} - -- (void)setCurrentSignedPrekeyId:(int)value -{ - [self.dbReadWriteConnection setObject:@(value) - forKey:OWSPrimaryStorageKeyPrekeyCurrentSignedPrekeyId - inCollection:OWSPrimaryStorageSignedPreKeyMetadataCollection]; -} - -- (nullable SignedPreKeyRecord *)currentSignedPreKey -{ - __block SignedPreKeyRecord *_Nullable currentRecord; - - [self.dbReadConnection readWithBlock:^(YapDatabaseReadTransaction *_Nonnull transaction) { - NSNumber *_Nullable preKeyId = [transaction objectForKey:OWSPrimaryStorageKeyPrekeyCurrentSignedPrekeyId - inCollection:OWSPrimaryStorageSignedPreKeyMetadataCollection]; - - if (preKeyId == nil) { - return; - } - - currentRecord = - [transaction objectForKey:preKeyId.stringValue inCollection:OWSPrimaryStorageSignedPreKeyStoreCollection]; - }]; - - return currentRecord; -} - -#pragma mark - Prekey update failures - -- (int)prekeyUpdateFailureCount -{ - NSNumber *_Nullable value = [self.dbReadConnection objectForKey:OWSPrimaryStorageKeyPrekeyUpdateFailureCount - inCollection:OWSPrimaryStorageSignedPreKeyMetadataCollection]; - // Will default to zero. - return [value intValue]; -} - -- (void)clearPrekeyUpdateFailureCount -{ - [self.dbReadWriteConnection removeObjectForKey:OWSPrimaryStorageKeyPrekeyUpdateFailureCount - inCollection:OWSPrimaryStorageSignedPreKeyMetadataCollection]; -} - -- (int)incrementPrekeyUpdateFailureCount -{ - return [self.dbReadWriteConnection incrementIntForKey:OWSPrimaryStorageKeyPrekeyUpdateFailureCount - inCollection:OWSPrimaryStorageSignedPreKeyMetadataCollection]; -} - -- (nullable NSDate *)firstPrekeyUpdateFailureDate -{ - return [self.dbReadConnection dateForKey:OWSPrimaryStorageKeyFirstPrekeyUpdateFailureDate - inCollection:OWSPrimaryStorageSignedPreKeyMetadataCollection]; -} - -- (void)setFirstPrekeyUpdateFailureDate:(nonnull NSDate *)value -{ - [self.dbReadWriteConnection setDate:value - forKey:OWSPrimaryStorageKeyFirstPrekeyUpdateFailureDate - inCollection:OWSPrimaryStorageSignedPreKeyMetadataCollection]; -} - -- (void)clearFirstPrekeyUpdateFailureDate -{ - [self.dbReadWriteConnection removeObjectForKey:OWSPrimaryStorageKeyFirstPrekeyUpdateFailureDate - inCollection:OWSPrimaryStorageSignedPreKeyMetadataCollection]; -} - -#pragma mark - Debugging - -- (void)logSignedPreKeyReport -{ - NSString *tag = @"[OWSPrimaryStorage (SignedPreKeyStore)]"; - - NSNumber *currentId = [self currentSignedPrekeyId]; - NSDate *firstPrekeyUpdateFailureDate = [self firstPrekeyUpdateFailureDate]; - NSUInteger prekeyUpdateFailureCount = [self prekeyUpdateFailureCount]; - - [self.dbReadConnection readWithBlock:^(YapDatabaseReadTransaction *_Nonnull transaction) { - __block int i = 0; - - OWSLogInfo(@"%@ SignedPreKeys Report:", tag); - OWSLogInfo(@"%@ currentId: %@", tag, currentId); - OWSLogInfo(@"%@ firstPrekeyUpdateFailureDate: %@", tag, firstPrekeyUpdateFailureDate); - OWSLogInfo(@"%@ prekeyUpdateFailureCount: %lu", tag, (unsigned long)prekeyUpdateFailureCount); - - NSUInteger count = [transaction numberOfKeysInCollection:OWSPrimaryStorageSignedPreKeyStoreCollection]; - OWSLogInfo(@"%@ All Keys (count: %lu):", tag, (unsigned long)count); - - [transaction - enumerateKeysAndObjectsInCollection:OWSPrimaryStorageSignedPreKeyStoreCollection - usingBlock:^( - NSString *_Nonnull key, id _Nonnull signedPreKeyObject, BOOL *_Nonnull stop) { - i++; - if (![signedPreKeyObject isKindOfClass:[SignedPreKeyRecord class]]) { - OWSFailDebug(@"%@ Was expecting SignedPreKeyRecord, but found: %@", - tag, - [signedPreKeyObject class]); - return; - } - SignedPreKeyRecord *signedPreKeyRecord - = (SignedPreKeyRecord *)signedPreKeyObject; - OWSLogInfo(@"%@ #%d -#import -#import -#import #import #import diff --git a/SignalUtilitiesKit/LokiSessionRestorationImplementation.swift b/SignalUtilitiesKit/LokiSessionRestorationImplementation.swift deleted file mode 100644 index c828082b5..000000000 --- a/SignalUtilitiesKit/LokiSessionRestorationImplementation.swift +++ /dev/null @@ -1,47 +0,0 @@ -import SessionProtocolKit - -@objc(SNSessionRestorationImplementation) -public final class SessionRestorationImplementation : NSObject, SessionRestorationProtocol { - - private var storage: OWSPrimaryStorage { - return OWSPrimaryStorage.shared() - } - - enum Error : LocalizedError { - case missingPreKey - case invalidPreKeyID - } - - public func validatePreKeyWhisperMessage(for publicKey: String, preKeyWhisperMessage: PreKeyWhisperMessage, using transaction: Any) throws { - guard let transaction = transaction as? YapDatabaseReadTransaction else { return } - guard let storedPreKey = storage.getPreKeyRecord(forContact: publicKey, transaction: transaction) else { - SNLog("Missing pre key bundle.") - throw Error.missingPreKey - } - guard storedPreKey.id == preKeyWhisperMessage.prekeyID else { - SNLog("Received a PreKeyWhisperMessage from an unknown source.") - throw Error.invalidPreKeyID - } - } - - public func getSessionRestorationStatus(for publicKey: String) -> SessionRestorationStatus { - var thread: TSContactThread? - Storage.read { transaction in - thread = TSContactThread.getWithContactId(publicKey, transaction: transaction) - } - return .none - } - - public func handleNewSessionAdopted(for publicKey: String, using transaction: Any) { - guard let transaction = transaction as? YapDatabaseReadWriteTransaction else { return } - guard !publicKey.isEmpty else { return } - guard let thread = TSContactThread.getWithContactId(publicKey, transaction: transaction) else { - return SNLog("A new session was adopted but the thread couldn't be found for: \(publicKey).") - } - // Notify the user - let infoMessage = TSInfoMessage(timestamp: NSDate.ows_millisecondTimeStamp(), in: thread, messageType: .typeLokiSessionResetDone) - infoMessage.save(with: transaction) - // Update the session reset status - thread.save(with: transaction) - } -} diff --git a/SignalUtilitiesKit/Messaging/TSInvalidIdentityKeySendingErrorMessage.h b/SignalUtilitiesKit/Messaging/TSInvalidIdentityKeySendingErrorMessage.h deleted file mode 100644 index 3357153ca..000000000 --- a/SignalUtilitiesKit/Messaging/TSInvalidIdentityKeySendingErrorMessage.h +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@class PreKeyBundle; -@class TSOutgoingMessage; -@class TSThread; - -extern NSString *TSInvalidPreKeyBundleKey; -extern NSString *TSInvalidRecipientKey; - -// DEPRECATED - we no longer create new instances of this class (as of mid-2017); However, existing instances may -// exist, so we should keep this class around to honor their old behavior. -__attribute__((deprecated)) @interface TSInvalidIdentityKeySendingErrorMessage : TSInvalidIdentityKeyErrorMessage - -@property (nonatomic, readonly) NSString *messageId; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SignalUtilitiesKit/Messaging/TSInvalidIdentityKeySendingErrorMessage.m b/SignalUtilitiesKit/Messaging/TSInvalidIdentityKeySendingErrorMessage.m deleted file mode 100644 index b3649a09d..000000000 --- a/SignalUtilitiesKit/Messaging/TSInvalidIdentityKeySendingErrorMessage.m +++ /dev/null @@ -1,60 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "TSInvalidIdentityKeySendingErrorMessage.h" -#import "OWSIdentityManager.h" -#import "OWSPrimaryStorage+SessionStore.h" -#import "OWSPrimaryStorage.h" -#import "PreKeyBundle+jsonDict.h" -#import "TSContactThread.h" -#import "TSErrorMessage_privateConstructor.h" -#import "TSOutgoingMessage.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -NSString *TSInvalidPreKeyBundleKey = @"TSInvalidPreKeyBundleKey"; -NSString *TSInvalidRecipientKey = @"TSInvalidRecipientKey"; - -@interface TSInvalidIdentityKeySendingErrorMessage () - -@property (nonatomic, readonly) PreKeyBundle *preKeyBundle; - -@end - -// DEPRECATED - we no longer create new instances of this class (as of mid-2017); However, existing instances may -// exist, so we should keep this class around to honor their old behavior. -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-implementations" -@implementation TSInvalidIdentityKeySendingErrorMessage -#pragma clang diagnostic pop - -- (void)throws_acceptNewIdentityKey -{ - // Shouldn't really get here, since we're no longer creating blocking SN changes. - // But there may still be some old unaccepted SN errors in the wild that need to be accepted. - OWSFailDebug(@"accepting new identity key is deprecated."); - - NSData *_Nullable newIdentityKey = [self throws_newIdentityKey]; - if (!newIdentityKey) { - OWSFailDebug(@"newIdentityKey is unexpectedly nil. Bad Prekey bundle?: %@", self.preKeyBundle); - return; - } - - [[OWSIdentityManager sharedManager] saveRemoteIdentity:newIdentityKey recipientId:self.recipientId]; -} - -- (nullable NSData *)throws_newIdentityKey -{ - return [self.preKeyBundle.identityKey throws_removeKeyType]; -} - -- (NSString *)theirSignalId -{ - return self.recipientId; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SignalUtilitiesKit/Meta/SignalUtilitiesKit.h b/SignalUtilitiesKit/Meta/SignalUtilitiesKit.h index 691dacfdb..0dc952ed4 100644 --- a/SignalUtilitiesKit/Meta/SignalUtilitiesKit.h +++ b/SignalUtilitiesKit/Meta/SignalUtilitiesKit.h @@ -24,9 +24,6 @@ FOUNDATION_EXPORT const unsigned char SignalUtilitiesKitVersionString[]; #import #import #import -#import -#import -#import #import #import #import @@ -43,7 +40,6 @@ FOUNDATION_EXPORT const unsigned char SignalUtilitiesKitVersionString[]; #import #import #import -#import #import #import #import diff --git a/SignalUtilitiesKit/OWSRecordTranscriptJob.m b/SignalUtilitiesKit/OWSRecordTranscriptJob.m index e505e89d3..8999ed92d 100644 --- a/SignalUtilitiesKit/OWSRecordTranscriptJob.m +++ b/SignalUtilitiesKit/OWSRecordTranscriptJob.m @@ -5,7 +5,6 @@ #import "OWSRecordTranscriptJob.h" #import "OWSAttachmentDownloads.h" #import "OWSDisappearingMessagesJob.h" -#import "OWSPrimaryStorage+SessionStore.h" #import "OWSReadReceiptManager.h" #import "SSKEnvironment.h" #import "TSAttachmentPointer.h" diff --git a/SignalUtilitiesKit/OWSUDManager.swift b/SignalUtilitiesKit/OWSUDManager.swift deleted file mode 100644 index 080ec0f32..000000000 --- a/SignalUtilitiesKit/OWSUDManager.swift +++ /dev/null @@ -1,433 +0,0 @@ -// -// Copyright (c) 2019 Open Whisper Systems. All rights reserved. -// - -import Foundation -import PromiseKit - - - -public enum OWSUDError: Error { - case assertionError(description: String) - case invalidData(description: String) -} - -@objc -public enum OWSUDCertificateExpirationPolicy: Int { - // We want to try to rotate the sender certificate - // on a frequent basis, but we don't want to block - // sending on this. - case strict - case permissive -} - -private func string(forUnidentifiedAccessMode mode: UnidentifiedAccessMode) -> String { - switch mode { - case .unknown: - return "unknown" - case .enabled: - return "enabled" - case .disabled: - return "disabled" - case .unrestricted: - return "unrestricted" - } -} - -// MARK: - - -@objc -public class OWSUDManagerImpl: NSObject, OWSUDManager { - - private let dbConnection: YapDatabaseConnection - - // MARK: Local Configuration State - private let kUDCollection = "kUDCollection" - private let kUDCurrentSenderCertificateKey_Production = "kUDCurrentSenderCertificateKey_Production" - private let kUDCurrentSenderCertificateKey_Staging = "kUDCurrentSenderCertificateKey_Staging" - private let kUDCurrentSenderCertificateDateKey_Production = "kUDCurrentSenderCertificateDateKey_Production" - private let kUDCurrentSenderCertificateDateKey_Staging = "kUDCurrentSenderCertificateDateKey_Staging" - private let kUDUnrestrictedAccessKey = "kUDUnrestrictedAccessKey" - - // MARK: Recipient State - private let kUnidentifiedAccessCollection = "kUnidentifiedAccessCollection" - - var certificateValidator: SMKCertificateValidator - - @objc - public required init(primaryStorage: OWSPrimaryStorage) { - self.dbConnection = primaryStorage.newDatabaseConnection() - self.certificateValidator = SMKCertificateDefaultValidator(trustRoot: OWSUDManagerImpl.trustRoot()) - - super.init() - - SwiftSingletons.register(self) - } - - @objc public func setup() { - AppReadiness.runNowOrWhenAppDidBecomeReady { - guard self.tsAccountManager.isRegistered() else { - return - } - - // Any error is silently ignored on startup. - self.ensureSenderCertificate(certificateExpirationPolicy: .strict).retainUntilComplete() - } - NotificationCenter.default.addObserver(self, - selector: #selector(registrationStateDidChange), - name: .RegistrationStateDidChange, - object: nil) - NotificationCenter.default.addObserver(self, - selector: #selector(didBecomeActive), - name: NSNotification.Name.OWSApplicationDidBecomeActive, - object: nil) - } - - @objc - func registrationStateDidChange() { - AssertIsOnMainThread() - - guard tsAccountManager.isRegisteredAndReady() else { - return - } - - // Any error is silently ignored - ensureSenderCertificate(certificateExpirationPolicy: .strict).retainUntilComplete() - } - - @objc func didBecomeActive() { - AssertIsOnMainThread() - - AppReadiness.runNowOrWhenAppDidBecomeReady { - guard self.tsAccountManager.isRegistered() else { - return - } - - // Any error is silently ignored on startup. - self.ensureSenderCertificate(certificateExpirationPolicy: .strict).retainUntilComplete() - } - } - - // MARK: - - - @objc - public func isUDVerboseLoggingEnabled() -> Bool { - return false - } - - // MARK: - Dependencies - - private var profileManager: ProfileManagerProtocol { - return SSKEnvironment.shared.profileManager - } - - private var tsAccountManager: TSAccountManager { - return TSAccountManager.sharedInstance() - } - - // MARK: - Recipient state - - @objc - public func randomUDAccessKey() -> SMKUDAccessKey { - return SMKUDAccessKey(randomKeyData: ()) - } - - private func unidentifiedAccessMode(forRecipientId recipientId: String, - isLocalNumber: Bool, - transaction: YapDatabaseReadTransaction) -> UnidentifiedAccessMode { - let defaultValue: UnidentifiedAccessMode = isLocalNumber ? .enabled : .unknown - guard let existingRawValue = transaction.object(forKey: recipientId, inCollection: kUnidentifiedAccessCollection) as? Int else { - return defaultValue - } - guard let existingValue = UnidentifiedAccessMode(rawValue: existingRawValue) else { - owsFailDebug("Couldn't parse mode value.") - return defaultValue - } - return existingValue - } - - @objc - public func unidentifiedAccessMode(forRecipientId recipientId: String) -> UnidentifiedAccessMode { - var isLocalNumber = false - if let localNumber = tsAccountManager.localNumber() { - isLocalNumber = recipientId == localNumber - } - - var mode: UnidentifiedAccessMode = .unknown - dbConnection.read { (transaction) in - mode = self.unidentifiedAccessMode(forRecipientId: recipientId, isLocalNumber: isLocalNumber, transaction: transaction) - } - return mode - } - - @objc - public func setUnidentifiedAccessMode(_ mode: UnidentifiedAccessMode, recipientId: String) { - var isLocalNumber = false - if let localNumber = tsAccountManager.localNumber() { - if recipientId == localNumber { - Logger.info("Setting local UD access mode: \(string(forUnidentifiedAccessMode: mode))") - isLocalNumber = true - } - } - - Storage.writeSync { (transaction) in - let oldMode = self.unidentifiedAccessMode(forRecipientId: recipientId, isLocalNumber: isLocalNumber, transaction: transaction) - - transaction.setObject(mode.rawValue as Int, forKey: recipientId, inCollection: self.kUnidentifiedAccessCollection) - - if mode != oldMode { - Logger.info("Setting UD access mode for \(recipientId): \(string(forUnidentifiedAccessMode: oldMode)) -> \(string(forUnidentifiedAccessMode: mode))") - } - } - } - - // Returns the UD access key for a given recipient - // if we have a valid profile key for them. - @objc - public func udAccessKey(forRecipientId recipientId: String) -> SMKUDAccessKey? { - guard let profileKey = profileManager.profileKeyData(forRecipientId: recipientId) else { - // Mark as "not a UD recipient". - return nil - } - do { - let udAccessKey = try SMKUDAccessKey(profileKey: profileKey) - return udAccessKey - } catch { - Logger.error("Could not determine udAccessKey: \(error)") - return nil - } - } - - // Returns the UD access key for sending to a given recipient. - @objc - public func udAccess(forRecipientId recipientId: String, - requireSyncAccess: Bool) -> OWSUDAccess? { - if requireSyncAccess { - guard let localNumber = tsAccountManager.localNumber() else { - if isUDVerboseLoggingEnabled() { - Logger.info("UD disabled for \(recipientId), no local number.") - } - owsFailDebug("Missing local number.") - return nil - } - if localNumber != recipientId { - let selfAccessMode = unidentifiedAccessMode(forRecipientId: localNumber) - guard selfAccessMode != .disabled else { - if isUDVerboseLoggingEnabled() { - Logger.info("UD disabled for \(recipientId), UD disabled for sync messages.") - } - return nil - } - } - } - - let accessMode = unidentifiedAccessMode(forRecipientId: recipientId) - switch accessMode { - case .unrestricted: - // Unrestricted users should use a random key. - if isUDVerboseLoggingEnabled() { - Logger.info("UD enabled for \(recipientId) with random key.") - } - let udAccessKey = randomUDAccessKey() - return OWSUDAccess(udAccessKey: udAccessKey, udAccessMode: accessMode, isRandomKey: true) - case .unknown: - // Unknown users should use a derived key if possible, - // and otherwise use a random key. - if let udAccessKey = udAccessKey(forRecipientId: recipientId) { - if isUDVerboseLoggingEnabled() { - Logger.info("UD unknown for \(recipientId); trying derived key.") - } - return OWSUDAccess(udAccessKey: udAccessKey, udAccessMode: accessMode, isRandomKey: false) - } else { - if isUDVerboseLoggingEnabled() { - Logger.info("UD unknown for \(recipientId); trying random key.") - } - let udAccessKey = randomUDAccessKey() - return OWSUDAccess(udAccessKey: udAccessKey, udAccessMode: accessMode, isRandomKey: true) - } - case .enabled: - guard let udAccessKey = udAccessKey(forRecipientId: recipientId) else { - if isUDVerboseLoggingEnabled() { - Logger.info("UD disabled for \(recipientId), no profile key for this recipient.") - } - if (!CurrentAppContext().isRunningTests) { - owsFailDebug("Couldn't find profile key for UD-enabled user.") - } - return nil - } - if isUDVerboseLoggingEnabled() { - Logger.info("UD enabled for \(recipientId).") - } - return OWSUDAccess(udAccessKey: udAccessKey, udAccessMode: accessMode, isRandomKey: false) - case .disabled: - if isUDVerboseLoggingEnabled() { - Logger.info("UD disabled for \(recipientId), UD not enabled for this recipient.") - } - return nil - } - } - - // MARK: - Sender Certificate - - #if DEBUG - @objc - public func hasSenderCertificate() -> Bool { - return senderCertificate(certificateExpirationPolicy: .permissive) != nil - } - #endif - - private func senderCertificate(certificateExpirationPolicy: OWSUDCertificateExpirationPolicy) -> SMKSenderCertificate? { - if certificateExpirationPolicy == .strict { - guard let certificateDate = dbConnection.object(forKey: senderCertificateDateKey(), inCollection: kUDCollection) as? Date else { - return nil - } - guard certificateDate.timeIntervalSinceNow < kDayInterval else { - // Discard certificates that we obtained more than 24 hours ago. - return nil - } - } - - guard let certificateData = dbConnection.object(forKey: senderCertificateKey(), inCollection: kUDCollection) as? Data else { - return nil - } - - do { - let certificate = try SMKSenderCertificate.parse(data: certificateData) - - guard isValidCertificate(certificate) else { - Logger.warn("Current sender certificate is not valid.") - return nil - } - - return certificate - } catch { - owsFailDebug("Certificate could not be parsed: \(error)") - return nil - } - } - - func setSenderCertificate(_ certificateData: Data) { - dbConnection.setObject(Date(), forKey: senderCertificateDateKey(), inCollection: kUDCollection) - dbConnection.setObject(certificateData, forKey: senderCertificateKey(), inCollection: kUDCollection) - } - - private func senderCertificateKey() -> String { - return IsUsingProductionService() ? kUDCurrentSenderCertificateKey_Production : kUDCurrentSenderCertificateKey_Staging - } - - private func senderCertificateDateKey() -> String { - return IsUsingProductionService() ? kUDCurrentSenderCertificateDateKey_Production : kUDCurrentSenderCertificateDateKey_Staging - } - - @objc - public func ensureSenderCertificate(success:@escaping (SMKSenderCertificate) -> Void, - failure:@escaping (Error) -> Void) { - return ensureSenderCertificate(certificateExpirationPolicy: .permissive, - success: success, - failure: failure) - } - - private func ensureSenderCertificate(certificateExpirationPolicy: OWSUDCertificateExpirationPolicy, - success:@escaping (SMKSenderCertificate) -> Void, - failure:@escaping (Error) -> Void) { - firstly { - ensureSenderCertificate(certificateExpirationPolicy: certificateExpirationPolicy) - }.map { certificate in - success(certificate) - }.catch { error in - failure(error) - }.retainUntilComplete() - } - - public func ensureSenderCertificate(certificateExpirationPolicy: OWSUDCertificateExpirationPolicy) -> Promise { - // Try to obtain a new sender certificate. - return firstly { - generateSenderCertificate() - }.map { (certificateData: Data, certificate: SMKSenderCertificate) in - - // Cache the current sender certificate. - self.setSenderCertificate(certificateData) - - return certificate - } - } - - private func generateSenderCertificate() -> Promise<(certificateData: Data, certificate: SMKSenderCertificate)> { - return Promise<(certificateData: Data, certificate: SMKSenderCertificate)> { seal in - // Loki: Generate a sender certificate locally - guard let sender = OWSIdentityManager.shared().identityKeyPair()?.hexEncodedPublicKey else { seal.reject(OWSUDError.assertionError(description: "")); return } - let certificate = SMKSenderCertificate(senderDeviceId: 1, senderRecipientId: sender) - let certificateAsData = try certificate.serialized() - guard isValidCertificate(certificate) else { - throw OWSUDError.invalidData(description: "Invalid sender certificate.") - } - seal.fulfill((certificateData: certificateAsData, certificate: certificate)) - } - } - - @objc - public func getSenderCertificate() -> SMKSenderCertificate? { - do { - let sender = OWSIdentityManager.shared().identityKeyPair()!.hexEncodedPublicKey - let certificate = SMKSenderCertificate(senderDeviceId: 1, senderRecipientId: sender) - guard self.isValidCertificate(certificate) else { - throw OWSUDError.invalidData(description: "Invalid sender certificate returned by server") - } - return certificate - } catch { - SNLog("Couldn't get UD sender certificate due to error: \(error).") - return nil - } - } - - private func isValidCertificate(_ certificate: SMKSenderCertificate) -> Bool { - // Ensure that the certificate will not expire in the next hour. - // We want a threshold long enough to ensure that any outgoing message - // sends will complete before the expiration. - let nowMs = NSDate.ows_millisecondTimeStamp() - let anHourFromNowMs = nowMs + kHourInMs - - do { - try certificateValidator.throwswrapped_validate(senderCertificate: certificate, validationTime: anHourFromNowMs) - return true - } catch { - OWSLogger.error("Invalid certificate") - return false - } - } - - @objc - public func trustRoot() -> ECPublicKey { - return OWSUDManagerImpl.trustRoot() - } - - @objc - public class func trustRoot() -> ECPublicKey { - guard let trustRootData = NSData(fromBase64String: kUDTrustRoot) else { - // This exits. - owsFail("Invalid trust root data.") - } - - do { - return try ECPublicKey(serializedKeyData: trustRootData as Data) - } catch { - // This exits. - owsFail("Invalid trust root.") - } - } - - // MARK: - Unrestricted Access - - @objc - public func shouldAllowUnrestrictedAccessLocal() -> Bool { - return dbConnection.bool(forKey: kUDUnrestrictedAccessKey, inCollection: kUDCollection, defaultValue: false) - } - - @objc - public func setShouldAllowUnrestrictedAccessLocal(_ value: Bool) { - dbConnection.setBool(value, forKey: kUDUnrestrictedAccessKey, inCollection: kUDCollection) - - // Try to update the account attributes to reflect this change. - tsAccountManager.updateAccountAttributes().retainUntilComplete() - } -} diff --git a/SignalUtilitiesKit/PreKeyBundle+jsonDict.h b/SignalUtilitiesKit/PreKeyBundle+jsonDict.h deleted file mode 100644 index c0ca91121..000000000 --- a/SignalUtilitiesKit/PreKeyBundle+jsonDict.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Copyright (c) 2017 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface PreKeyBundle (jsonDict) - -+ (nullable PreKeyBundle *)preKeyBundleFromDictionary:(NSDictionary *)dictionary forDeviceNumber:(NSNumber *)number; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SignalUtilitiesKit/PreKeyBundle+jsonDict.m b/SignalUtilitiesKit/PreKeyBundle+jsonDict.m deleted file mode 100644 index 306f477c5..000000000 --- a/SignalUtilitiesKit/PreKeyBundle+jsonDict.m +++ /dev/null @@ -1,110 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -#import "PreKeyBundle+jsonDict.h" -#import - -NS_ASSUME_NONNULL_BEGIN - -@implementation PreKeyBundle (jsonDict) - -+ (nullable PreKeyBundle *)preKeyBundleFromDictionary:(NSDictionary *)dictionary forDeviceNumber:(NSNumber *)number -{ - PreKeyBundle *bundle = nil; - - id identityKeyObject = [dictionary objectForKey:@"identityKey"]; - if (![identityKeyObject isKindOfClass:[NSString class]]) { - OWSFailDebug(@"Unexpected identityKeyObject: %@", [identityKeyObject class]); - return nil; - } - NSString *identityKeyString = (NSString *)identityKeyObject; - - id devicesObject = [dictionary objectForKey:@"devices"]; - if (![devicesObject isKindOfClass:[NSArray class]]) { - OWSFailDebug(@"Unexpected devicesObject: %@", [devicesObject class]); - return nil; - } - NSArray *devicesArray = (NSArray *)devicesObject; - - NSData *identityKey = [NSData dataFromBase64StringNoPadding:identityKeyString]; - - for (NSDictionary *deviceDict in devicesArray) { - NSNumber *registrationIdString = [deviceDict objectForKey:@"registrationId"]; - NSNumber *deviceIdString = [deviceDict objectForKey:@"deviceId"]; - - if (!(registrationIdString && deviceIdString)) { - OWSLogError(@"Failed to get the registration id and device id"); - return nil; - } - - if (![deviceIdString isEqualToNumber:number]) { - OWSLogWarn(@"Got a keyid for another device"); - return nil; - } - - int registrationId = [registrationIdString intValue]; - int deviceId = [deviceIdString intValue]; - - NSDictionary *_Nullable preKeyDict; - id optionalPreKeyDict = [deviceDict objectForKey:@"preKey"]; - // JSON parsing might give us NSNull, so we can't simply check for non-nil. - if ([optionalPreKeyDict isKindOfClass:[NSDictionary class]]) { - preKeyDict = (NSDictionary *)optionalPreKeyDict; - } - - int prekeyId; - NSData *_Nullable preKeyPublic; - - if (!preKeyDict) { - OWSLogInfo(@"No one-time prekey included in the bundle."); - prekeyId = -1; - } else { - prekeyId = [[preKeyDict objectForKey:@"keyId"] intValue]; - NSString *preKeyPublicString = [preKeyDict objectForKey:@"publicKey"]; - preKeyPublic = [NSData dataFromBase64StringNoPadding:preKeyPublicString]; - } - - NSDictionary *signedPrekey = [deviceDict objectForKey:@"signedPreKey"]; - - if (![signedPrekey isKindOfClass:[NSDictionary class]]) { - OWSLogError(@"Device doesn't have signed prekeys registered"); - return nil; - } - - NSNumber *signedKeyIdNumber = [signedPrekey objectForKey:@"keyId"]; - NSString *signedSignatureString = [signedPrekey objectForKey:@"signature"]; - NSString *signedPublicKeyString = [signedPrekey objectForKey:@"publicKey"]; - - - if (!(signedKeyIdNumber && signedPublicKeyString && signedSignatureString)) { - OWSLogError(@"Missing signed key material"); - return nil; - } - - NSData *signedPrekeyPublic = [NSData dataFromBase64StringNoPadding:signedPublicKeyString]; - NSData *signedPreKeySignature = [NSData dataFromBase64StringNoPadding:signedSignatureString]; - - if (!(signedPrekeyPublic && signedPreKeySignature)) { - OWSLogError(@"Failed to parse signed keying material"); - return nil; - } - - int signedPreKeyId = [signedKeyIdNumber intValue]; - - bundle = [[self alloc] initWithRegistrationId:registrationId - deviceId:deviceId - preKeyId:prekeyId - preKeyPublic:preKeyPublic - signedPreKeyPublic:signedPrekeyPublic - signedPreKeyId:signedPreKeyId - signedPreKeySignature:signedPreKeySignature - identityKey:identityKey]; - } - - return bundle; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SignalUtilitiesKit/PreKeyRefreshOperation.swift b/SignalUtilitiesKit/PreKeyRefreshOperation.swift deleted file mode 100644 index d313dbe30..000000000 --- a/SignalUtilitiesKit/PreKeyRefreshOperation.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation -import PromiseKit - -// We generate 100 one-time prekeys at a time. We should replenish -// whenever ~2/3 of them have been consumed. -let kEphemeralPreKeysMinimumCount: UInt = 35 - -@objc(SSKRefreshPreKeysOperation) -public class RefreshPreKeysOperation: OWSOperation { - - private var tsAccountManager: TSAccountManager { - return TSAccountManager.sharedInstance() - } - - private var identityKeyManager: OWSIdentityManager { - return OWSIdentityManager.shared() - } - - public override func run() { - Logger.debug("") - - guard tsAccountManager.isRegistered() else { - Logger.debug("Skipping pre key refresh; user isn't registered.") - return - } - - DispatchQueue.global().async { - let storage = OWSPrimaryStorage.shared() - guard storage.currentSignedPrekeyId() == nil else { return } - let signedPreKeyRecord = storage.generateRandomSignedRecord() - signedPreKeyRecord.markAsAcceptedByService() - storage.storeSignedPreKey(signedPreKeyRecord.id, signedPreKeyRecord: signedPreKeyRecord) - storage.setCurrentSignedPrekeyId(signedPreKeyRecord.id) - TSPreKeyManager.clearPreKeyUpdateFailureCount() - TSPreKeyManager.clearSignedPreKeyRecords() - SNLog("Signed pre key refreshed successfully.") - self.reportSuccess() - } - } - - public override func didSucceed() { - TSPreKeyManager.refreshPreKeysDidSucceed() - } - - override public func didFail(error: Error) { - Logger.debug("Don't report SPK rotation failure w/ non NetworkManager error: \(error)") - } -} diff --git a/SignalUtilitiesKit/RotateSignedKeyOperation.swift b/SignalUtilitiesKit/RotateSignedKeyOperation.swift deleted file mode 100644 index c92d86453..000000000 --- a/SignalUtilitiesKit/RotateSignedKeyOperation.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright (c) 2018 Open Whisper Systems. All rights reserved. -// - -import Foundation -import PromiseKit - -@objc(SSKRotateSignedPreKeyOperation) -public class RotateSignedPreKeyOperation: OWSOperation { - private var tsAccountManager: TSAccountManager { - return TSAccountManager.sharedInstance() - } - - public override func run() { - Logger.debug("") - - guard tsAccountManager.isRegistered() else { - Logger.debug("skipping - not registered") - return - } - - DispatchQueue.global().async { - let storage = OWSPrimaryStorage.shared() - let signedPreKeyRecord = storage.generateRandomSignedRecord() - signedPreKeyRecord.markAsAcceptedByService() - storage.storeSignedPreKey(signedPreKeyRecord.id, signedPreKeyRecord: signedPreKeyRecord) - storage.setCurrentSignedPrekeyId(signedPreKeyRecord.id) - TSPreKeyManager.clearPreKeyUpdateFailureCount() - TSPreKeyManager.clearSignedPreKeyRecords() - SNLog("Signed pre key rotated successfully.") - self.reportSuccess() - } - } - - override public func didFail(error: Error) { - Logger.debug("don't report SPK rotation failure w/ non NetworkManager error: \(error)") - } -} diff --git a/SignalUtilitiesKit/TSPreKeyManager.h b/SignalUtilitiesKit/TSPreKeyManager.h deleted file mode 100644 index 76c0cdaed..000000000 --- a/SignalUtilitiesKit/TSPreKeyManager.h +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright (c) 2019 Open Whisper Systems. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface TSPreKeyManager : NSObject - -#pragma mark - State Tracking - -+ (BOOL)isAppLockedDueToPreKeyUpdateFailures; - -+ (void)incrementPreKeyUpdateFailureCount; - -+ (void)clearPreKeyUpdateFailureCount; - -+ (void)clearSignedPreKeyRecords; - -// This should only be called from the TSPreKeyManager.operationQueue -+ (void)refreshPreKeysDidSucceed; - -#pragma mark - Check/Request Initiation - -+ (void)rotateSignedPreKeyWithSuccess:(void (^)(void))successHandler failure:(void (^)(NSError *error))failureHandler; - -+ (void)createPreKeysWithSuccess:(void (^)(void))successHandler failure:(void (^)(NSError *error))failureHandler; - -+ (void)checkPreKeys; - -+ (void)checkPreKeysIfNecessary; - -@end - -NS_ASSUME_NONNULL_END diff --git a/SignalUtilitiesKit/TSPreKeyManager.m b/SignalUtilitiesKit/TSPreKeyManager.m deleted file mode 100644 index 91ea8857d..000000000 --- a/SignalUtilitiesKit/TSPreKeyManager.m +++ /dev/null @@ -1,292 +0,0 @@ -// -// Copyright (c) 2019 Open Whisper Systems. All rights reserved. -// - -#import "TSPreKeyManager.h" -#import "AppContext.h" -#import "NSURLSessionDataTask+StatusCode.h" -#import "OWSIdentityManager.h" -#import "OWSPrimaryStorage+SignedPreKeyStore.h" -#import "SSKEnvironment.h" - -#import "TSStorageHeaders.h" -#import -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -// Time before deletion of signed prekeys (measured in seconds) -#define kSignedPreKeysDeletionTime (7 * kDayInterval) - -// Time before rotation of signed prekeys (measured in seconds) -#define kSignedPreKeyRotationTime (2 * kDayInterval) - -// How often we check prekey state on app activation. -#define kPreKeyCheckFrequencySeconds (12 * kHourInterval) - -// This global should only be accessed on prekeyQueue. -static NSDate *lastPreKeyCheckTimestamp = nil; - -// Maximum number of failures while updating signed prekeys -// before the message sending is disabled. -static const NSUInteger kMaxPrekeyUpdateFailureCount = 5; - -// Maximum amount of time that can elapse without updating signed prekeys -// before the message sending is disabled. -#define kSignedPreKeyUpdateFailureMaxFailureDuration (10 * kDayInterval) - -#pragma mark - - -@implementation TSPreKeyManager - -#pragma mark - Dependencies - -+ (TSAccountManager *)tsAccountManager -{ - OWSAssertDebug(SSKEnvironment.shared.tsAccountManager); - - return SSKEnvironment.shared.tsAccountManager; -} - -#pragma mark - State Tracking - -+ (BOOL)isAppLockedDueToPreKeyUpdateFailures -{ - // Only disable message sending if we have failed more than N times - // over a period of at least M days. - OWSPrimaryStorage *primaryStorage = [OWSPrimaryStorage sharedManager]; - return ([primaryStorage prekeyUpdateFailureCount] >= kMaxPrekeyUpdateFailureCount && - [primaryStorage firstPrekeyUpdateFailureDate] != nil - && fabs([[primaryStorage firstPrekeyUpdateFailureDate] timeIntervalSinceNow]) - >= kSignedPreKeyUpdateFailureMaxFailureDuration); -} - -+ (void)incrementPreKeyUpdateFailureCount -{ - // Record a prekey update failure. - OWSPrimaryStorage *primaryStorage = [OWSPrimaryStorage sharedManager]; - int failureCount = [primaryStorage incrementPrekeyUpdateFailureCount]; - OWSLogInfo(@"new failureCount: %d", failureCount); - - if (failureCount == 1 || ![primaryStorage firstPrekeyUpdateFailureDate]) { - // If this is the "first" failure, record the timestamp of that - // failure. - [primaryStorage setFirstPrekeyUpdateFailureDate:[NSDate new]]; - } -} - -+ (void)clearPreKeyUpdateFailureCount -{ - OWSPrimaryStorage *primaryStorage = [OWSPrimaryStorage sharedManager]; - [primaryStorage clearFirstPrekeyUpdateFailureDate]; - [primaryStorage clearPrekeyUpdateFailureCount]; -} - -+ (void)refreshPreKeysDidSucceed -{ - lastPreKeyCheckTimestamp = [NSDate new]; -} - -#pragma mark - Check/Request Initiation - -+ (NSOperationQueue *)operationQueue -{ - static dispatch_once_t onceToken; - static NSOperationQueue *operationQueue; - - // PreKey state lives in two places - on the client and on the service. - // Some of our pre-key operations depend on the service state, e.g. we need to check our one-time-prekey count - // before we decide to upload new ones. This potentially entails multiple async operations, all of which should - // complete before starting any other pre-key operation. That's why a dispatch_queue is insufficient for - // coordinating PreKey operations and instead we use NSOperation's on a serial NSOperationQueue. - dispatch_once(&onceToken, ^{ - operationQueue = [NSOperationQueue new]; - operationQueue.name = @"TSPreKeyManager"; - operationQueue.maxConcurrentOperationCount = 1; - }); - return operationQueue; -} - -+ (void)checkPreKeysIfNecessary -{ - if (!CurrentAppContext().isMainAppAndActive) { - return; - } - if (!self.tsAccountManager.isRegisteredAndReady) { - return; - } - - SSKRefreshPreKeysOperation *refreshOperation = [SSKRefreshPreKeysOperation new]; - - __weak SSKRefreshPreKeysOperation *weakRefreshOperation = refreshOperation; - NSBlockOperation *checkIfRefreshNecessaryOperation = [NSBlockOperation blockOperationWithBlock:^{ - BOOL shouldCheck = (lastPreKeyCheckTimestamp == nil - || fabs([lastPreKeyCheckTimestamp timeIntervalSinceNow]) >= kPreKeyCheckFrequencySeconds); - if (!shouldCheck) { - [weakRefreshOperation cancel]; - } - }]; - - [refreshOperation addDependency:checkIfRefreshNecessaryOperation]; - - SSKRotateSignedPreKeyOperation *rotationOperation = [SSKRotateSignedPreKeyOperation new]; - - __weak SSKRotateSignedPreKeyOperation *weakRotationOperation = rotationOperation; - NSBlockOperation *checkIfRotationNecessaryOperation = [NSBlockOperation blockOperationWithBlock:^{ - OWSPrimaryStorage *primaryStorage = [OWSPrimaryStorage sharedManager]; - SignedPreKeyRecord *_Nullable signedPreKey = [primaryStorage currentSignedPreKey]; - - BOOL shouldCheck - = !signedPreKey || fabs(signedPreKey.generatedAt.timeIntervalSinceNow) >= kSignedPreKeyRotationTime; - if (!shouldCheck) { - [weakRotationOperation cancel]; - } - }]; - - [rotationOperation addDependency:checkIfRotationNecessaryOperation]; - - // Order matters here - if we rotated *before* refreshing, we'd risk uploading - // two SPK's in a row since RefreshPreKeysOperation can also upload a new SPK. - [checkIfRotationNecessaryOperation addDependency:refreshOperation]; - - NSArray *operations = - @[ checkIfRefreshNecessaryOperation, refreshOperation, checkIfRotationNecessaryOperation, rotationOperation ]; - [self.operationQueue addOperations:operations waitUntilFinished:NO]; -} - -+ (void)createPreKeysWithSuccess:(void (^)(void))successHandler failure:(void (^)(NSError *error))failureHandler -{ - OWSAssertDebug(!self.tsAccountManager.isRegisteredAndReady); - - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - SSKCreatePreKeysOperation *operation = [SSKCreatePreKeysOperation new]; - [self.operationQueue addOperations:@[ operation ] waitUntilFinished:YES]; - - NSError *_Nullable error = operation.failingError; - if (error) { - dispatch_async(dispatch_get_main_queue(), ^{ - failureHandler(error); - }); - } else { - dispatch_async(dispatch_get_main_queue(), ^{ - successHandler(); - }); - } - }); -} - -+ (void)rotateSignedPreKeyWithSuccess:(void (^)(void))successHandler failure:(void (^)(NSError *error))failureHandler -{ - OWSAssertDebug(!self.tsAccountManager.isRegisteredAndReady); - - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - SSKRotateSignedPreKeyOperation *operation = [SSKRotateSignedPreKeyOperation new]; - [self.operationQueue addOperations:@[ operation ] waitUntilFinished:YES]; - - NSError *_Nullable error = operation.failingError; - if (error) { - dispatch_async(dispatch_get_main_queue(), ^{ - failureHandler(error); - }); - } else { - dispatch_async(dispatch_get_main_queue(), ^{ - successHandler(); - }); - } - }); -} - -+ (void)checkPreKeys -{ - if (!CurrentAppContext().isMainApp) { return; } - if (!self.tsAccountManager.isRegisteredAndReady) { return; } - SSKRefreshPreKeysOperation *operation = [SSKRefreshPreKeysOperation new]; - [self.operationQueue addOperation:operation]; -} - -+ (void)clearSignedPreKeyRecords { - OWSPrimaryStorage *primaryStorage = [OWSPrimaryStorage sharedManager]; - NSNumber *_Nullable currentSignedPrekeyId = [primaryStorage currentSignedPrekeyId]; - [self clearSignedPreKeyRecordsWithKeyId:currentSignedPrekeyId]; -} - -+ (void)clearSignedPreKeyRecordsWithKeyId:(NSNumber *_Nullable)keyId -{ - if (!keyId) { - // currentSignedPreKeyId should only be nil before we've completed registration. - // We have this guard here for robustness, but we should never get here. - return; - } - - OWSPrimaryStorage *primaryStorage = [OWSPrimaryStorage sharedManager]; - SignedPreKeyRecord *currentRecord = [primaryStorage loadSignedPrekeyOrNil:keyId.intValue]; - if (!currentRecord) { - OWSFailDebug(@"Couldn't find signed prekey for id: %@", keyId); - } - NSArray *allSignedPrekeys = [primaryStorage loadSignedPreKeys]; - NSArray *oldSignedPrekeys - = (currentRecord != nil ? [self removeCurrentRecord:currentRecord fromRecords:allSignedPrekeys] - : allSignedPrekeys); - - NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; - dateFormatter.dateStyle = NSDateFormatterMediumStyle; - dateFormatter.timeStyle = NSDateFormatterMediumStyle; - dateFormatter.locale = [NSLocale systemLocale]; - - // Sort the signed prekeys in ascending order of generation time. - oldSignedPrekeys = [oldSignedPrekeys sortedArrayUsingComparator:^NSComparisonResult( - SignedPreKeyRecord *_Nonnull left, SignedPreKeyRecord *_Nonnull right) { - return [left.generatedAt compare:right.generatedAt]; - }]; - - NSUInteger oldSignedPreKeyCount = oldSignedPrekeys.count; - - int oldAcceptedSignedPreKeyCount = 0; - for (SignedPreKeyRecord *signedPrekey in oldSignedPrekeys) { - if (signedPrekey.wasAcceptedByService) { - oldAcceptedSignedPreKeyCount++; - } - } - - // Iterate the signed prekeys in ascending order so that we try to delete older keys first. - for (SignedPreKeyRecord *signedPrekey in oldSignedPrekeys) { - // Always keep at least 3 keys, accepted or otherwise. - if (oldSignedPreKeyCount <= 3) { - continue; - } - - // Never delete signed prekeys until they are N days old. - if (fabs([signedPrekey.generatedAt timeIntervalSinceNow]) < kSignedPreKeysDeletionTime) { - continue; - } - - // We try to keep a minimum of 3 "old, accepted" signed prekeys. - if (signedPrekey.wasAcceptedByService) { - if (oldAcceptedSignedPreKeyCount <= 3) { - continue; - } else { - oldAcceptedSignedPreKeyCount--; - } - } - - oldSignedPreKeyCount--; - [primaryStorage removeSignedPreKey:signedPrekey.Id]; - } -} - -+ (NSArray *)removeCurrentRecord:(SignedPreKeyRecord *)currentRecord fromRecords:(NSArray *)allRecords { - NSMutableArray *oldRecords = [NSMutableArray array]; - - for (SignedPreKeyRecord *record in allRecords) { - if (currentRecord.Id != record.Id) { - [oldRecords addObject:record]; - } - } - - return oldRecords; -} - -@end - -NS_ASSUME_NONNULL_END diff --git a/SignalUtilitiesKit/ThreadUtil.m b/SignalUtilitiesKit/ThreadUtil.m index 2fcd05655..68a52e67e 100644 --- a/SignalUtilitiesKit/ThreadUtil.m +++ b/SignalUtilitiesKit/ThreadUtil.m @@ -14,7 +14,6 @@ #import #import #import -#import #import #import #import @@ -86,15 +85,12 @@ NS_ASSUME_NONNULL_BEGIN // Find any "dynamic" interactions and safety number changes. // // We use different views for performance reasons. - NSMutableArray *blockingSafetyNumberChanges = [NSMutableArray new]; NSMutableArray *nonBlockingSafetyNumberChanges = [NSMutableArray new]; [[TSDatabaseView threadSpecialMessagesDatabaseView:transaction] enumerateKeysAndObjectsInGroup:thread.uniqueId usingBlock:^( NSString *collection, NSString *key, id object, NSUInteger index, BOOL *stop) { - if ([object isKindOfClass:[TSInvalidIdentityKeyErrorMessage class]]) { - [blockingSafetyNumberChanges addObject:object]; - } else if ([object isKindOfClass:[TSErrorMessage class]]) { + if ([object isKindOfClass:[TSErrorMessage class]]) { TSErrorMessage *errorMessage = (TSErrorMessage *)object; OWSAssertDebug( errorMessage.errorType == TSErrorMessageNonBlockingIdentityChange); @@ -126,7 +122,6 @@ NS_ASSUME_NONNULL_BEGIN thread:thread transaction:transaction maxRangeSize:maxRangeSize - blockingSafetyNumberChanges:blockingSafetyNumberChanges nonBlockingSafetyNumberChanges:nonBlockingSafetyNumberChanges hideUnreadMessagesIndicator:hideUnreadMessagesIndicator firstUnseenSortId:firstUnseenSortId]; @@ -146,7 +141,6 @@ NS_ASSUME_NONNULL_BEGIN thread:(TSThread *)thread transaction:(YapDatabaseReadTransaction *)transaction maxRangeSize:(int)maxRangeSize - blockingSafetyNumberChanges:(NSArray *)blockingSafetyNumberChanges nonBlockingSafetyNumberChanges:(NSArray *)nonBlockingSafetyNumberChanges hideUnreadMessagesIndicator:(BOOL)hideUnreadMessagesIndicator firstUnseenSortId:(nullable NSNumber *)firstUnseenSortId @@ -154,7 +148,6 @@ NS_ASSUME_NONNULL_BEGIN OWSAssertDebug(dynamicInteractions); OWSAssertDebug(thread); OWSAssertDebug(transaction); - OWSAssertDebug(blockingSafetyNumberChanges); OWSAssertDebug(nonBlockingSafetyNumberChanges); if (hideUnreadMessagesIndicator) { @@ -223,45 +216,12 @@ NS_ASSUME_NONNULL_BEGIN } OWSAssertDebug(visibleUnseenMessageCount > 0); - NSUInteger missingUnseenSafetyNumberChangeCount = 0; - if (hasMoreUnseenMessages) { - NSMutableSet *missingUnseenSafetyNumberChanges = [NSMutableSet set]; - for (TSInvalidIdentityKeyErrorMessage *safetyNumberChange in blockingSafetyNumberChanges) { - BOOL isUnseen = safetyNumberChange.sortId >= firstUnseenSortId.unsignedLongLongValue; - if (!isUnseen) { - continue; - } - - BOOL isMissing = safetyNumberChange.sortId < interactionAfterUnreadIndicator.sortId; - if (!isMissing) { - continue; - } - - @try { - NSData *_Nullable newIdentityKey = [safetyNumberChange throws_newIdentityKey]; - if (newIdentityKey == nil) { - OWSFailDebug(@"Safety number change was missing it's new identity key."); - continue; - } - - [missingUnseenSafetyNumberChanges addObject:newIdentityKey]; - } @catch (NSException *exception) { - OWSFailDebug(@"exception: %@", exception); - } - } - - // Count the de-duplicated "blocking" safety number changes and all - // of the "non-blocking" safety number changes. - missingUnseenSafetyNumberChangeCount - = (missingUnseenSafetyNumberChanges.count + nonBlockingSafetyNumberChanges.count); - } - NSInteger unreadIndicatorPosition = visibleUnseenMessageCount; dynamicInteractions.unreadIndicator = [[OWSUnreadIndicator alloc] initWithFirstUnseenSortId:firstUnseenSortId.unsignedLongLongValue hasMoreUnseenMessages:hasMoreUnseenMessages - missingUnseenSafetyNumberChangeCount:missingUnseenSafetyNumberChangeCount + missingUnseenSafetyNumberChangeCount:nonBlockingSafetyNumberChanges.count unreadIndicatorPosition:unreadIndicatorPosition]; OWSLogInfo(@"Creating Unread Indicator: %llu", dynamicInteractions.unreadIndicator.firstUnseenSortId); } diff --git a/SignalUtilitiesKit/To Do/OWSPrimaryStorage+Loki.h b/SignalUtilitiesKit/To Do/OWSPrimaryStorage+Loki.h index 9dd7bef9d..56c6f86cd 100644 --- a/SignalUtilitiesKit/To Do/OWSPrimaryStorage+Loki.h +++ b/SignalUtilitiesKit/To Do/OWSPrimaryStorage+Loki.h @@ -1,8 +1,5 @@ #import -#import -#import -#import #import #import @@ -10,22 +7,6 @@ NS_ASSUME_NONNULL_BEGIN @interface OWSPrimaryStorage (Loki) -# pragma mark - Pre Key Record Management - -- (BOOL)hasPreKeyRecordForContact:(NSString *)hexEncodedPublicKey; -- (PreKeyRecord *_Nullable)getPreKeyRecordForContact:(NSString *)hexEncodedPublicKey transaction:(YapDatabaseReadTransaction *)transaction; -- (PreKeyRecord *)getOrCreatePreKeyRecordForContact:(NSString *)hexEncodedPublicKey; - -# pragma mark - Pre Key Bundle Management - -/** - * Generates a pre key bundle for the given contact. Doesn't store the pre key bundle (pre key bundles are supposed to be sent without ever being stored). - */ -- (PreKeyBundle *)generatePreKeyBundleForContact:(NSString *)hexEncodedPublicKey; -- (PreKeyBundle *_Nullable)getPreKeyBundleForContact:(NSString *)hexEncodedPublicKey; -- (void)setPreKeyBundle:(PreKeyBundle *)bundle forContact:(NSString *)hexEncodedPublicKey transaction:(YapDatabaseReadWriteTransaction *)transaction; -- (void)removePreKeyBundleForContact:(NSString *)hexEncodedPublicKey transaction:(YapDatabaseReadWriteTransaction *)transaction; - # pragma mark - Last Message Hash /** diff --git a/SignalUtilitiesKit/To Do/OWSPrimaryStorage+Loki.m b/SignalUtilitiesKit/To Do/OWSPrimaryStorage+Loki.m index 7d658c73a..6176f7fb5 100644 --- a/SignalUtilitiesKit/To Do/OWSPrimaryStorage+Loki.m +++ b/SignalUtilitiesKit/To Do/OWSPrimaryStorage+Loki.m @@ -1,15 +1,10 @@ #import "OWSPrimaryStorage+Loki.h" -#import "OWSPrimaryStorage+PreKeyStore.h" -#import "OWSPrimaryStorage+SignedPreKeyStore.h" #import "OWSPrimaryStorage+keyFromIntLong.h" - #import "OWSIdentityManager.h" #import "NSDate+OWS.h" #import "TSAccountManager.h" -#import "TSPreKeyManager.h" #import "YapDatabaseConnection+OWS.h" #import "YapDatabaseTransaction+OWS.h" -#import #import "NSObject+Casting.h" #import @@ -25,135 +20,6 @@ return TSAccountManager.sharedInstance; } -# pragma mark - Pre Key Record Management - -#define LKPreKeyContactCollection @"LKPreKeyContactCollection" -#define OWSPrimaryStoragePreKeyStoreCollection @"TSStorageManagerPreKeyStoreCollection" - -- (BOOL)hasPreKeyRecordForContact:(NSString *)hexEncodedPublicKey { - int preKeyId = [self.dbReadWriteConnection intForKey:hexEncodedPublicKey inCollection:LKPreKeyContactCollection]; - return preKeyId > 0; -} - -- (PreKeyRecord *_Nullable)getPreKeyRecordForContact:(NSString *)hexEncodedPublicKey transaction:(YapDatabaseReadTransaction *)transaction { - OWSAssertDebug(hexEncodedPublicKey.length > 0); - int preKeyID = [transaction intForKey:hexEncodedPublicKey inCollection:LKPreKeyContactCollection]; - - if (preKeyID <= 0) { return nil; } - - // throws_loadPreKey doesn't allow us to pass transaction - // FIXME: This seems like it could be a pretty big issue? - return [transaction preKeyRecordForKey:[self keyFromInt:preKeyID] inCollection:OWSPrimaryStoragePreKeyStoreCollection]; -} - -- (PreKeyRecord *)getOrCreatePreKeyRecordForContact:(NSString *)hexEncodedPublicKey { - OWSAssertDebug(hexEncodedPublicKey.length > 0); - int preKeyID = [self.dbReadWriteConnection intForKey:hexEncodedPublicKey inCollection:LKPreKeyContactCollection]; - - // If we don't have an ID then generate and store a new one - if (preKeyID <= 0) { - return [self generateAndStorePreKeyRecordForContact:hexEncodedPublicKey]; - } - - // Load existing pre key record if possible; generate a new one otherwise - @try { - return [self throws_loadPreKey:preKeyID]; - } @catch (NSException *exception) { - return [self generateAndStorePreKeyRecordForContact:hexEncodedPublicKey]; - } -} - -- (PreKeyRecord *)generateAndStorePreKeyRecordForContact:(NSString *)hexEncodedPublicKey { - NSLog([NSString stringWithFormat:@"[Loki] Generating new pre key record for: %@.", hexEncodedPublicKey]); - OWSAssertDebug(hexEncodedPublicKey.length > 0); - - NSArray *records = [self generatePreKeyRecords:1]; - OWSAssertDebug(records.count > 0); - [self storePreKeyRecords:records]; - - PreKeyRecord *record = records.firstObject; - [self.dbReadWriteConnection setInt:record.Id forKey:hexEncodedPublicKey inCollection:LKPreKeyContactCollection]; - - return record; -} - -# pragma mark - Pre Key Bundle Management - -#define LKPreKeyBundleCollection @"LKPreKeyBundleCollection" - -- (PreKeyBundle *)generatePreKeyBundleForContact:(NSString *)hexEncodedPublicKey forceClean:(BOOL)forceClean { - // Refresh signed pre key if needed - [TSPreKeyManager checkPreKeys]; - - ECKeyPair *_Nullable keyPair = self.identityManager.identityKeyPair; - OWSAssertDebug(keyPair); - - // Refresh signed pre key if needed - if (self.currentSignedPreKey == nil || forceClean) { // TODO: Is the self.currentSignedPreKey == nil check needed? - SignedPreKeyRecord *signedPreKeyRecord = [self generateRandomSignedRecord]; - [signedPreKeyRecord markAsAcceptedByService]; - [self storeSignedPreKey:signedPreKeyRecord.Id signedPreKeyRecord:signedPreKeyRecord]; - [self setCurrentSignedPrekeyId:signedPreKeyRecord.Id]; - NSLog(@"[Loki] Signed pre key refreshed successfully."); - } - - SignedPreKeyRecord *_Nullable signedPreKey = self.currentSignedPreKey; - if (signedPreKey == nil) { - OWSFailDebug(@"Signed pre key is nil."); - } - - PreKeyRecord *preKey = [self getOrCreatePreKeyRecordForContact:hexEncodedPublicKey]; - uint32_t registrationID = [self.accountManager getOrGenerateRegistrationId]; - - PreKeyBundle *bundle = [[PreKeyBundle alloc] initWithRegistrationId:registrationID - deviceId:(uint32_t)1 - preKeyId:preKey.Id - preKeyPublic:preKey.keyPair.publicKey.prependKeyType - signedPreKeyPublic:signedPreKey.keyPair.publicKey.prependKeyType - signedPreKeyId:signedPreKey.Id - signedPreKeySignature:signedPreKey.signature - identityKey:keyPair.publicKey.prependKeyType]; - return bundle; -} - -- (PreKeyBundle *)generatePreKeyBundleForContact:(NSString *)hexEncodedPublicKey { - NSInteger failureCount = 0; - BOOL forceClean = NO; - while (failureCount < 3) { - @try { - PreKeyBundle *preKeyBundle = [self generatePreKeyBundleForContact:hexEncodedPublicKey forceClean:forceClean]; - if (![Ed25519 throws_verifySignature:preKeyBundle.signedPreKeySignature - publicKey:preKeyBundle.identityKey.throws_removeKeyType - data:preKeyBundle.signedPreKeyPublic]) { - @throw [NSException exceptionWithName:InvalidKeyException reason:@"KeyIsNotValidlySigned" userInfo:nil]; - } - NSLog([NSString stringWithFormat:@"[Loki] Generated a new pre key bundle for: %@.", hexEncodedPublicKey]); - return preKeyBundle; - } @catch (NSException *exception) { - failureCount += 1; - forceClean = YES; - } - } - NSLog([NSString stringWithFormat:@"[Loki] Failed to generate a valid pre key bundle for: %@.", hexEncodedPublicKey]); - return nil; -} - -- (PreKeyBundle *_Nullable)getPreKeyBundleForContact:(NSString *)hexEncodedPublicKey { - return [self.dbReadConnection preKeyBundleForKey:hexEncodedPublicKey inCollection:LKPreKeyBundleCollection]; -} - -- (void)setPreKeyBundle:(PreKeyBundle *)bundle forContact:(NSString *)hexEncodedPublicKey transaction:(YapDatabaseReadWriteTransaction *)transaction { - [transaction setObject:bundle forKey:hexEncodedPublicKey inCollection:LKPreKeyBundleCollection]; - NSLog([NSString stringWithFormat:@"[Loki] Stored pre key bundle from: %@.", hexEncodedPublicKey]); - // FIXME: I don't think the line below is good for anything - [transaction.connection flushTransactionsWithCompletionQueue:dispatch_get_main_queue() completionBlock:^{ }]; -} - -- (void)removePreKeyBundleForContact:(NSString *)hexEncodedPublicKey transaction:(YapDatabaseReadWriteTransaction *)transaction { - [transaction removeObjectForKey:hexEncodedPublicKey inCollection:LKPreKeyBundleCollection]; - NSLog([NSString stringWithFormat:@"[Loki] Removed pre key bundle from: %@.", hexEncodedPublicKey]); -} - # pragma mark - Open Groups #define LKMessageIDCollection @"LKMessageIDCollection" diff --git a/SignalUtilitiesKit/To Do/OWSProfileManager.m b/SignalUtilitiesKit/To Do/OWSProfileManager.m index b536d429c..d589f356e 100644 --- a/SignalUtilitiesKit/To Do/OWSProfileManager.m +++ b/SignalUtilitiesKit/To Do/OWSProfileManager.m @@ -131,13 +131,6 @@ typedef void (^ProfileManagerFailureBlock)(NSError *error); return SSKEnvironment.shared.blockingManager; } -- (id)udManager -{ - OWSAssertDebug(SSKEnvironment.shared.udManager); - - return SSKEnvironment.shared.udManager; -} - #pragma mark - User Profile Accessor - (void)ensureLocalProfileCached @@ -902,8 +895,6 @@ typedef void (^ProfileManagerFailureBlock)(NSError *error); dbConnection:self.dbConnection completion:^{ dispatch_async(dispatch_get_main_queue(), ^{ - [self.udManager setUnidentifiedAccessMode:UnidentifiedAccessModeUnknown - recipientId:recipientId]; [userProfile updateWithAvatarUrlPath:avatarURL avatarFileName:nil dbConnection:self.dbConnection completion:^{ [self downloadAvatarForUserProfile:userProfile]; }];