Add protocol context to protocol kit.

pull/1/head
Matthew Chen 7 years ago
parent 074046b98e
commit d3e16583eb

@ -1,5 +1,5 @@
// //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved. // Copyright (c) 2018 Open Whisper Systems. All rights reserved.
// //
import Foundation import Foundation
@ -26,19 +26,19 @@ class SessionResetJob: NSObject {
func run() { func run() {
Logger.info("\(TAG) Local user reset session.") Logger.info("\(TAG) Local user reset session.")
OWSDispatch.sessionStoreQueue().async { TSStorageManager.protocolStoreDBConnection().asyncReadWrite { (transaction) in
Logger.info("\(self.TAG) deleting sessions for recipient: \(self.recipientId)") Logger.info("\(self.TAG) deleting sessions for recipient: \(self.recipientId)")
self.storageManager.deleteAllSessions(forContact: self.recipientId) self.storageManager.deleteAllSessions(forContact: self.recipientId, protocolContext: transaction)
DispatchQueue.main.async { DispatchQueue.main.async {
let endSessionMessage = EndSessionMessage(timestamp: NSDate.ows_millisecondTimeStamp(), in: self.thread) let endSessionMessage = EndSessionMessage(timestamp: NSDate.ows_millisecondTimeStamp(), in: self.thread)
self.messageSender.enqueue(endSessionMessage, success: { self.messageSender.enqueue(endSessionMessage, success: {
OWSDispatch.sessionStoreQueue().async { TSStorageManager.protocolStoreDBConnection().asyncReadWrite { (transaction) in
// Archive the just-created session since the recipient should delete their corresponding // Archive the just-created session since the recipient should delete their corresponding
// session upon receiving and decrypting our EndSession message. // session upon receiving and decrypting our EndSession message.
// Otherwise if we send another message before them, they wont have the session to decrypt it. // Otherwise if we send another message before them, they wont have the session to decrypt it.
self.storageManager.archiveAllSessions(forContact: self.recipientId) self.storageManager.archiveAllSessions(forContact: self.recipientId, protocolContext: transaction)
} }
Logger.info("\(self.TAG) successfully sent EndSessionMessage.") Logger.info("\(self.TAG) successfully sent EndSessionMessage.")
let message = TSInfoMessage(timestamp: NSDate.ows_millisecondTimeStamp(), let message = TSInfoMessage(timestamp: NSDate.ows_millisecondTimeStamp(),
@ -46,7 +46,7 @@ class SessionResetJob: NSObject {
messageType: TSInfoMessageType.typeSessionDidEnd) messageType: TSInfoMessageType.typeSessionDidEnd)
message.save() message.save()
}, failure: {error in }, failure: {error in
OWSDispatch.sessionStoreQueue().async { TSStorageManager.protocolStoreDBConnection().asyncReadWrite { (transaction) in
// Even though this is the error handler - which means probably the recipient didn't receive the message // Even though this is the error 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. // 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, // Since the cost of sending a future message using a session the recipient doesn't have is so high,
@ -55,7 +55,7 @@ class SessionResetJob: NSObject {
// Archive the just-created session since the recipient should delete their corresponding // Archive the just-created session since the recipient should delete their corresponding
// session upon receiving and decrypting our EndSession message. // session upon receiving and decrypting our EndSession message.
// Otherwise if we send another message before them, they wont have the session to decrypt it. // Otherwise if we send another message before them, they wont have the session to decrypt it.
self.storageManager.archiveAllSessions(forContact: self.recipientId) self.storageManager.archiveAllSessions(forContact: self.recipientId, protocolContext: transaction)
} }
Logger.error("\(self.TAG) failed to send EndSessionMessage with error: \(error.localizedDescription)") Logger.error("\(self.TAG) failed to send EndSessionMessage with error: \(error.localizedDescription)")
}) })

@ -80,6 +80,7 @@
#import <SignalServiceKit/OWSIdentityManager.h> #import <SignalServiceKit/OWSIdentityManager.h>
#import <SignalServiceKit/OWSMessageManager.h> #import <SignalServiceKit/OWSMessageManager.h>
#import <SignalServiceKit/OWSMessageSender.h> #import <SignalServiceKit/OWSMessageSender.h>
#import <SignalServiceKit/OWSMessageUtils.h>
#import <SignalServiceKit/OWSReadReceiptManager.h> #import <SignalServiceKit/OWSReadReceiptManager.h>
#import <SignalServiceKit/OWSVerificationStateChangeMessage.h> #import <SignalServiceKit/OWSVerificationStateChangeMessage.h>
#import <SignalServiceKit/SignalRecipient.h> #import <SignalServiceKit/SignalRecipient.h>
@ -202,7 +203,6 @@ typedef NS_ENUM(NSInteger, MessagesRangeSizeMode) {
@property (nonatomic, readonly) ContactsUpdater *contactsUpdater; @property (nonatomic, readonly) ContactsUpdater *contactsUpdater;
@property (nonatomic, readonly) OWSMessageSender *messageSender; @property (nonatomic, readonly) OWSMessageSender *messageSender;
@property (nonatomic, readonly) TSStorageManager *storageManager; @property (nonatomic, readonly) TSStorageManager *storageManager;
@property (nonatomic, readonly) OWSMessageManager *messagesManager;
@property (nonatomic, readonly) TSNetworkManager *networkManager; @property (nonatomic, readonly) TSNetworkManager *networkManager;
@property (nonatomic, readonly) OutboundCallInitiator *outboundCallInitiator; @property (nonatomic, readonly) OutboundCallInitiator *outboundCallInitiator;
@property (nonatomic, readonly) OWSBlockingManager *blockingManager; @property (nonatomic, readonly) OWSBlockingManager *blockingManager;
@ -274,7 +274,6 @@ typedef NS_ENUM(NSInteger, MessagesRangeSizeMode) {
_messageSender = [Environment current].messageSender; _messageSender = [Environment current].messageSender;
_outboundCallInitiator = SignalApp.sharedApp.outboundCallInitiator; _outboundCallInitiator = SignalApp.sharedApp.outboundCallInitiator;
_storageManager = [TSStorageManager sharedManager]; _storageManager = [TSStorageManager sharedManager];
_messagesManager = [OWSMessageManager sharedManager];
_networkManager = [TSNetworkManager sharedManager]; _networkManager = [TSNetworkManager sharedManager];
_blockingManager = [OWSBlockingManager sharedManager]; _blockingManager = [OWSBlockingManager sharedManager];
_contactsViewHelper = [[ContactsViewHelper alloc] initWithDelegate:self]; _contactsViewHelper = [[ContactsViewHelper alloc] initWithDelegate:self];
@ -700,7 +699,7 @@ typedef NS_ENUM(NSInteger, MessagesRangeSizeMode) {
{ {
NSMutableArray<NSString *> *result = [NSMutableArray new]; NSMutableArray<NSString *> *result = [NSMutableArray new];
for (NSString *recipientId in self.thread.recipientIdentifiers) { for (NSString *recipientId in self.thread.recipientIdentifiers) {
if ([[OWSIdentityManager sharedManager] verificationStateForRecipientId:recipientId] if ([[OWSIdentityManager sharedManager] verificationStateForRecipientIdWithoutTransaction:recipientId]
== OWSVerificationStateNoLongerVerified) { == OWSVerificationStateNoLongerVerified) {
[result addObject:recipientId]; [result addObject:recipientId];
} }
@ -927,10 +926,14 @@ typedef NS_ENUM(NSInteger, MessagesRangeSizeMode) {
continue; continue;
} }
[OWSIdentityManager.sharedManager setVerificationState:OWSVerificationStateDefault [TSStorageManager.protocolStoreDBConnection
identityKey:identityKey asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
recipientId:recipientId [OWSIdentityManager.sharedManager setVerificationState:OWSVerificationStateDefault
isUserInitiatedChange:YES]; identityKey:identityKey
recipientId:recipientId
isUserInitiatedChange:YES
protocolContext:transaction];
}];
} }
} }
@ -1300,7 +1303,7 @@ typedef NS_ENUM(NSInteger, MessagesRangeSizeMode) {
BOOL isVerified = YES; BOOL isVerified = YES;
for (NSString *recipientId in self.thread.recipientIdentifiers) { for (NSString *recipientId in self.thread.recipientIdentifiers) {
if ([[OWSIdentityManager sharedManager] verificationStateForRecipientId:recipientId] if ([[OWSIdentityManager sharedManager] verificationStateForRecipientIdWithoutTransaction:recipientId]
!= OWSVerificationStateVerified) { != OWSVerificationStateVerified) {
isVerified = NO; isVerified = NO;
break; break;
@ -3586,7 +3589,7 @@ typedef NS_ENUM(NSInteger, MessagesRangeSizeMode) {
- (void)updateBackButtonUnreadCount - (void)updateBackButtonUnreadCount
{ {
OWSAssertIsOnMainThread(); OWSAssertIsOnMainThread();
self.backButtonUnreadCount = [self.messagesManager unreadMessagesCountExcept:self.thread]; self.backButtonUnreadCount = [OWSMessageUtils.sharedManager unreadMessagesCountExcept:self.thread];
} }
- (void)setBackButtonUnreadCount:(NSUInteger)unreadCount - (void)setBackButtonUnreadCount:(NSUInteger)unreadCount

@ -1258,7 +1258,11 @@ NS_ASSUME_NONNULL_BEGIN
NSData *envelopeData = [envelopeBuilder build].data; NSData *envelopeData = [envelopeBuilder build].data;
OWSAssert(envelopeData); OWSAssert(envelopeData);
[[OWSBatchMessageProcessor sharedInstance] enqueueEnvelopeData:envelopeData plaintextData:plaintextData]; [TSStorageManager.protocolStoreDBConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
[[OWSBatchMessageProcessor sharedInstance] enqueueEnvelopeData:envelopeData
plaintextData:plaintextData
transaction:transaction];
}];
} }
+ (void)performRandomActions:(int)counter thread:(TSThread *)thread + (void)performRandomActions:(int)counter thread:(TSThread *)thread

@ -30,9 +30,7 @@ NS_ASSUME_NONNULL_BEGIN
}], }],
[OWSTableItem itemWithTitle:@"Log All Sessions" [OWSTableItem itemWithTitle:@"Log All Sessions"
actionBlock:^{ actionBlock:^{
dispatch_async([OWSDispatch sessionStoreQueue], ^{ [[TSStorageManager sharedManager] printAllSessions];
[[TSStorageManager sharedManager] printAllSessions];
});
}], }],
[OWSTableItem itemWithTitle:@"Toggle Key Change" [OWSTableItem itemWithTitle:@"Toggle Key Change"
actionBlock:^{ actionBlock:^{
@ -41,33 +39,39 @@ NS_ASSUME_NONNULL_BEGIN
OWSIdentityManager *identityManager = [OWSIdentityManager sharedManager]; OWSIdentityManager *identityManager = [OWSIdentityManager sharedManager];
NSString *recipientId = [thread contactIdentifier]; NSString *recipientId = [thread contactIdentifier];
NSData *currentKey = [identityManager identityKeyForRecipientIdWOT:recipientId]; [TSStorageManager.protocolStoreDBConnection
NSMutableData *flippedKey = [NSMutableData new]; readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
const char *currentKeyBytes = currentKey.bytes; NSData *currentKey = [identityManager identityKeyForRecipientId:recipientId
for (NSUInteger i = 0; i < currentKey.length; i++) { protocolContext:transaction];
const char xorByte = currentKeyBytes[i] ^ 0xff; NSMutableData *flippedKey = [NSMutableData new];
[flippedKey appendBytes:&xorByte length:1]; const char *currentKeyBytes = currentKey.bytes;
} for (NSUInteger i = 0; i < currentKey.length; i++) {
OWSAssert(flippedKey.length == currentKey.length); const char xorByte = currentKeyBytes[i] ^ 0xff;
[identityManager saveRemoteIdentity:flippedKey [flippedKey appendBytes:&xorByte length:1];
recipientId:recipientId }
protocolContext:protocolContext]; OWSAssert(flippedKey.length == currentKey.length);
[identityManager saveRemoteIdentity:flippedKey
recipientId:recipientId
protocolContext:transaction];
}];
}], }],
[OWSTableItem itemWithTitle:@"Delete all sessions" [OWSTableItem itemWithTitle:@"Delete all sessions"
actionBlock:^{ actionBlock:^{
dispatch_async([OWSDispatch sessionStoreQueue], ^{ [TSStorageManager.protocolStoreDBConnection
[[TSStorageManager sharedManager] readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
deleteAllSessionsForContact:thread.contactIdentifier [[TSStorageManager sharedManager]
protocolContext:protocolContext]; deleteAllSessionsForContact:thread.contactIdentifier
}); protocolContext:transaction];
}];
}], }],
[OWSTableItem itemWithTitle:@"Archive all sessions" [OWSTableItem itemWithTitle:@"Archive all sessions"
actionBlock:^{ actionBlock:^{
dispatch_async([OWSDispatch sessionStoreQueue], ^{ [TSStorageManager.protocolStoreDBConnection
[[TSStorageManager sharedManager] readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
archiveAllSessionsForContact:thread.contactIdentifier [[TSStorageManager sharedManager]
protocolContext:protocolContext]; archiveAllSessionsForContact:thread.contactIdentifier
}); protocolContext:transaction];
}];
}], }],
[OWSTableItem itemWithTitle:@"Send session reset" [OWSTableItem itemWithTitle:@"Send session reset"
actionBlock:^{ actionBlock:^{
@ -101,32 +105,20 @@ NS_ASSUME_NONNULL_BEGIN
#if DEBUG #if DEBUG
+ (void)clearSessionAndIdentityStore + (void)clearSessionAndIdentityStore
{ {
dispatch_async([OWSDispatch sessionStoreQueue], ^{ [[TSStorageManager sharedManager] resetSessionStore];
[[TSStorageManager sharedManager] resetSessionStore]; [[OWSIdentityManager sharedManager] clearIdentityState];
dispatch_async(dispatch_get_main_queue(), ^{
[[OWSIdentityManager sharedManager] clearIdentityState];
});
});
} }
+ (void)snapshotSessionAndIdentityStore + (void)snapshotSessionAndIdentityStore
{ {
dispatch_async([OWSDispatch sessionStoreQueue], ^{ [[TSStorageManager sharedManager] snapshotSessionStore];
[[TSStorageManager sharedManager] snapshotSessionStore]; [[OWSIdentityManager sharedManager] snapshotIdentityState];
dispatch_async(dispatch_get_main_queue(), ^{
[[OWSIdentityManager sharedManager] snapshotIdentityState];
});
});
} }
+ (void)restoreSessionAndIdentityStore + (void)restoreSessionAndIdentityStore
{ {
dispatch_async([OWSDispatch sessionStoreQueue], ^{ [[TSStorageManager sharedManager] restoreSessionStore];
[[TSStorageManager sharedManager] restoreSessionStore]; [[OWSIdentityManager sharedManager] restoreIdentityState];
dispatch_async(dispatch_get_main_queue(), ^{
[[OWSIdentityManager sharedManager] restoreIdentityState];
});
});
} }
#endif #endif

@ -1,5 +1,5 @@
// //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved. // Copyright (c) 2018 Open Whisper Systems. All rights reserved.
// //
#import "FingerprintViewController.h" #import "FingerprintViewController.h"
@ -338,7 +338,8 @@ typedef void (^CustomLayoutBlock)(void);
{ {
OWSAssert(self.recipientId.length > 0); OWSAssert(self.recipientId.length > 0);
BOOL isVerified = [[OWSIdentityManager sharedManager] verificationStateForRecipientId:self.recipientId] BOOL isVerified =
[[OWSIdentityManager sharedManager] verificationStateForRecipientIdWithoutTransaction:self.recipientId]
== OWSVerificationStateVerified; == OWSVerificationStateVerified;
if (isVerified) { if (isVerified) {
@ -512,15 +513,19 @@ typedef void (^CustomLayoutBlock)(void);
- (void)verifyUnverifyButtonTapped:(UIGestureRecognizer *)gestureRecognizer - (void)verifyUnverifyButtonTapped:(UIGestureRecognizer *)gestureRecognizer
{ {
if (gestureRecognizer.state == UIGestureRecognizerStateRecognized) { if (gestureRecognizer.state == UIGestureRecognizerStateRecognized) {
BOOL isVerified = [[OWSIdentityManager sharedManager] verificationStateForRecipientId:self.recipientId] [TSStorageManager.protocolStoreDBConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
== OWSVerificationStateVerified; BOOL isVerified = [[OWSIdentityManager sharedManager] verificationStateForRecipientId:self.recipientId
transaction:transaction]
OWSVerificationState newVerificationState == OWSVerificationStateVerified;
= (isVerified ? OWSVerificationStateDefault : OWSVerificationStateVerified);
[[OWSIdentityManager sharedManager] setVerificationState:newVerificationState OWSVerificationState newVerificationState
identityKey:self.identityKey = (isVerified ? OWSVerificationStateDefault : OWSVerificationStateVerified);
recipientId:self.recipientId [[OWSIdentityManager sharedManager] setVerificationState:newVerificationState
isUserInitiatedChange:YES]; identityKey:self.identityKey
recipientId:self.recipientId
isUserInitiatedChange:YES
protocolContext:transaction];
}];
[self dismissViewControllerAnimated:YES completion:nil]; [self dismissViewControllerAnimated:YES completion:nil];
} }

@ -1,5 +1,5 @@
// //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved. // Copyright (c) 2018 Open Whisper Systems. All rights reserved.
// //
#import "FingerprintViewScanController.h" #import "FingerprintViewScanController.h"
@ -200,10 +200,15 @@ NS_ASSUME_NONNULL_BEGIN
@"Button that marks user as verified after a successful fingerprint scan.") @"Button that marks user as verified after a successful fingerprint scan.")
style:UIAlertActionStyleDefault style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) { handler:^(UIAlertAction *action) {
[OWSIdentityManager.sharedManager setVerificationState:OWSVerificationStateVerified [TSStorageManager.protocolStoreDBConnection
identityKey:identityKey asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
recipientId:recipientId [OWSIdentityManager.sharedManager
isUserInitiatedChange:YES]; setVerificationState:OWSVerificationStateVerified
identityKey:identityKey
recipientId:recipientId
isUserInitiatedChange:YES
protocolContext:transaction];
}];
[viewController dismissViewControllerAnimated:true completion:nil]; [viewController dismissViewControllerAnimated:true completion:nil];
}]]; }]];
UIAlertAction *dismissAction = UIAlertAction *dismissAction =

@ -25,6 +25,7 @@
#import <SignalServiceKit/NSDate+OWS.h> #import <SignalServiceKit/NSDate+OWS.h>
#import <SignalServiceKit/OWSBlockingManager.h> #import <SignalServiceKit/OWSBlockingManager.h>
#import <SignalServiceKit/OWSMessageSender.h> #import <SignalServiceKit/OWSMessageSender.h>
#import <SignalServiceKit/OWSMessageUtils.h>
#import <SignalServiceKit/TSOutgoingMessage.h> #import <SignalServiceKit/TSOutgoingMessage.h>
#import <SignalServiceKit/Threading.h> #import <SignalServiceKit/Threading.h>
#import <YapDatabase/YapDatabase.h> #import <YapDatabase/YapDatabase.h>
@ -57,7 +58,6 @@ typedef NS_ENUM(NSInteger, CellState) { kArchiveState, kInboxState };
@property (nonatomic, readonly) AccountManager *accountManager; @property (nonatomic, readonly) AccountManager *accountManager;
@property (nonatomic, readonly) OWSContactsManager *contactsManager; @property (nonatomic, readonly) OWSContactsManager *contactsManager;
@property (nonatomic, readonly) OWSMessageManager *messagesManager;
@property (nonatomic, readonly) OWSMessageSender *messageSender; @property (nonatomic, readonly) OWSMessageSender *messageSender;
@property (nonatomic, readonly) OWSBlockingManager *blockingManager; @property (nonatomic, readonly) OWSBlockingManager *blockingManager;
@ -106,7 +106,6 @@ typedef NS_ENUM(NSInteger, CellState) { kArchiveState, kInboxState };
{ {
_accountManager = SignalApp.sharedApp.accountManager; _accountManager = SignalApp.sharedApp.accountManager;
_contactsManager = [Environment current].contactsManager; _contactsManager = [Environment current].contactsManager;
_messagesManager = [OWSMessageManager sharedManager];
_messageSender = [Environment current].messageSender; _messageSender = [Environment current].messageSender;
_blockingManager = [OWSBlockingManager sharedManager]; _blockingManager = [OWSBlockingManager sharedManager];
_blockedPhoneNumberSet = [NSSet setWithArray:[_blockingManager blockedPhoneNumbers]]; _blockedPhoneNumberSet = [NSSet setWithArray:[_blockingManager blockedPhoneNumbers]];
@ -752,7 +751,7 @@ typedef NS_ENUM(NSInteger, CellState) { kArchiveState, kInboxState };
- (void)updateInboxCountLabel - (void)updateInboxCountLabel
{ {
NSUInteger numberOfItems = [self.messagesManager unreadMessagesCount]; NSUInteger numberOfItems = [OWSMessageUtils.sharedManager unreadMessagesCount];
NSString *unreadString = NSLocalizedString(@"WHISPER_NAV_BAR_TITLE", nil); NSString *unreadString = NSLocalizedString(@"WHISPER_NAV_BAR_TITLE", nil);
if (numberOfItems > 0) { if (numberOfItems > 0) {

@ -205,7 +205,7 @@ const NSUInteger kAvatarViewDiameter = 52;
} }
NSAttributedString *attributedDate = [self dateAttributedString:thread.lastMessageDate]; NSAttributedString *attributedDate = [self dateAttributedString:thread.lastMessageDate];
NSUInteger unreadCount = [[OWSMessageManager sharedManager] unreadMessagesInThread:thread]; NSUInteger unreadCount = [[OWSMessageUtils sharedManager] unreadMessagesInThread:thread];
[[NSNotificationCenter defaultCenter] addObserver:self [[NSNotificationCenter defaultCenter] addObserver:self

@ -682,7 +682,8 @@ NS_ASSUME_NONNULL_BEGIN
} }
} }
BOOL isVerified = [[OWSIdentityManager sharedManager] verificationStateForRecipientId:recipientId] BOOL isVerified =
[[OWSIdentityManager sharedManager] verificationStateForRecipientIdWithoutTransaction:recipientId]
== OWSVerificationStateVerified; == OWSVerificationStateVerified;
if (isVerified) { if (isVerified) {
NSMutableAttributedString *subtitle = [NSMutableAttributedString new]; NSMutableAttributedString *subtitle = [NSMutableAttributedString new];

@ -149,7 +149,7 @@ NS_ASSUME_NONNULL_BEGIN
// Optimistically set this flag. // Optimistically set this flag.
[OWSDeviceManager.sharedManager setMayHaveLinkedDevices]; [OWSDeviceManager.sharedManager setMayHaveLinkedDevices];
ECKeyPair *_Nullable identityKeyPair = [[OWSIdentityManager sharedManager] identityKeyPair]; ECKeyPair *_Nullable identityKeyPair = [[OWSIdentityManager sharedManager] identityKeyPairWithoutProtocolContext];
OWSAssert(identityKeyPair); OWSAssert(identityKeyPair);
NSData *myPublicKey = identityKeyPair.publicKey; NSData *myPublicKey = identityKeyPair.publicKey;
NSData *myPrivateKey = identityKeyPair.ows_privateKey; NSData *myPrivateKey = identityKeyPair.ows_privateKey;

@ -1,5 +1,5 @@
// //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved. // Copyright (c) 2018 Open Whisper Systems. All rights reserved.
// //
import Foundation import Foundation
@ -55,8 +55,8 @@ class SafetyNumberConfirmationAlert: NSObject {
let confirmAction = UIAlertAction(title: confirmationText, style: .default) { _ in let confirmAction = UIAlertAction(title: confirmationText, style: .default) { _ in
Logger.info("\(self.TAG) Confirmed identity: \(untrustedIdentity)") Logger.info("\(self.TAG) Confirmed identity: \(untrustedIdentity)")
OWSDispatch.sessionStoreQueue().async { TSStorageManager.protocolStoreDBConnection().asyncReadWrite { (transaction) in
OWSIdentityManager.shared().setVerificationState(.default, identityKey: untrustedIdentity.identityKey, recipientId: untrustedIdentity.recipientId, isUserInitiatedChange: true) OWSIdentityManager.shared().setVerificationState(.default, identityKey: untrustedIdentity.identityKey, recipientId: untrustedIdentity.recipientId, isUserInitiatedChange: true, protocolContext: transaction)
DispatchQueue.main.async { DispatchQueue.main.async {
completion(true) completion(true)
} }

@ -177,7 +177,7 @@ NS_ASSUME_NONNULL_BEGIN
ContactTableViewCell *cell = [ContactTableViewCell new]; ContactTableViewCell *cell = [ContactTableViewCell new];
SignalAccount *signalAccount = [helper signalAccountForRecipientId:recipientId]; SignalAccount *signalAccount = [helper signalAccountForRecipientId:recipientId];
OWSVerificationState verificationState = OWSVerificationState verificationState =
[[OWSIdentityManager sharedManager] verificationStateForRecipientId:recipientId]; [[OWSIdentityManager sharedManager] verificationStateForRecipientIdWithoutTransaction:recipientId];
BOOL isVerified = verificationState == OWSVerificationStateVerified; BOOL isVerified = verificationState == OWSVerificationStateVerified;
BOOL isNoLongerVerified = verificationState == OWSVerificationStateNoLongerVerified; BOOL isNoLongerVerified = verificationState == OWSVerificationStateNoLongerVerified;
BOOL isBlocked = [helper isRecipientIdBlocked:recipientId]; BOOL isBlocked = [helper isRecipientIdBlocked:recipientId];
@ -244,17 +244,22 @@ NS_ASSUME_NONNULL_BEGIN
OWSIdentityManager *identityManger = [OWSIdentityManager sharedManager]; OWSIdentityManager *identityManger = [OWSIdentityManager sharedManager];
NSArray<NSString *> *recipientIds = [self noLongerVerifiedRecipientIds]; NSArray<NSString *> *recipientIds = [self noLongerVerifiedRecipientIds];
for (NSString *recipientId in recipientIds) { for (NSString *recipientId in recipientIds) {
OWSVerificationState verificationState = [identityManger verificationStateForRecipientId:recipientId]; OWSVerificationState verificationState =
[identityManger verificationStateForRecipientIdWithoutTransaction:recipientId];
if (verificationState == OWSVerificationStateNoLongerVerified) { if (verificationState == OWSVerificationStateNoLongerVerified) {
NSData *identityKey = [identityManger identityKeyForRecipientIdWOT:recipientId]; NSData *identityKey = [identityManger identityKeyForRecipientIdWOT:recipientId];
if (identityKey.length < 1) { if (identityKey.length < 1) {
OWSFail(@"Missing identity key for: %@", recipientId); OWSFail(@"Missing identity key for: %@", recipientId);
continue; continue;
} }
[identityManger setVerificationState:OWSVerificationStateDefault [TSStorageManager.protocolStoreDBConnection
identityKey:identityKey asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
recipientId:recipientId [identityManger setVerificationState:OWSVerificationStateDefault
isUserInitiatedChange:YES]; identityKey:identityKey
recipientId:recipientId
isUserInitiatedChange:YES
protocolContext:transaction];
}];
} }
} }
@ -266,7 +271,7 @@ NS_ASSUME_NONNULL_BEGIN
{ {
NSMutableArray<NSString *> *result = [NSMutableArray new]; NSMutableArray<NSString *> *result = [NSMutableArray new];
for (NSString *recipientId in self.thread.recipientIdentifiers) { for (NSString *recipientId in self.thread.recipientIdentifiers) {
if ([[OWSIdentityManager sharedManager] verificationStateForRecipientId:recipientId] if ([[OWSIdentityManager sharedManager] verificationStateForRecipientIdWithoutTransaction:recipientId]
== OWSVerificationStateNoLongerVerified) { == OWSVerificationStateNoLongerVerified) {
[result addObject:recipientId]; [result addObject:recipientId];
} }

@ -1,5 +1,5 @@
// //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved. // Copyright (c) 2018 Open Whisper Systems. All rights reserved.
// //
#import "NotificationsManager.h" #import "NotificationsManager.h"
@ -291,7 +291,8 @@ NSString *const kNotificationsManagerNewMesssageSoundName = @"NewMessage.aifc";
// "no longer verified". // "no longer verified".
BOOL isNoLongerVerified = NO; BOOL isNoLongerVerified = NO;
for (NSString *recipientId in thread.recipientIdentifiers) { for (NSString *recipientId in thread.recipientIdentifiers) {
if ([OWSIdentityManager.sharedManager verificationStateForRecipientId:recipientId] if ([OWSIdentityManager.sharedManager
verificationStateForRecipientIdWithoutTransaction:recipientId]
== OWSVerificationStateNoLongerVerified) { == OWSVerificationStateNoLongerVerified) {
isNoLongerVerified = YES; isNoLongerVerified = YES;
break; break;

@ -385,9 +385,10 @@ typedef void (^SendMessageBlock)(SendCompletionBlock completion);
DDLogDebug(@"%@ Confirming identity for recipient: %@", self.logTag, recipientId); DDLogDebug(@"%@ Confirming identity for recipient: %@", self.logTag, recipientId);
dispatch_async([OWSDispatch sessionStoreQueue], ^(void) { [TSStorageManager.protocolStoreDBConnection asyncReadWriteWithBlock:^(
YapDatabaseReadWriteTransaction *transaction) {
OWSVerificationState verificationState = OWSVerificationState verificationState =
[[OWSIdentityManager sharedManager] verificationStateForRecipientId:recipientId]; [[OWSIdentityManager sharedManager] verificationStateForRecipientId:recipientId transaction:transaction];
switch (verificationState) { switch (verificationState) {
case OWSVerificationStateVerified: { case OWSVerificationStateVerified: {
OWSFail(@"%@ Shouldn't need to confirm identity if it was already verified", self.logTag); OWSFail(@"%@ Shouldn't need to confirm identity if it was already verified", self.logTag);
@ -404,12 +405,14 @@ typedef void (^SendMessageBlock)(SendCompletionBlock completion);
} }
case OWSVerificationStateNoLongerVerified: { case OWSVerificationStateNoLongerVerified: {
DDLogInfo(@"%@ marked recipient: %@ as default verification status.", self.logTag, recipientId); DDLogInfo(@"%@ marked recipient: %@ as default verification status.", self.logTag, recipientId);
NSData *identityKey = [[OWSIdentityManager sharedManager] identityKeyForRecipientIdWOT:recipientId]; NSData *identityKey = [[OWSIdentityManager sharedManager] identityKeyForRecipientId:recipientId
protocolContext:transaction];
OWSAssert(identityKey); OWSAssert(identityKey);
[[OWSIdentityManager sharedManager] setVerificationState:OWSVerificationStateDefault [[OWSIdentityManager sharedManager] setVerificationState:OWSVerificationStateDefault
identityKey:identityKey identityKey:identityKey
recipientId:recipientId recipientId:recipientId
isUserInitiatedChange:YES]; isUserInitiatedChange:YES
protocolContext:transaction];
break; break;
} }
} }
@ -417,7 +420,7 @@ typedef void (^SendMessageBlock)(SendCompletionBlock completion);
dispatch_async(dispatch_get_main_queue(), ^(void) { dispatch_async(dispatch_get_main_queue(), ^(void) {
[self resendMessage:message fromViewController:fromViewController]; [self resendMessage:message fromViewController:fromViewController];
}); });
}); }];
} }
- (void)resendMessage:(TSOutgoingMessage *)message fromViewController:(UIViewController *)fromViewController - (void)resendMessage:(TSOutgoingMessage *)message fromViewController:(UIViewController *)fromViewController

@ -1,5 +1,5 @@
// //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved. // Copyright (c) 2018 Open Whisper Systems. All rights reserved.
// //
import Foundation import Foundation
@ -130,10 +130,10 @@ public class ProfileFetcherJob: NSObject {
} }
private func verifyIdentityUpToDateAsync(recipientId: String, latestIdentityKey: Data) { private func verifyIdentityUpToDateAsync(recipientId: String, latestIdentityKey: Data) {
OWSDispatch.sessionStoreQueue().async { TSStorageManager.protocolStoreDBConnection().asyncReadWrite { (transaction) in
if OWSIdentityManager.shared().saveRemoteIdentity(latestIdentityKey, recipientId: recipientId) { if OWSIdentityManager.shared().saveRemoteIdentity(latestIdentityKey, recipientId: recipientId, protocolContext: transaction) {
Logger.info("\(self.TAG) updated identity key with fetched profile for recipient: \(recipientId)") Logger.info("\(self.TAG) updated identity key with fetched profile for recipient: \(recipientId)")
self.storageManager.archiveAllSessions(forContact: recipientId) self.storageManager.archiveAllSessions(forContact: recipientId, protocolContext: transaction)
} else { } else {
// no change in identity. // no change in identity.
} }

@ -41,7 +41,9 @@ extern const NSUInteger kIdentityKeyLength;
isUserInitiatedChange:(BOOL)isUserInitiatedChange isUserInitiatedChange:(BOOL)isUserInitiatedChange
protocolContext:(nullable id)protocolContext; protocolContext:(nullable id)protocolContext;
- (OWSVerificationState)verificationStateForRecipientId:(NSString *)recipientId; - (OWSVerificationState)verificationStateForRecipientIdWithoutTransaction:(NSString *)recipientId;
- (OWSVerificationState)verificationStateForRecipientId:(NSString *)recipientId
transaction:(YapDatabaseReadWriteTransaction *)transaction;
- (nullable OWSRecipientIdentity *)recipientIdentityForRecipientId:(NSString *)recipientId; - (nullable OWSRecipientIdentity *)recipientIdentityForRecipientId:(NSString *)recipientId;
@ -50,8 +52,7 @@ extern const NSUInteger kIdentityKeyLength;
* @returns nil if the recipient does not exist, or is trusted for sending * @returns nil if the recipient does not exist, or is trusted for sending
* else returns the untrusted recipient. * else returns the untrusted recipient.
*/ */
- (nullable OWSRecipientIdentity *)untrustedIdentityForSendingToRecipientId:(NSString *)recipientId - (nullable OWSRecipientIdentity *)untrustedIdentityForSendingToRecipientId:(NSString *)recipientId;
protocolContext:(nullable id)protocolContext;
// This method can be called from any thread. // This method can be called from any thread.
- (void)processIncomingSyncMessage:(OWSSignalServiceProtosVerified *)verified; - (void)processIncomingSyncMessage:(OWSSignalServiceProtosVerified *)verified;

@ -305,7 +305,7 @@ NSString *const kNSNotificationName_IdentityStateDidChange = @"kNSNotificationNa
[self fireIdentityStateChangeNotification]; [self fireIdentityStateChangeNotification];
} }
- (OWSVerificationState)verificationStateForRecipientId:(NSString *)recipientId - (OWSVerificationState)verificationStateForRecipientIdWithoutTransaction:(NSString *)recipientId
{ {
__block OWSVerificationState result; __block OWSVerificationState result;
// Use a read/write transaction to block on latest. // Use a read/write transaction to block on latest.
@ -345,30 +345,31 @@ NSString *const kNSNotificationName_IdentityStateDidChange = @"kNSNotificationNa
} }
- (nullable OWSRecipientIdentity *)untrustedIdentityForSendingToRecipientId:(NSString *)recipientId - (nullable OWSRecipientIdentity *)untrustedIdentityForSendingToRecipientId:(NSString *)recipientId
protocolContext:(nullable id)protocolContext
{ {
OWSAssert(recipientId.length > 0); OWSAssert(recipientId.length > 0);
OWSAssert([protocolContext isKindOfClass:[YapDatabaseReadWriteTransaction class]]);
YapDatabaseReadWriteTransaction *transaction = protocolContext; __block OWSRecipientIdentity *_Nullable result;
// Use a read/write transaction to block on latest.
OWSRecipientIdentity *_Nullable recipientIdentity = [self.dbConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *_Nonnull transaction) {
[OWSRecipientIdentity fetchObjectWithUniqueID:recipientId transaction:transaction]; OWSRecipientIdentity *_Nullable recipientIdentity =
[OWSRecipientIdentity fetchObjectWithUniqueID:recipientId transaction:transaction];
if (recipientIdentity == nil) { if (recipientIdentity == nil) {
// trust on first use // trust on first use
return nil; return;
} }
BOOL isTrusted = [self isTrustedIdentityKey:recipientIdentity.identityKey BOOL isTrusted = [self isTrustedIdentityKey:recipientIdentity.identityKey
recipientId:recipientId recipientId:recipientId
direction:TSMessageDirectionOutgoing direction:TSMessageDirectionOutgoing
protocolContext:protocolContext]; protocolContext:transaction];
if (isTrusted) { if (isTrusted) {
return nil; return;
} else { } else {
return recipientIdentity; result = recipientIdentity;
} }
}];
return result;
} }
- (void)fireIdentityStateChangeNotification - (void)fireIdentityStateChangeNotification

Loading…
Cancel
Save