From 34a8cf2bdaefa455fecd1ac514bd6dc903514687 Mon Sep 17 00:00:00 2001 From: Adam Sharp Date: Tue, 2 Jul 2024 12:19:12 -0400 Subject: [PATCH] Rename owsAssert to owsPrecondition --- Signal/AppLaunch/AppDelegate.swift | 4 +-- Signal/AppLaunch/AppEnvironment.swift | 2 +- Signal/AppLaunch/SignalApp.swift | 2 +- Signal/Calls/CallService.swift | 6 ++-- ...GroupCallRecordRingingCleanupManager.swift | 2 +- Signal/Calls/IndividualCall.swift | 2 +- Signal/Calls/IndividualCallService.swift | 2 +- ...lsListViewController+ViewModelLoader.swift | 14 ++++---- .../CallsListViewController.swift | 10 +++--- .../GroupCallViewController.swift | 14 ++++---- .../SimulatorCallUIAdaptee.swift | 6 ++-- ...eLinkQRCodeColorPickerViewController.swift | 2 +- .../QRCodes/UsernameLinkQRCodeGenerator.swift | 2 +- .../DatabaseRecoveryViewController.swift | 2 +- .../DonateChoosePaymentMethodSheet.swift | 2 +- ...ewController+OneTimeApplePayDonation.swift | 2 +- .../DonateViewController+State.swift | 2 +- ...aymentDetailsViewController+3DSecure.swift | 4 +-- ...ntDetailsViewController+GiftDonation.swift | 2 +- .../Chat List/ChatListViewController.swift | 2 +- .../MediaGallery/MediaGalleryCellItem.swift | 2 +- .../MediaGalleryCollectionViewUpdater.swift | 4 +-- .../MediaGallery/MediaGallerySections.swift | 14 ++++---- .../MediaTileViewController.swift | 2 +- .../AddToBlockListViewController.swift | 2 +- .../AddToGroupViewController.swift | 2 +- SignalNSE/NSEEnvironment.swift | 2 +- .../PniDistributionParameterBuilder.swift | 2 +- .../IncomingCallEventSyncMessageManager.swift | 2 +- .../DeletedCallRecordCleanupManager.swift | 4 +-- .../DeletedCallRecordStore.swift | 2 +- SignalServiceKit/Contacts/E164.swift | 2 +- .../Contacts/RecipientMerger.swift | 2 +- .../Contacts/Threads/TSGroupThread.m | 32 +++++++++---------- .../DebugLogs/ScrubbingLogFormatter.swift | 4 +-- SignalServiceKit/Environment/AppSetup.swift | 4 +-- .../GroupUpdateInfoMessageInserter.swift | 2 +- SignalServiceKit/Groups/GroupsV2.swift | 8 ++--- .../JobRecords/MessageSenderJobRecord.swift | 2 +- SignalServiceKit/Logging/OWSLogs.m | 2 +- .../DeleteForMeAddressableMessageFinder.swift | 2 +- ...eleteForMeOutgoingSyncMessageManager.swift | 4 +-- .../InteractionDeleteManager.swift | 2 +- .../Interactions/TSInfoMessage+Swift.swift | 2 +- .../Messages/MessageFetcherJob.swift | 2 +- .../Messages/MessageProcessor.swift | 2 +- SignalServiceKit/Messages/MessageSender.swift | 2 +- .../Messages/OWSIdentityManager.swift | 2 +- .../Messages/Stickers/StickerPackInfo.swift | 2 +- .../Messages/UD/SMKUDAccessKey.swift | 4 +-- ...kOutgoingCallEventSyncMessageManager.swift | 4 +-- .../Network/API/RESTNetworkManager.swift | 2 +- .../AccountAttributesRequestFactory.swift | 4 +-- .../Network/OWSChatConnection.swift | 4 +-- .../Network/WebSocketPromise.swift | 4 +-- .../NotificationPresenterImpl.swift | 2 +- SignalServiceKit/OWSAsserts/OWSAsserts.h | 10 +++--- .../OWSAsserts/OWSSwiftUtils.swift | 9 ++++-- SignalServiceKit/Randomness/Randomness.m | 4 +-- .../SCKExceptionWrapper/SCKExceptionWrapper.m | 2 +- SignalServiceKit/SSKEnvironment.swift | 2 +- .../Security/OWSHTTPSecurityPolicy.m | 4 +-- .../AxolotlStore/Model/LegacyChainKey.m | 4 +-- .../AxolotlStore/Model/LegacyMessageKeys.m | 6 ++-- .../AxolotlStore/Model/LegacyReceivingChain.m | 4 +-- .../AxolotlStore/Model/LegacyRootKey.m | 2 +- .../AxolotlStore/Model/LegacySendingChain.m | 4 +-- .../AxolotlStore/Model/LegacySessionState.m | 8 ++--- .../Storage/AxolotlStore/Model/PreKeyRecord.m | 2 +- .../AxolotlStore/SSKSignedPreKeyStore.m | 2 +- .../Storage/Database/DatabaseRecovery.swift | 8 ++--- .../Database/GRDBDatabaseStorageAdapter.swift | 8 ++--- .../SDSKeyValueStore/SDSKeyValueStore+ObjC.m | 4 +-- .../Paypal+WebAuthentication.swift | 2 +- .../ReceiptCredentialRequestError.swift | 2 +- .../SubscriptionManagerImpl.swift | 2 +- SignalServiceKit/TSConstants.swift | 2 +- .../TestUtils/MockSSKEnvironment.swift | 2 +- .../TestUtils/TestProtocolRunner.swift | 2 +- SignalServiceKit/Util/Currency.swift | 2 +- .../Util/ImageMetadata/PngChunker.swift | 2 +- SignalServiceKit/Util/ModelReadCache.swift | 2 +- SignalServiceKit/Util/NSData+OWS.m | 2 +- SignalServiceKit/Util/OWSFileSystem.m | 6 ++-- SignalServiceKit/Util/OrderedDictionary.swift | 4 +-- SignalServiceKit/Util/SqliteUtil.swift | 6 ++-- .../PreKeys/SignedPreKeyDeletionTests.swift | 4 +-- .../DisappearingMessageFinderTest.swift | 2 +- .../Database/DatabaseRecoveryTest.swift | 2 +- .../ShareViewController.swift | 2 +- .../ContactSharing/ContactShareField.swift | 8 ++--- .../ContactShareViewController.swift | 2 +- .../DeleteSystemContactViewController.swift | 2 +- 93 files changed, 184 insertions(+), 181 deletions(-) diff --git a/Signal/AppLaunch/AppDelegate.swift b/Signal/AppLaunch/AppDelegate.swift index f3f9f0de74..4aeac2eb7e 100644 --- a/Signal/AppLaunch/AppDelegate.swift +++ b/Signal/AppLaunch/AppDelegate.swift @@ -463,8 +463,8 @@ final class AppDelegate: UIResponder, UIApplicationDelegate { ) { Logger.info("") AssertIsOnMainThread() - owsAssert(!AppReadiness.isAppReady) - owsAssert(!CurrentAppContext().isRunningTests) + owsPrecondition(!AppReadiness.isAppReady) + owsPrecondition(!CurrentAppContext().isRunningTests) let appContext = launchContext.appContext diff --git a/Signal/AppLaunch/AppEnvironment.swift b/Signal/AppLaunch/AppEnvironment.swift index 7642db0b06..d7b336b135 100644 --- a/Signal/AppLaunch/AppEnvironment.swift +++ b/Signal/AppLaunch/AppEnvironment.swift @@ -10,7 +10,7 @@ public class AppEnvironment: NSObject { private static var _shared: AppEnvironment? static func setSharedEnvironment(_ appEnvironment: AppEnvironment) { - owsAssert(self._shared == nil) + owsPrecondition(self._shared == nil) self._shared = appEnvironment } diff --git a/Signal/AppLaunch/SignalApp.swift b/Signal/AppLaunch/SignalApp.swift index 854f47cef9..780b92e1b4 100644 --- a/Signal/AppLaunch/SignalApp.swift +++ b/Signal/AppLaunch/SignalApp.swift @@ -66,7 +66,7 @@ extension SignalApp { func showLaunchInterface(_ launchInterface: LaunchInterface, launchStartedAt: TimeInterval) { AssertIsOnMainThread() - owsAssert(AppReadiness.isAppReady) + owsPrecondition(AppReadiness.isAppReady) let startupDuration = CACurrentMediaTime() - launchStartedAt let formattedStartupDuration = String(format: "%.3f", startupDuration) diff --git a/Signal/Calls/CallService.swift b/Signal/Calls/CallService.swift index a0e35f6796..3385bf3d4d 100644 --- a/Signal/Calls/CallService.swift +++ b/Signal/Calls/CallService.swift @@ -291,7 +291,7 @@ final class CallService: CallServiceStateObserver, CallServiceStateDelegate { private func updateIsLocalAudioMutedWithMicrophonePermission(call: SignalCall, isLocalAudioMuted: Bool) { AssertIsOnMainThread() - owsAssert(call === callServiceState.currentCall) + owsPrecondition(call === callServiceState.currentCall) switch call.mode { case .groupThread(let call as GroupCall), .callLink(let call as GroupCall): @@ -346,7 +346,7 @@ final class CallService: CallServiceStateObserver, CallServiceStateDelegate { private func updateIsLocalVideoMutedWithCameraPermissions(call: SignalCall, isLocalVideoMuted: Bool) { AssertIsOnMainThread() - owsAssert(call === callServiceState.currentCall) + owsPrecondition(call === callServiceState.currentCall) switch call.mode { case .groupThread(let call as GroupCall), .callLink(let call as GroupCall): @@ -949,7 +949,7 @@ extension CallService: GroupCallObserver { case nil, .individual: owsFail("Can't receive callback without an active group call") case .groupThread(let currentCall as GroupCall), .callLink(let currentCall as GroupCall): - owsAssert(currentCall === groupCall) + owsPrecondition(currentCall === groupCall) if currentCall.shouldTerminateOnEndEvent { callServiceState.terminateCall(call!) } diff --git a/Signal/Calls/GroupCallRecordRingingCleanupManager.swift b/Signal/Calls/GroupCallRecordRingingCleanupManager.swift index c808815f6d..0d42510b9c 100644 --- a/Signal/Calls/GroupCallRecordRingingCleanupManager.swift +++ b/Signal/Calls/GroupCallRecordRingingCleanupManager.swift @@ -131,7 +131,7 @@ class GroupCallRecordRingingCleanupManager { groupThread: TSGroupThread, callRecords: [CallRecord] ) async throws { - owsAssert(callRecords.allSatisfy { $0.threadRowId == groupThread.sqliteRowId! }) + owsPrecondition(callRecords.allSatisfy { $0.threadRowId == groupThread.sqliteRowId! }) let peekInfo = try await self.groupCallPeekClient.fetchPeekInfo( groupThread: groupThread diff --git a/Signal/Calls/IndividualCall.swift b/Signal/Calls/IndividualCall.swift index 91121fc52d..26413258af 100644 --- a/Signal/Calls/IndividualCall.swift +++ b/Signal/Calls/IndividualCall.swift @@ -79,7 +79,7 @@ public class IndividualCall: CustomDebugStringConvertible { func setOutgoingCallIdAndUpdateCallRecord(_ callId: UInt64) { AssertIsOnMainThread() - owsAssert(self.direction == .outgoing) + owsPrecondition(self.direction == .outgoing) Logger.info("") self.callId = callId diff --git a/Signal/Calls/IndividualCallService.swift b/Signal/Calls/IndividualCallService.swift index 08ba852f08..aed0dbe106 100644 --- a/Signal/Calls/IndividualCallService.swift +++ b/Signal/Calls/IndividualCallService.swift @@ -1124,7 +1124,7 @@ final class IndividualCallService: CallServiceStateObserver { */ private func handleConnected(call: SignalCall) { AssertIsOnMainThread() - owsAssert(call === callServiceState.currentCall) + owsPrecondition(call === callServiceState.currentCall) Logger.info("call: \(call)") // End the background task. diff --git a/Signal/Calls/UserInterface/CallsListViewController+ViewModelLoader.swift b/Signal/Calls/UserInterface/CallsListViewController+ViewModelLoader.swift index aacd653a3e..8577b02d84 100644 --- a/Signal/Calls/UserInterface/CallsListViewController+ViewModelLoader.swift +++ b/Signal/Calls/UserInterface/CallsListViewController+ViewModelLoader.swift @@ -58,7 +58,7 @@ extension CallsListViewController { maxCachedViewModelCount: Int = 150, maxCoalescedCallsInOneViewModel: UInt = 50 ) { - owsAssert( + owsPrecondition( maxCachedViewModelCount >= viewModelPageSize, "Must be able to cache at least one page of view models!" ) @@ -265,7 +265,7 @@ extension CallsListViewController { tx: tx ) - owsAssert(rehydratedCount <= viewModelsToLoadCount) + owsPrecondition(rehydratedCount <= viewModelsToLoadCount) viewModelsToLoadCount -= rehydratedCount if viewModelsToLoadCount == 0 { @@ -325,7 +325,7 @@ extension CallsListViewController { return true case .loaded(let newViewModels): - owsAssert(newViewModels.count > 0) + owsPrecondition(newViewModels.count > 0) loadedViewModelReferences.prepend( newElements: newViewModels.map { $0.reference } @@ -456,7 +456,7 @@ extension CallsListViewController { maxCount: UInt, tx: DBReadTransaction ) -> [CallViewModel] { - owsAssert( + owsPrecondition( cachedViewModels.isEmpty || cachedViewModels.last!.reference == loadedViewModelReferences.last!, "Unexpectedly loading brand new view models, but last loaded view model reference does not have a cached view model!" ) @@ -513,7 +513,7 @@ extension CallsListViewController { } } - owsAssert( + owsPrecondition( groupedCallRecordsForViewModels.allSatisfy { !$0.isEmpty }, "Had an empty grouping for a view model. How did this happen?" ) @@ -583,7 +583,7 @@ extension CallsListViewController { currentNewestViewModel: CallViewModel, tx: DBReadTransaction ) -> LoadBrandNewViewModelsNewerResult { - owsAssert(currentNewestViewModel.reference == loadedViewModelReferences.first) + owsPrecondition(currentNewestViewModel.reference == loadedViewModelReferences.first) let newCallRecordsCursor: CallRecordCursor = callRecordLoader.loadCallRecords( loadDirection: .newerThan( @@ -604,7 +604,7 @@ extension CallsListViewController { /// /// We'll reverse them here, and return them ordered descending, to /// make things easier on our callers. - owsAssert(pageOfNewCallRecordsAsc.isSortedByTimestamp(.ascending)) + owsPrecondition(pageOfNewCallRecordsAsc.isSortedByTimestamp(.ascending)) let pageOfNewCallRecords = pageOfNewCallRecordsAsc.reversed() if pageOfNewCallRecords.isEmpty { diff --git a/Signal/Calls/UserInterface/CallsListViewController.swift b/Signal/Calls/UserInterface/CallsListViewController.swift index 6b8065870d..e6f252bd66 100644 --- a/Signal/Calls/UserInterface/CallsListViewController.swift +++ b/Signal/Calls/UserInterface/CallsListViewController.swift @@ -815,19 +815,19 @@ class CallsListViewController: OWSViewController, HomeTabViewController, CallSer deps: Dependencies, tx: SDSAnyReadTransaction ) -> CallViewModel { - owsAssert( + owsPrecondition( coalescedCallRecords.allSatisfy { $0.threadRowId == primaryCallRecord.threadRowId }, "Coalesced call records were for a different thread than the primary!" ) - owsAssert( + owsPrecondition( coalescedCallRecords.allSatisfy { $0.callDirection == primaryCallRecord.callDirection }, "Coalesced call records were of a different direction than the primary!" ) - owsAssert( + owsPrecondition( coalescedCallRecords.allSatisfy { $0.callStatus.isMissedCall == primaryCallRecord.callStatus.isMissedCall }, "Coalesced call records were of a different missed status than the primary!" ) - owsAssert( + owsPrecondition( ([primaryCallRecord] + coalescedCallRecords).isSortedByTimestamp(.descending), "Primary and coalesced call records were not ordered descending by timestamp!" ) @@ -1308,7 +1308,7 @@ extension CallsListViewController: UITableViewDelegate { private func viewModel( forIndexPathThatShouldHaveOne indexPath: IndexPath ) -> CallViewModel? { - owsAssert( + owsPrecondition( indexPath.section == Section.existingCalls.rawValue, "Unexpected section for index path: \(indexPath.section)" ) diff --git a/Signal/Calls/UserInterface/GroupCallViewController.swift b/Signal/Calls/UserInterface/GroupCallViewController.swift index 7661b2bdce..5622d097b0 100644 --- a/Signal/Calls/UserInterface/GroupCallViewController.swift +++ b/Signal/Calls/UserInterface/GroupCallViewController.swift @@ -1354,7 +1354,7 @@ extension GroupCallViewController: CallViewControllerWindowReference { extension GroupCallViewController: GroupCallObserver { func groupCallLocalDeviceStateChanged(_ call: GroupCall) { AssertIsOnMainThread() - owsAssert(self.groupCall === call) + owsPrecondition(self.groupCall === call) guard self.isReadyToHandleObserver else { return } @@ -1373,7 +1373,7 @@ extension GroupCallViewController: GroupCallObserver { func groupCallRemoteDeviceStatesChanged(_ call: GroupCall) { AssertIsOnMainThread() - owsAssert(self.groupCall === call) + owsPrecondition(self.groupCall === call) guard self.isReadyToHandleObserver else { return } @@ -1388,7 +1388,7 @@ extension GroupCallViewController: GroupCallObserver { func groupCallPeekChanged(_ call: GroupCall) { AssertIsOnMainThread() - owsAssert(self.groupCall === call) + owsPrecondition(self.groupCall === call) guard self.isReadyToHandleObserver else { return } @@ -1398,7 +1398,7 @@ extension GroupCallViewController: GroupCallObserver { func groupCallEnded(_ call: GroupCall, reason: GroupCallEndReason) { AssertIsOnMainThread() - owsAssert(self.groupCall === call) + owsPrecondition(self.groupCall === call) guard self.isReadyToHandleObserver else { return } @@ -1470,7 +1470,7 @@ extension GroupCallViewController: GroupCallObserver { func groupCallReceivedReactions(_ call: GroupCall, reactions: [SignalRingRTC.Reaction]) { AssertIsOnMainThread() - owsAssert(self.groupCall === call) + owsPrecondition(self.groupCall === call) guard self.isReadyToHandleObserver else { return } @@ -1508,7 +1508,7 @@ extension GroupCallViewController: GroupCallObserver { func groupCallReceivedRaisedHands(_ call: GroupCall, raisedHands: [DemuxId]) { AssertIsOnMainThread() - owsAssert(self.groupCall === call) + owsPrecondition(self.groupCall === call) guard self.isReadyToHandleObserver else { return } @@ -1518,7 +1518,7 @@ extension GroupCallViewController: GroupCallObserver { func handleUntrustedIdentityError(_ call: GroupCall) { AssertIsOnMainThread() - owsAssert(self.groupCall === call) + owsPrecondition(self.groupCall === call) guard self.isReadyToHandleObserver else { return } diff --git a/Signal/Calls/UserInterface/SimulatorCallUIAdaptee.swift b/Signal/Calls/UserInterface/SimulatorCallUIAdaptee.swift index 3c78861578..5b7c871a37 100644 --- a/Signal/Calls/UserInterface/SimulatorCallUIAdaptee.swift +++ b/Signal/Calls/UserInterface/SimulatorCallUIAdaptee.swift @@ -81,7 +81,7 @@ class SimulatorCallUIAdaptee: NSObject, CallUIAdaptee { func localHangupCall(_ call: SignalCall) { AssertIsOnMainThread() // If both parties hang up at the same moment, call might already be nil. - owsAssert(self.callService.callServiceState.currentCall == nil || call.localId == self.callService.callServiceState.currentCall?.localId) + owsPrecondition(self.callService.callServiceState.currentCall == nil || call.localId == self.callService.callServiceState.currentCall?.localId) callService.handleLocalHangupCall(call) } @@ -105,13 +105,13 @@ class SimulatorCallUIAdaptee: NSObject, CallUIAdaptee { func setIsMuted(call: SignalCall, isMuted: Bool) { AssertIsOnMainThread() - owsAssert(call.localId == self.callService.callServiceState.currentCall?.localId) + owsPrecondition(call.localId == self.callService.callServiceState.currentCall?.localId) self.callService.updateIsLocalAudioMuted(isLocalAudioMuted: isMuted) } func setHasLocalVideo(call: SignalCall, hasLocalVideo: Bool) { AssertIsOnMainThread() - owsAssert(call.localId == self.callService.callServiceState.currentCall?.localId) + owsPrecondition(call.localId == self.callService.callServiceState.currentCall?.localId) self.callService.updateIsLocalVideoMuted(isLocalVideoMuted: !hasLocalVideo) } } diff --git a/Signal/Usernames/Links/UsernameLinkQRCodeColorPickerViewController.swift b/Signal/Usernames/Links/UsernameLinkQRCodeColorPickerViewController.swift index 6ac76c04b6..7fac5a9f84 100644 --- a/Signal/Usernames/Links/UsernameLinkQRCodeColorPickerViewController.swift +++ b/Signal/Usernames/Links/UsernameLinkQRCodeColorPickerViewController.swift @@ -25,7 +25,7 @@ class UsernameLinkQRCodeColorPickerViewController: OWSTableViewController2 { qrCodeTemplateImage: UIImage, delegate: UsernameLinkQRCodeColorPickerDelegate ) { - owsAssert(qrCodeTemplateImage.renderingMode == .alwaysTemplate) + owsPrecondition(qrCodeTemplateImage.renderingMode == .alwaysTemplate) self.startingColor = currentColor self.currentColor = currentColor diff --git a/Signal/src/QRCodes/UsernameLinkQRCodeGenerator.swift b/Signal/src/QRCodes/UsernameLinkQRCodeGenerator.swift index 3dee3f918d..c3d86376c1 100644 --- a/Signal/src/QRCodes/UsernameLinkQRCodeGenerator.swift +++ b/Signal/src/QRCodes/UsernameLinkQRCodeGenerator.swift @@ -119,7 +119,7 @@ extension Bitmaps.Image { dimensionPercentage percentage: CGFloat, paddingPoints: Int ) -> Bitmaps.Rect { - owsAssert( + owsPrecondition( percentage < 0.5, // Roughly the dimension percentage for deadzoning 30% of the surface area "Deadzoning too much of a QR code means it might not scan!" ) diff --git a/Signal/src/ViewControllers/DatabaseRecoveryViewController.swift b/Signal/src/ViewControllers/DatabaseRecoveryViewController.swift index 636f7a88e5..73dd8edc7a 100644 --- a/Signal/src/ViewControllers/DatabaseRecoveryViewController.swift +++ b/Signal/src/ViewControllers/DatabaseRecoveryViewController.swift @@ -161,7 +161,7 @@ class DatabaseRecoveryViewController: OWSViewController { @objc private func didTapToExportDatabase() { - owsAssert(DebugFlags.internalSettings, "Only internal users can export databases") + owsPrecondition(DebugFlags.internalSettings, "Only internal users can export databases") SignalApp.showExportDatabaseUI(from: self) } diff --git a/Signal/src/ViewControllers/Donations/DonateChoosePaymentMethodSheet.swift b/Signal/src/ViewControllers/Donations/DonateChoosePaymentMethodSheet.swift index 638377c4af..bc9a743d38 100644 --- a/Signal/src/ViewControllers/Donations/DonateChoosePaymentMethodSheet.swift +++ b/Signal/src/ViewControllers/Donations/DonateChoosePaymentMethodSheet.swift @@ -292,7 +292,7 @@ class DonateChoosePaymentMethodSheet: OWSTableSheetViewController { .filter(supportedPaymentMethods.contains) .map(createButtonFor(paymentMethod:)) - owsAssert(!paymentMethodButtons.isEmpty, "Expected at least one payment method") + owsPrecondition(!paymentMethodButtons.isEmpty, "Expected at least one payment method") let stackView = UIStackView(arrangedSubviews: paymentMethodButtons) stackView.axis = .vertical diff --git a/Signal/src/ViewControllers/Donations/DonateViewController+OneTimeApplePayDonation.swift b/Signal/src/ViewControllers/Donations/DonateViewController+OneTimeApplePayDonation.swift index 9f1a82d94e..bc38803f26 100644 --- a/Signal/src/ViewControllers/Donations/DonateViewController+OneTimeApplePayDonation.swift +++ b/Signal/src/ViewControllers/Donations/DonateViewController+OneTimeApplePayDonation.swift @@ -37,7 +37,7 @@ extension DonateViewController { for: .applePay(payment: payment) ) }.done(on: DispatchQueue.main) { confirmedIntent -> Void in - owsAssert( + owsPrecondition( confirmedIntent.redirectToUrl == nil, "[Donations] There shouldn't be a 3DS redirect for Apple Pay" ) diff --git a/Signal/src/ViewControllers/Donations/DonateViewController+State.swift b/Signal/src/ViewControllers/Donations/DonateViewController+State.swift index bbdad4de90..37d65426cd 100644 --- a/Signal/src/ViewControllers/Donations/DonateViewController+State.swift +++ b/Signal/src/ViewControllers/Donations/DonateViewController+State.swift @@ -310,7 +310,7 @@ extension DonateViewController { } fileprivate func selectSubscriptionLevel(_ newValue: SubscriptionLevel) -> MonthlyState { - owsAssert(subscriptionLevels.contains(newValue), "Subscription level not found") + owsPrecondition(subscriptionLevels.contains(newValue), "Subscription level not found") return MonthlyState( subscriptionLevels: subscriptionLevels, selectedCurrencyCode: selectedCurrencyCode, diff --git a/Signal/src/ViewControllers/Donations/DonationPaymentDetailsViewController+3DSecure.swift b/Signal/src/ViewControllers/Donations/DonationPaymentDetailsViewController+3DSecure.swift index 18b9e630a0..0da8180cfc 100644 --- a/Signal/src/ViewControllers/Donations/DonationPaymentDetailsViewController+3DSecure.swift +++ b/Signal/src/ViewControllers/Donations/DonationPaymentDetailsViewController+3DSecure.swift @@ -9,7 +9,7 @@ import SignalServiceKit extension DonationPaymentDetailsViewController { func show3DS(for redirectUrl: URL) -> Promise { - owsAssert( + owsPrecondition( threeDSecureAuthenticationSession == nil, "[Donations] Unexpectedly already had a 3DS authentication session going" ) @@ -53,7 +53,7 @@ extension DonationPaymentDetailsViewController { session.presentationContextProvider = self - owsAssert( + owsPrecondition( session.start(), "[Donations] Failed to start 3DS authentication session. Was it set up correctly?" ) diff --git a/Signal/src/ViewControllers/Donations/DonationPaymentDetailsViewController+GiftDonation.swift b/Signal/src/ViewControllers/Donations/DonationPaymentDetailsViewController+GiftDonation.swift index 13fafa9947..2090c4ee13 100644 --- a/Signal/src/ViewControllers/Donations/DonationPaymentDetailsViewController+GiftDonation.swift +++ b/Signal/src/ViewControllers/Donations/DonationPaymentDetailsViewController+GiftDonation.swift @@ -68,7 +68,7 @@ extension DonationPaymentDetailsViewController { Logger.info("[Gifting] Gifting card donation finished") self?.onFinished(nil) }.catch(on: DispatchQueue.main) { [weak self] error in - owsAssert(error is DonationViewsUtil.Gifts.SendGiftError) + owsPrecondition(error is DonationViewsUtil.Gifts.SendGiftError) Logger.warn("[Gifting] Gifting card donation failed") self?.onFinished(error) diff --git a/Signal/src/ViewControllers/HomeView/Chat List/ChatListViewController.swift b/Signal/src/ViewControllers/HomeView/Chat List/ChatListViewController.swift index 6ebe62e8b1..c8867b7cf4 100644 --- a/Signal/src/ViewControllers/HomeView/Chat List/ChatListViewController.swift +++ b/Signal/src/ViewControllers/HomeView/Chat List/ChatListViewController.swift @@ -619,7 +619,7 @@ public class ChatListViewController: OWSViewController, HomeTabViewController { @objc private func pullToRefreshPerformed(_ refreshControl: UIRefreshControl) { AssertIsOnMainThread() - owsAssert(DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice == false) + owsPrecondition(DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice == false) syncManager.sendAllSyncRequestMessages(timeout: 20).ensure { refreshControl.endRefreshing() diff --git a/Signal/src/ViewControllers/MediaGallery/MediaGalleryCellItem.swift b/Signal/src/ViewControllers/MediaGallery/MediaGalleryCellItem.swift index 134c97c855..b884707308 100644 --- a/Signal/src/ViewControllers/MediaGallery/MediaGalleryCellItem.swift +++ b/Signal/src/ViewControllers/MediaGallery/MediaGalleryCellItem.swift @@ -108,7 +108,7 @@ class MediaGalleryCellItemPhotoVideo: PhotoGridItem { } private var videoDurationPromise: Promise { - owsAssert(galleryItem.isVideo) + owsPrecondition(galleryItem.isVideo) switch galleryItem.attachmentStream.attachmentStream.concreteStreamType { case .legacy(let tSAttachment): return TSAttachmentVideoDurationHelper.shared.promisedDuration( diff --git a/Signal/src/ViewControllers/MediaGallery/MediaGalleryCollectionViewUpdater.swift b/Signal/src/ViewControllers/MediaGallery/MediaGalleryCollectionViewUpdater.swift index 43d69e77ff..00f538a31b 100644 --- a/Signal/src/ViewControllers/MediaGallery/MediaGalleryCollectionViewUpdater.swift +++ b/Signal/src/ViewControllers/MediaGallery/MediaGalleryCollectionViewUpdater.swift @@ -18,7 +18,7 @@ extension IndexSet { /// /// For example, if `self` contains { 5, 6, 7 } then `nthIndex(1)` returns `6`. func nthIndex(_ n: Int) -> Element? { - owsAssert(n >= 0) + owsPrecondition(n >= 0) guard n < count else { return nil } @@ -98,7 +98,7 @@ struct MediaGalleryCollectionViewUpdater { let originalNumberOfItems: Int mutating func remove(at i: Int) { - owsAssert(i < survivors.count) + owsPrecondition(i < survivors.count) if let index = survivors.nthIndex(i) { // Delete an original item. survivors.remove(index) diff --git a/Signal/src/ViewControllers/MediaGallery/MediaGallerySections.swift b/Signal/src/ViewControllers/MediaGallery/MediaGallerySections.swift index 1b2361c531..30f63692c3 100644 --- a/Signal/src/ViewControllers/MediaGallery/MediaGallerySections.swift +++ b/Signal/src/ViewControllers/MediaGallery/MediaGallerySections.swift @@ -234,7 +234,7 @@ internal struct MediaGallerySections MediaGalleryIndexPath? { - owsAssert(naiveIndex >= 0, "should not be used for indexes before the current section") + owsPrecondition(naiveIndex >= 0, "should not be used for indexes before the current section") var currentSectionIndex = initialSectionIndex var limitInCurrentSection = naiveIndex @@ -632,7 +632,7 @@ internal struct MediaGallerySections Item? { - owsAssert(path.count == 2) + owsPrecondition(path.count == 2) guard let slot = state.itemsBySection[safe: path.section]?.value[safe: path.item] else { owsFailDebug("invalid path \(path)") return nil @@ -1193,7 +1193,7 @@ internal struct MediaGallerySections MediaGalleryIndexPath? { - owsAssert(path.count == 2) + owsPrecondition(path.count == 2) var result = path // Next item? @@ -1218,7 +1218,7 @@ internal struct MediaGallerySections MediaGalleryIndexPath? { - owsAssert(path.count == 2) + owsPrecondition(path.count == 2) var result = path // Previous item? diff --git a/Signal/src/ViewControllers/MediaGallery/MediaTileViewController.swift b/Signal/src/ViewControllers/MediaGallery/MediaTileViewController.swift index 2970cabe19..7eb3452e94 100644 --- a/Signal/src/ViewControllers/MediaGallery/MediaTileViewController.swift +++ b/Signal/src/ViewControllers/MediaGallery/MediaTileViewController.swift @@ -40,7 +40,7 @@ extension MediaTileViewController: MediaGalleryCollectionViewUpdaterDelegate { func updaterDidFinish(numberOfSectionsBefore: Int, numberOfSectionsAfter: Int) { Logger.debug("\(numberOfSectionsBefore) -> \(numberOfSectionsAfter)") - owsAssert(numberOfSectionsAfter == mediaGallery.galleryDates.count) + owsPrecondition(numberOfSectionsAfter == mediaGallery.galleryDates.count) if numberOfSectionsBefore == 0 && numberOfSectionsAfter > 0 { // Adding a "load newer" section. It goes at the end. collectionView?.insertSections(IndexSet(integer: localSection(numberOfSectionsAfter))) diff --git a/Signal/src/ViewControllers/RecipientPicker/AddToBlockListViewController.swift b/Signal/src/ViewControllers/RecipientPicker/AddToBlockListViewController.swift index 9f78e1b3a0..96442483d9 100644 --- a/Signal/src/ViewControllers/RecipientPicker/AddToBlockListViewController.swift +++ b/Signal/src/ViewControllers/RecipientPicker/AddToBlockListViewController.swift @@ -93,7 +93,7 @@ extension AddToBlockListViewController: RecipientPickerDelegate, UsernameLinkSca case .address(let address): #if DEBUG let isBlocked = blockingManager.isAddressBlocked(address, transaction: transaction) - owsAssert(!isBlocked, "It should be impossible to see a blocked connection in this view") + owsPrecondition(!isBlocked, "It should be impossible to see a blocked connection in this view") #endif return nil case .group(let thread): diff --git a/Signal/src/ViewControllers/ThreadSettings/AddToGroupViewController.swift b/Signal/src/ViewControllers/ThreadSettings/AddToGroupViewController.swift index 0c92d205fb..db73c8bba9 100644 --- a/Signal/src/ViewControllers/ThreadSettings/AddToGroupViewController.swift +++ b/Signal/src/ViewControllers/ThreadSettings/AddToGroupViewController.swift @@ -139,7 +139,7 @@ public class AddToGroupViewController: OWSTableViewController2 { private func addToGroup(_ groupThread: TSGroupThread, shortName: String) { AssertIsOnMainThread() - owsAssert(groupThread.isGroupV2Thread) // non-gv2 filtered above when fetching groups + owsPrecondition(groupThread.isGroupV2Thread) // non-gv2 filtered above when fetching groups guard let serviceId = self.address.serviceId else { GroupViewUtils.showInvalidGroupMemberAlert(fromViewController: self) diff --git a/SignalNSE/NSEEnvironment.swift b/SignalNSE/NSEEnvironment.swift index 68029813c5..c152f9aea5 100644 --- a/SignalNSE/NSEEnvironment.swift +++ b/SignalNSE/NSEEnvironment.swift @@ -164,7 +164,7 @@ class NSEEnvironment: Dependencies { private func setAppIsReady() { AssertIsOnMainThread() - owsAssert(!AppReadiness.isAppReady) + owsPrecondition(!AppReadiness.isAppReady) // Note that this does much more than set a flag; it will also run all deferred blocks. AppReadiness.setAppIsReady() diff --git a/SignalServiceKit/Account/PniDistributionParameterBuilder.swift b/SignalServiceKit/Account/PniDistributionParameterBuilder.swift index 27420febea..aca7e3e1cf 100644 --- a/SignalServiceKit/Account/PniDistributionParameterBuilder.swift +++ b/SignalServiceKit/Account/PniDistributionParameterBuilder.swift @@ -62,7 +62,7 @@ public enum PniDistribution { registrationId: UInt32, deviceMessage: DeviceMessage ) { - owsAssert(deviceId == deviceMessage.destinationDeviceId) + owsPrecondition(deviceId == deviceMessage.destinationDeviceId) devicePniSignedPreKeys["\(deviceId)"] = signedPreKey devicePniPqLastResortPreKeys["\(deviceId)"] = pqLastResortPreKey diff --git a/SignalServiceKit/Calls/CallRecord/IncomingCallEventSyncMessageManager.swift b/SignalServiceKit/Calls/CallRecord/IncomingCallEventSyncMessageManager.swift index 39c8f3ce3a..20cf2c6c3b 100644 --- a/SignalServiceKit/Calls/CallRecord/IncomingCallEventSyncMessageManager.swift +++ b/SignalServiceKit/Calls/CallRecord/IncomingCallEventSyncMessageManager.swift @@ -485,7 +485,7 @@ private extension IncomingCallEventSyncMessageManagerImpl { syncMessageTimestamp: UInt64, tx: DBWriteTransaction ) { - owsAssert(callInteraction.uniqueThreadId == thread.uniqueId) + owsPrecondition(callInteraction.uniqueThreadId == thread.uniqueId) markAsReadShims.markThingsAsReadForIncomingSyncMessage( callInteraction: callInteraction, diff --git a/SignalServiceKit/Calls/DeletedCallRecord/DeletedCallRecordCleanupManager.swift b/SignalServiceKit/Calls/DeletedCallRecord/DeletedCallRecordCleanupManager.swift index 4d53bfcd21..cda4f49f85 100644 --- a/SignalServiceKit/Calls/DeletedCallRecord/DeletedCallRecordCleanupManager.swift +++ b/SignalServiceKit/Calls/DeletedCallRecord/DeletedCallRecordCleanupManager.swift @@ -54,7 +54,7 @@ final class DeletedCallRecordCleanupManagerImpl: DeletedCallRecordCleanupManager func release() { let isUnlocked = lock.tryToClearFlag() - owsAssert(isUnlocked) + owsPrecondition(isUnlocked) } } @@ -151,7 +151,7 @@ final class DeletedCallRecordCleanupManagerImpl: DeletedCallRecordCleanupManager private func scheduleCleanup( beginningWith recordToScheduleExpiration: DeletedCallRecord ) { - owsAssert(cleanupLock.get()) + owsPrecondition(cleanupLock.get()) let secondsUntilNextCleanupPass: TimeInterval = max( recordToScheduleExpiration.secondsUntilExpiration( diff --git a/SignalServiceKit/Calls/DeletedCallRecord/DeletedCallRecordStore.swift b/SignalServiceKit/Calls/DeletedCallRecord/DeletedCallRecordStore.swift index e54032318a..45df0db561 100644 --- a/SignalServiceKit/Calls/DeletedCallRecord/DeletedCallRecordStore.swift +++ b/SignalServiceKit/Calls/DeletedCallRecord/DeletedCallRecordStore.swift @@ -202,7 +202,7 @@ class DeletedCallRecordStoreImpl: DeletedCallRecordStore { equalityClauses.append("\(column.rawValue) = ?") equalityArgs.append(value) case .ascending(let column): - owsAssert( + owsPrecondition( orderingClause == nil, "Multiple ordering clauses! How did that happen?" ) diff --git a/SignalServiceKit/Contacts/E164.swift b/SignalServiceKit/Contacts/E164.swift index 85cf3cf891..30311f6c7d 100644 --- a/SignalServiceKit/Contacts/E164.swift +++ b/SignalServiceKit/Contacts/E164.swift @@ -33,7 +33,7 @@ public struct E164: Equatable, Hashable, Codable, CustomDebugStringConvertible { } public var uint64Value: UInt64 { - owsAssert(stringValue.first == "+") + owsPrecondition(stringValue.first == "+") return UInt64(stringValue.dropFirst())! } diff --git a/SignalServiceKit/Contacts/RecipientMerger.swift b/SignalServiceKit/Contacts/RecipientMerger.swift index 7a4dd423cd..f9682c09e8 100644 --- a/SignalServiceKit/Contacts/RecipientMerger.swift +++ b/SignalServiceKit/Contacts/RecipientMerger.swift @@ -216,7 +216,7 @@ class RecipientMergerImpl: RecipientMerger { ) -> SignalRecipient { // The caller checks this, but we assert here to maintain consistency with // all the other merging methods that check this themselves. - owsAssert(!localIdentifiers.containsAnyOf(aci: serviceIds.aci, phoneNumber: phoneNumber, pni: serviceIds.pni)) + owsPrecondition(!localIdentifiers.containsAnyOf(aci: serviceIds.aci, phoneNumber: phoneNumber, pni: serviceIds.pni)) let updatedValues = { () -> (phoneNumber: E164, pni: Pni)? in let pni = serviceIds.pni diff --git a/SignalServiceKit/Contacts/Threads/TSGroupThread.m b/SignalServiceKit/Contacts/Threads/TSGroupThread.m index 2874b06a36..58ac41fbc8 100644 --- a/SignalServiceKit/Contacts/Threads/TSGroupThread.m +++ b/SignalServiceKit/Contacts/Threads/TSGroupThread.m @@ -160,23 +160,23 @@ lastVisibleSortIdOnScreenPercentageObsolete:lastVisibleSortIdOnScreenPercentageO BOOL didAvatarChange = ![NSObject isNullableObject:newGroupModel.avatarHash equalTo:self.groupModel.avatarHash]; BOOL didNameChange = ![newGroupModel.groupNameOrDefault isEqualToString:self.groupModel.groupNameOrDefault]; - [self anyUpdateGroupThreadWithTransaction:transaction - block:^(TSGroupThread *thread) { - if ([thread.groupModel isKindOfClass:TSGroupModelV2.class]) { - if (![newGroupModel isKindOfClass:TSGroupModelV2.class]) { - // Can't downgrade a v2 group to a v1 group. - OWSFail(@"Invalid group model."); - } else { - // Can't downgrade a v2 group to an earlier revision. - TSGroupModelV2 *oldGroupModelV2 - = (TSGroupModelV2 *)thread.groupModel; - TSGroupModelV2 *newGroupModelV2 = (TSGroupModelV2 *)newGroupModel; - OWSAssert(oldGroupModelV2.revision <= newGroupModelV2.revision); - } - } + [self + anyUpdateGroupThreadWithTransaction:transaction + block:^(TSGroupThread *thread) { + if ([thread.groupModel isKindOfClass:TSGroupModelV2.class]) { + if (![newGroupModel isKindOfClass:TSGroupModelV2.class]) { + // Can't downgrade a v2 group to a v1 group. + OWSFail(@"Invalid group model."); + } else { + // Can't downgrade a v2 group to an earlier revision. + TSGroupModelV2 *oldGroupModelV2 = (TSGroupModelV2 *)thread.groupModel; + TSGroupModelV2 *newGroupModelV2 = (TSGroupModelV2 *)newGroupModel; + OWSPrecondition(oldGroupModelV2.revision <= newGroupModelV2.revision); + } + } - thread.groupModel = [newGroupModel copy]; - }]; + thread.groupModel = [newGroupModel copy]; + }]; [self updateGroupMemberRecordsWithTransaction:transaction]; // We only need to re-index the group if the group name changed. diff --git a/SignalServiceKit/DebugLogs/ScrubbingLogFormatter.swift b/SignalServiceKit/DebugLogs/ScrubbingLogFormatter.swift index 7fe5e6e4c6..c69ca5dc8e 100644 --- a/SignalServiceKit/DebugLogs/ScrubbingLogFormatter.swift +++ b/SignalServiceKit/DebugLogs/ScrubbingLogFormatter.swift @@ -33,14 +33,14 @@ class ScrubbingLogFormatter: NSObject, DDLogFormatter { // It's important to have some padding because we use that to mark the end // of the groupId. If we don't have padding, then we need to sort the // groupId Replacements from longest to shortest. - owsAssert(base64Padding != 0) + owsPrecondition(base64Padding != 0) let unredactedLength = 3 let redactedLength = base64Length - base64Padding - unredactedLength // This assertion exists to prevent someone from updating the values and forgetting to // update things here. - owsAssert(prefix == "g" && redactedLength >= 1) + owsPrecondition(prefix == "g" && redactedLength >= 1) let base64Character = "A-Za-z0-9+/" let paddingCharacter = "=" diff --git a/SignalServiceKit/Environment/AppSetup.swift b/SignalServiceKit/Environment/AppSetup.swift index 0c28ca3c75..b96b3dd124 100644 --- a/SignalServiceKit/Environment/AppSetup.swift +++ b/SignalServiceKit/Environment/AppSetup.swift @@ -124,8 +124,8 @@ public class AppSetup { // is locked, the download will fail if the temporary directory is // NSFileProtectionComplete. let temporaryDirectory = NSTemporaryDirectory() - owsAssert(OWSFileSystem.ensureDirectoryExists(temporaryDirectory)) - owsAssert(OWSFileSystem.protectFileOrFolder(atPath: temporaryDirectory, fileProtectionType: .completeUntilFirstUserAuthentication)) + owsPrecondition(OWSFileSystem.ensureDirectoryExists(temporaryDirectory)) + owsPrecondition(OWSFileSystem.protectFileOrFolder(atPath: temporaryDirectory, fileProtectionType: .completeUntilFirstUserAuthentication)) let tsConstants = TSConstants.shared let keyValueStoreFactory = testDependencies.keyValueStoreFactory ?? SDSKeyValueStoreFactory() diff --git a/SignalServiceKit/Groups/GroupUpdateInfoMessageInserter.swift b/SignalServiceKit/Groups/GroupUpdateInfoMessageInserter.swift index 5756ac5cf4..b3ff9c6656 100644 --- a/SignalServiceKit/Groups/GroupUpdateInfoMessageInserter.swift +++ b/SignalServiceKit/Groups/GroupUpdateInfoMessageInserter.swift @@ -196,7 +196,7 @@ class GroupUpdateInfoMessageInserterImpl: GroupUpdateInfoMessageInserter { /// compute above will never be empty. Even if we get a strange group /// update that somehow doesn't produce a diff, we'll get back a list /// with a single "generic group update" item in it. - owsAssert(!updateItemsForNewMessage.isEmpty) + owsPrecondition(!updateItemsForNewMessage.isEmpty) let infoMessage = TSInfoMessage.newGroupUpdateInfoMessage( timestamp: dateProvider().ows_millisecondsSince1970, spamReportingMetadata: spamReportingMetadata, diff --git a/SignalServiceKit/Groups/GroupsV2.swift b/SignalServiceKit/Groups/GroupsV2.swift index f3bbca6b63..08aef42eff 100644 --- a/SignalServiceKit/Groups/GroupsV2.swift +++ b/SignalServiceKit/Groups/GroupsV2.swift @@ -392,7 +392,7 @@ public struct GroupV2Change { public init(snapshot: GroupV2Snapshot?, changeActionsProto: GroupsProtoGroupChangeActions?, downloadedAvatars: GroupV2DownloadedAvatars) { - owsAssert(snapshot != nil || changeActionsProto != nil) + owsPrecondition(snapshot != nil || changeActionsProto != nil) self.snapshot = snapshot self.changeActionsProto = changeActionsProto self.downloadedAvatars = downloadedAvatars @@ -578,7 +578,7 @@ public class MockGroupsV2: GroupsV2 { public func groupId(forGroupSecretParamsData groupSecretParamsData: Data) throws -> Data { if CurrentAppContext().isRunningTests { - owsAssert(groupSecretParamsData.count >= 32) + owsPrecondition(groupSecretParamsData.count >= 32) return groupSecretParamsData.subdata(in: Int(0).. Data? { let v2GroupId = v1GroupId + v1GroupId - owsAssert(GroupManager.isV1GroupId(v1GroupId)) - owsAssert(GroupManager.isV2GroupId(v2GroupId)) + owsPrecondition(GroupManager.isV1GroupId(v1GroupId)) + owsPrecondition(GroupManager.isV2GroupId(v2GroupId)) return v2GroupId } diff --git a/SignalServiceKit/Jobs/JobRecords/MessageSenderJobRecord.swift b/SignalServiceKit/Jobs/JobRecords/MessageSenderJobRecord.swift index 1b85e60a56..8699281d4a 100644 --- a/SignalServiceKit/Jobs/JobRecords/MessageSenderJobRecord.swift +++ b/SignalServiceKit/Jobs/JobRecords/MessageSenderJobRecord.swift @@ -150,7 +150,7 @@ public final class MessageSenderJobRecord: JobRecord, FactoryInitializableFromRe transientMessage: TSOutgoingMessage, isHighPriority: Bool ) { - owsAssert( + owsPrecondition( transientMessage.shouldBeSaved.negated && !(transientMessage is OutgoingStoryMessage) && !(transientMessage is OWSSyncContactsMessage), diff --git a/SignalServiceKit/Logging/OWSLogs.m b/SignalServiceKit/Logging/OWSLogs.m index df085fd3f3..a578a1431a 100644 --- a/SignalServiceKit/Logging/OWSLogs.m +++ b/SignalServiceKit/Logging/OWSLogs.m @@ -13,7 +13,7 @@ NS_ASSUME_NONNULL_BEGIN static void logUnconditionally( DDLogFlag flag, const char *file, BOOL shouldTrimFilePath, NSUInteger line, const char *function, NSString *message) { - OWSCAssert(ShouldLogFlag(flag)); + OWSCPrecondition(ShouldLogFlag(flag)); NSString *fileObj = [NSString stringWithFormat:@"%s", file]; fileObj = shouldTrimFilePath ? fileObj.lastPathComponent : fileObj; DDLogMessage *logMessage = [[DDLogMessage alloc] initWithMessage:message diff --git a/SignalServiceKit/Messages/DeviceSyncing/DeleteForMe/DeleteForMeAddressableMessageFinder.swift b/SignalServiceKit/Messages/DeviceSyncing/DeleteForMe/DeleteForMeAddressableMessageFinder.swift index 22a74f4e07..460f395d62 100644 --- a/SignalServiceKit/Messages/DeviceSyncing/DeleteForMe/DeleteForMeAddressableMessageFinder.swift +++ b/SignalServiceKit/Messages/DeviceSyncing/DeleteForMe/DeleteForMeAddressableMessageFinder.swift @@ -60,7 +60,7 @@ final class DeleteForMeAddressableMessageFinderImpl: DeleteForMeAddressableMessa threadUniqueId: threadUniqueId, sdsTx: SDSDB.shimOnlyBridge(tx) ).iterate { interaction in - owsAssert( + owsPrecondition( interaction is TSIncomingMessage || interaction is TSOutgoingMessage, "Unexpected interaction type! \(type(of: interaction))" ) diff --git a/SignalServiceKit/Messages/DeviceSyncing/DeleteForMe/DeleteForMeOutgoingSyncMessageManager.swift b/SignalServiceKit/Messages/DeviceSyncing/DeleteForMe/DeleteForMeOutgoingSyncMessageManager.swift index 9751ac0088..9f733a2e82 100644 --- a/SignalServiceKit/Messages/DeviceSyncing/DeleteForMe/DeleteForMeOutgoingSyncMessageManager.swift +++ b/SignalServiceKit/Messages/DeviceSyncing/DeleteForMe/DeleteForMeOutgoingSyncMessageManager.swift @@ -61,10 +61,10 @@ extension DeleteForMeSyncMessage { func registerMessageDeletedFromThread(_ message: TSMessage) { do { let messageRowId = message.sqliteRowId! - owsAssert(messageRowId < lastAddedMessageRowId) + owsPrecondition(messageRowId < lastAddedMessageRowId) lastAddedMessageRowId = messageRowId - owsAssert(message.uniqueThreadId == threadUniqueId) + owsPrecondition(message.uniqueThreadId == threadUniqueId) } guard let addressableMessage: AddressableMessage = .addressing( diff --git a/SignalServiceKit/Messages/Interactions/InteractionDeleteManager.swift b/SignalServiceKit/Messages/Interactions/InteractionDeleteManager.swift index ebab1efb1a..10b86feaf6 100644 --- a/SignalServiceKit/Messages/Interactions/InteractionDeleteManager.swift +++ b/SignalServiceKit/Messages/Interactions/InteractionDeleteManager.swift @@ -213,7 +213,7 @@ final class InteractionDeleteManagerImpl: InteractionDeleteManager { ) { switch sideEffects.deleteForMeSyncMessage { case .sendSyncMessage(let interactionsThread): - owsAssert( + owsPrecondition( interactions.allSatisfy { $0.uniqueThreadId == interactionsThread.uniqueId }, "Thread did not match interaction!" ) diff --git a/SignalServiceKit/Messages/Interactions/TSInfoMessage+Swift.swift b/SignalServiceKit/Messages/Interactions/TSInfoMessage+Swift.swift index fcfa2f91b7..378852bece 100644 --- a/SignalServiceKit/Messages/Interactions/TSInfoMessage+Swift.swift +++ b/SignalServiceKit/Messages/Interactions/TSInfoMessage+Swift.swift @@ -33,7 +33,7 @@ public extension TSInfoMessage { groupThread: TSGroupThread, updateItems: [PersistableGroupUpdateItem] ) -> TSInfoMessage { - owsAssert(!updateItems.isEmpty) + owsPrecondition(!updateItems.isEmpty) var userInfoForNewMessage: [InfoMessageUserInfoKey: Any] = [:] diff --git a/SignalServiceKit/Messages/MessageFetcherJob.swift b/SignalServiceKit/Messages/MessageFetcherJob.swift index e7030f69d9..4409d3442f 100644 --- a/SignalServiceKit/Messages/MessageFetcherJob.swift +++ b/SignalServiceKit/Messages/MessageFetcherJob.swift @@ -215,7 +215,7 @@ public class MessageFetcherJob: NSObject { } private var isReadyToFetchMessagesViaRest: Bool { - owsAssert(CurrentAppContext().isNSE) + owsPrecondition(CurrentAppContext().isNSE) // The NSE has tight memory constraints. // For perf reasons, MessageProcessor keeps its queue in memory. diff --git a/SignalServiceKit/Messages/MessageProcessor.swift b/SignalServiceKit/Messages/MessageProcessor.swift index 1c1a0a8710..b025c36a68 100644 --- a/SignalServiceKit/Messages/MessageProcessor.swift +++ b/SignalServiceKit/Messages/MessageProcessor.swift @@ -619,7 +619,7 @@ private struct ProcessingRequestBuilder { for decryptedEnvelope: DecryptedIncomingEnvelope, tx: SDSAnyWriteTransaction ) -> ProcessingRequest.State { - owsAssert(CurrentAppContext().shouldProcessIncomingMessages) + owsPrecondition(CurrentAppContext().shouldProcessIncomingMessages) // Pre-processing has to happen during the same transaction that performed // decryption. diff --git a/SignalServiceKit/Messages/MessageSender.swift b/SignalServiceKit/Messages/MessageSender.swift index 20c7a35a45..4db2fe9cb1 100644 --- a/SignalServiceKit/Messages/MessageSender.swift +++ b/SignalServiceKit/Messages/MessageSender.swift @@ -1212,7 +1212,7 @@ public class MessageSender: Dependencies { ) async throws -> [SentDeviceMessage] { // The caller has access to the error, so they must throw it if no more // retries are allowed. - owsAssert(remainingAttempts > 0) + owsPrecondition(remainingAttempts > 0) let message = messageSend.message let serviceId = messageSend.serviceId diff --git a/SignalServiceKit/Messages/OWSIdentityManager.swift b/SignalServiceKit/Messages/OWSIdentityManager.swift index fcf3a5144a..09eec6cb24 100644 --- a/SignalServiceKit/Messages/OWSIdentityManager.swift +++ b/SignalServiceKit/Messages/OWSIdentityManager.swift @@ -306,7 +306,7 @@ public class OWSIdentityManagerImpl: OWSIdentityManager { public func setIdentityKeyPair(_ keyPair: ECKeyPair?, for identity: OWSIdentity, tx: DBWriteTransaction) { // Under no circumstances may we *clear* our *ACI* identity key. - owsAssert(keyPair != nil || identity != .aci) + owsPrecondition(keyPair != nil || identity != .aci) ownIdentityKeyValueStore.setObject(keyPair, key: identity.persistenceKey, transaction: tx) } diff --git a/SignalServiceKit/Messages/Stickers/StickerPackInfo.swift b/SignalServiceKit/Messages/Stickers/StickerPackInfo.swift index c920c27e77..2db6688eac 100644 --- a/SignalServiceKit/Messages/Stickers/StickerPackInfo.swift +++ b/SignalServiceKit/Messages/Stickers/StickerPackInfo.swift @@ -15,7 +15,7 @@ public class StickerPackInfo: MTLModel { @objc public init(packId: Data, packKey: Data) { - owsAssert(!packId.isEmpty && packKey.count == StickerManager.packKeyLength) + owsPrecondition(!packId.isEmpty && packKey.count == StickerManager.packKeyLength) self.packId = packId self.packKey = packKey diff --git a/SignalServiceKit/Messages/UD/SMKUDAccessKey.swift b/SignalServiceKit/Messages/UD/SMKUDAccessKey.swift index b6b6ef487b..9bb48ee724 100644 --- a/SignalServiceKit/Messages/UD/SMKUDAccessKey.swift +++ b/SignalServiceKit/Messages/UD/SMKUDAccessKey.swift @@ -31,8 +31,8 @@ public class SMKUDAccessKey: NSObject { /// Used to compose multiple Unidentified-Access-Keys for the multiRecipient endpoint public static func ^ (lhs: SMKUDAccessKey, rhs: SMKUDAccessKey) -> SMKUDAccessKey { - owsAssert(lhs.keyData.count == SMKUDAccessKey.kUDAccessKeyLength) - owsAssert(rhs.keyData.count == SMKUDAccessKey.kUDAccessKeyLength) + owsPrecondition(lhs.keyData.count == SMKUDAccessKey.kUDAccessKeyLength) + owsPrecondition(rhs.keyData.count == SMKUDAccessKey.kUDAccessKeyLength) let xoredBytes = zip(lhs.keyData, rhs.keyData).map(^) return .init(keyData: Data(xoredBytes)) diff --git a/SignalServiceKit/Mocks/CallRecord/MockOutgoingCallEventSyncMessageManager.swift b/SignalServiceKit/Mocks/CallRecord/MockOutgoingCallEventSyncMessageManager.swift index 9b2e5b64c9..b913277d7f 100644 --- a/SignalServiceKit/Mocks/CallRecord/MockOutgoingCallEventSyncMessageManager.swift +++ b/SignalServiceKit/Mocks/CallRecord/MockOutgoingCallEventSyncMessageManager.swift @@ -16,7 +16,7 @@ class MockOutgoingCallEventSyncMessageManager: OutgoingCallEventSyncMessageManag callEventTimestamp: UInt64, tx: DBWriteTransaction ) { - owsAssert(expectedCallEvent == callEvent) + owsPrecondition(expectedCallEvent == callEvent) syncMessageSendCount += 1 } @@ -26,7 +26,7 @@ class MockOutgoingCallEventSyncMessageManager: OutgoingCallEventSyncMessageManag callEvent: CallEvent, tx: DBWriteTransaction ) { - owsAssert(expectedCallEvent == callEvent) + owsPrecondition(expectedCallEvent == callEvent) syncMessageSendCount += 1 } } diff --git a/SignalServiceKit/Network/API/RESTNetworkManager.swift b/SignalServiceKit/Network/API/RESTNetworkManager.swift index 518e8f8518..15e3689c5e 100644 --- a/SignalServiceKit/Network/API/RESTNetworkManager.swift +++ b/SignalServiceKit/Network/API/RESTNetworkManager.swift @@ -40,7 +40,7 @@ class RESTNetworkManager { let isUdRequest = request.isUDRequest let label = isUdRequest ? "UD request" : "Non-UD request" if (isUdRequest) { - owsAssert(!request.shouldHaveAuthorizationHeaders) + owsPrecondition(!request.shouldHaveAuthorizationHeaders) } Logger.info("Making \(label): \(request)") diff --git a/SignalServiceKit/Network/API/Requests/AccountAttributes/AccountAttributesRequestFactory.swift b/SignalServiceKit/Network/API/Requests/AccountAttributes/AccountAttributesRequestFactory.swift index 01678750be..50bdda1127 100644 --- a/SignalServiceKit/Network/API/Requests/AccountAttributes/AccountAttributesRequestFactory.swift +++ b/SignalServiceKit/Network/API/Requests/AccountAttributes/AccountAttributesRequestFactory.swift @@ -10,7 +10,7 @@ public enum AccountAttributesRequestFactory { /// If you are updating capabilities for a secondary device, use `updateLinkedDeviceCapabilitiesRequest` instead public static func updatePrimaryDeviceAttributesRequest(_ attributes: AccountAttributes) -> TSRequest { - owsAssert( + owsPrecondition( DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? true, "Trying to set primary device attributes from secondary/linked device" ) @@ -36,7 +36,7 @@ public enum AccountAttributesRequestFactory { _ capabilities: AccountAttributes.Capabilities, tsAccountManager: TSAccountManager ) -> TSRequest { - owsAssert( + owsPrecondition( (tsAccountManager.registrationStateWithMaybeSneakyTransaction.isPrimaryDevice ?? false).negated, "Trying to set seconday device attributes from primary device" ) diff --git a/SignalServiceKit/Network/OWSChatConnection.swift b/SignalServiceKit/Network/OWSChatConnection.swift index 5992d791e9..c1dbc0bc61 100644 --- a/SignalServiceKit/Network/OWSChatConnection.swift +++ b/SignalServiceKit/Network/OWSChatConnection.swift @@ -1457,7 +1457,7 @@ internal class OWSChatConnectionWithLibSignalShadowing: OWSChatConnectionUsingSS } internal init(libsignalNet: Net, type: OWSChatConnectionType, appExpiry: AppExpiry, db: DB, shadowingFrequency: Double) { - owsAssert((0.0...1.0).contains(shadowingFrequency)) + owsPrecondition((0.0...1.0).contains(shadowingFrequency)) self.libsignalNet = libsignalNet self.chatService = Self.makeChatService(libsignalNet: libsignalNet) self._shadowingFrequency = shadowingFrequency @@ -1487,7 +1487,7 @@ internal class OWSChatConnectionWithLibSignalShadowing: OWSChatConnectionUsingSS } internal func updateShadowingFrequency(_ newFrequency: Double) { - owsAssert((0.0...1.0).contains(newFrequency)) + owsPrecondition((0.0...1.0).contains(newFrequency)) serialQueue.async { self.shadowingFrequency = newFrequency } diff --git a/SignalServiceKit/Network/WebSocketPromise.swift b/SignalServiceKit/Network/WebSocketPromise.swift index 7c2db17672..ae2140f0ee 100644 --- a/SignalServiceKit/Network/WebSocketPromise.swift +++ b/SignalServiceKit/Network/WebSocketPromise.swift @@ -85,7 +85,7 @@ final class WebSocketPromise: SSKWebSocketDelegate { func waitForResponse() -> Promise { let (promise, future) = Promise.pending() updateState { state in - owsAssert(state.waitingState == nil) + owsPrecondition(state.waitingState == nil) state.waitingState = .waitingForResponse(future) } return promise @@ -107,7 +107,7 @@ final class WebSocketPromise: SSKWebSocketDelegate { func waitForAllResponses() -> Promise<[Data]> { let (promise, future) = Promise<[Data]>.pending() updateState { state in - owsAssert(state.waitingState == nil) + owsPrecondition(state.waitingState == nil) state.waitingState = .waitingForAllResponses(future) } return promise diff --git a/SignalServiceKit/Notifications/NotificationPresenterImpl.swift b/SignalServiceKit/Notifications/NotificationPresenterImpl.swift index f2039862b9..5e1eaeb3aa 100644 --- a/SignalServiceKit/Notifications/NotificationPresenterImpl.swift +++ b/SignalServiceKit/Notifications/NotificationPresenterImpl.swift @@ -660,7 +660,7 @@ public class NotificationPresenterImpl: NotificationPresenter { guard previewType == .namePreview else { return } - owsAssert(Self.shouldShowActions(for: previewType)) + owsPrecondition(Self.shouldShowActions(for: previewType)) let senderName = contactManager.displayName(for: reaction.reactor, tx: transaction).resolvedValue() diff --git a/SignalServiceKit/OWSAsserts/OWSAsserts.h b/SignalServiceKit/OWSAsserts/OWSAsserts.h index 9d20684beb..212110c73c 100644 --- a/SignalServiceKit/OWSAsserts/OWSAsserts.h +++ b/SignalServiceKit/OWSAsserts/OWSAsserts.h @@ -89,14 +89,14 @@ NS_ASSUME_NONNULL_BEGIN #endif // Like OWSAssertDebug, but will fail in production, terminating the app -#define OWSAssert(X) \ +#define OWSPrecondition(X) \ do { \ if (!(X)) { \ OWSFail(@"Assertion failed: %s", CONVERT_EXPR_TO_STRING(X)); \ } \ } while (NO) -#define OWSCAssert(X) \ +#define OWSCPrecondition(X) \ do { \ if (!(X)) { \ OWSCFail(@"Assertion failed: %s", CONVERT_EXPR_TO_STRING(X)); \ @@ -156,19 +156,19 @@ __attribute__((annotate("returns_localized_nsstring"))) static inline NSString * #define ows_add_overflow(a, b, resultRef) \ do { \ BOOL _didOverflow = __builtin_add_overflow(a, b, resultRef); \ - OWSAssert(!_didOverflow); \ + OWSPrecondition(!_didOverflow); \ } while (NO) #define ows_sub_overflow(a, b, resultRef) \ do { \ BOOL _didOverflow = __builtin_sub_overflow(a, b, resultRef); \ - OWSAssert(!_didOverflow); \ + OWSPrecondition(!_didOverflow); \ } while (NO) #define ows_mul_overflow(a, b, resultRef) \ do { \ BOOL _didOverflow = __builtin_mul_overflow(a, b, resultRef); \ - OWSAssert(!_didOverflow); \ + OWSPrecondition(!_didOverflow); \ } while (NO) NS_ASSUME_NONNULL_END diff --git a/SignalServiceKit/OWSAsserts/OWSSwiftUtils.swift b/SignalServiceKit/OWSAsserts/OWSSwiftUtils.swift index d17207b5c9..5b4cce15d5 100644 --- a/SignalServiceKit/OWSAsserts/OWSSwiftUtils.swift +++ b/SignalServiceKit/OWSAsserts/OWSSwiftUtils.swift @@ -76,15 +76,18 @@ public func owsAssertDebug( } } +/// Like `Swift.precondition(_:)`, this will trap if `condition` evaluates to +/// `false`. Also performs additional logging before terminating the process. +/// See `owsFail(_:)` for more information about logging. @inlinable -public func owsAssert( - _ condition: Bool, +public func owsPrecondition( + _ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = String(), file: String = #fileID, function: String = #function, line: Int = #line ) { - if !condition { + if !condition() { let message: String = message() owsFail(message.isEmpty ? "Assertion failed." : message, file: file, function: function, line: line) } diff --git a/SignalServiceKit/Randomness/Randomness.m b/SignalServiceKit/Randomness/Randomness.m index ddd9fa5b47..c289dd0c46 100644 --- a/SignalServiceKit/Randomness/Randomness.m +++ b/SignalServiceKit/Randomness/Randomness.m @@ -22,8 +22,8 @@ NS_ASSUME_NONNULL_BEGIN } NSData *copy = [randomBytes copy]; - OWSAssert(copy != nil); - OWSAssert(copy.length == numberBytes); + OWSPrecondition(copy != nil); + OWSPrecondition(copy.length == numberBytes); return copy; } diff --git a/SignalServiceKit/SCKExceptionWrapper/SCKExceptionWrapper.m b/SignalServiceKit/SCKExceptionWrapper/SCKExceptionWrapper.m index 902c33922b..0b0508f81c 100644 --- a/SignalServiceKit/SCKExceptionWrapper/SCKExceptionWrapper.m +++ b/SignalServiceKit/SCKExceptionWrapper/SCKExceptionWrapper.m @@ -40,7 +40,7 @@ void SCKRaiseIfExceptionWrapperError(NSError *_Nullable error) if (error && [error.domain isEqualToString:SCKExceptionWrapperErrorDomain] && error.code == SCKExceptionWrapperErrorThrown) { NSException *_Nullable exception = error.userInfo[SCKExceptionWrapperUnderlyingExceptionKey]; - OWSCAssert(exception); + OWSCPrecondition(exception); @throw exception; } } diff --git a/SignalServiceKit/SSKEnvironment.swift b/SignalServiceKit/SSKEnvironment.swift index 82d4ab1eb4..c8f7a6266b 100644 --- a/SignalServiceKit/SSKEnvironment.swift +++ b/SignalServiceKit/SSKEnvironment.swift @@ -15,7 +15,7 @@ public class SSKEnvironment: NSObject { public static var shared: SSKEnvironment { _shared! } public static func setShared(_ env: SSKEnvironment, isRunningTests: Bool) { - owsAssert(_shared == nil || isRunningTests) + owsPrecondition(_shared == nil || isRunningTests) _shared = env } diff --git a/SignalServiceKit/Security/OWSHTTPSecurityPolicy.m b/SignalServiceKit/Security/OWSHTTPSecurityPolicy.m index 0f29ec8cdb..b0193dea80 100644 --- a/SignalServiceKit/Security/OWSHTTPSecurityPolicy.m +++ b/SignalServiceKit/Security/OWSHTTPSecurityPolicy.m @@ -45,7 +45,7 @@ NS_ASSUME_NONNULL_BEGIN } NSData *data = [NSData dataWithContentsOfFile:path]; - OWSAssert(data.length > 0); + OWSPrecondition(data.length > 0); return data; } @@ -62,7 +62,7 @@ NS_ASSUME_NONNULL_BEGIN { NSData *certificateData = [self dataFromCertificateFileForService:service]; SecCertificateRef certRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certificateData)); - OWSAssert(certRef); + OWSPrecondition(certRef); return certRef; } diff --git a/SignalServiceKit/Storage/AxolotlStore/Model/LegacyChainKey.m b/SignalServiceKit/Storage/AxolotlStore/Model/LegacyChainKey.m index e239a9d101..3fba3b2cd9 100644 --- a/SignalServiceKit/Storage/AxolotlStore/Model/LegacyChainKey.m +++ b/SignalServiceKit/Storage/AxolotlStore/Model/LegacyChainKey.m @@ -34,8 +34,8 @@ static NSString *const kCoderIndex = @"kCoderIndex"; - (instancetype)initWithData:(NSData *)chainKey index:(int)index { - OWSAssert(chainKey.length == 32); - OWSAssert(index >= 0); + OWSPrecondition(chainKey.length == 32); + OWSPrecondition(index >= 0); self = [super init]; diff --git a/SignalServiceKit/Storage/AxolotlStore/Model/LegacyMessageKeys.m b/SignalServiceKit/Storage/AxolotlStore/Model/LegacyMessageKeys.m index 99950206f9..5ed4ce50d6 100644 --- a/SignalServiceKit/Storage/AxolotlStore/Model/LegacyMessageKeys.m +++ b/SignalServiceKit/Storage/AxolotlStore/Model/LegacyMessageKeys.m @@ -39,9 +39,9 @@ static NSString *const kCoderMessageKeysIndex = @"kCoderMessageKeysIndex"; - (instancetype)initWithCipherKey:(NSData *)cipherKey macKey:(NSData *)macKey iv:(NSData *)data index:(int)index { - OWSAssert(cipherKey); - OWSAssert(macKey); - OWSAssert(data); + OWSPrecondition(cipherKey); + OWSPrecondition(macKey); + OWSPrecondition(data); self = [super init]; diff --git a/SignalServiceKit/Storage/AxolotlStore/Model/LegacyReceivingChain.m b/SignalServiceKit/Storage/AxolotlStore/Model/LegacyReceivingChain.m index a8db10b204..fe31fa40ab 100644 --- a/SignalServiceKit/Storage/AxolotlStore/Model/LegacyReceivingChain.m +++ b/SignalServiceKit/Storage/AxolotlStore/Model/LegacyReceivingChain.m @@ -42,8 +42,8 @@ static NSString *const kCoderMessageKeys = @"kCoderMessageKeys"; - (instancetype)initWithChainKey:(LegacyChainKey *)chainKey senderRatchetKey:(NSData *)senderRatchet { - OWSAssert(chainKey); - OWSAssert(senderRatchet); + OWSPrecondition(chainKey); + OWSPrecondition(senderRatchet); self = [super init]; diff --git a/SignalServiceKit/Storage/AxolotlStore/Model/LegacyRootKey.m b/SignalServiceKit/Storage/AxolotlStore/Model/LegacyRootKey.m index 156ac76bf8..24a7f3923a 100644 --- a/SignalServiceKit/Storage/AxolotlStore/Model/LegacyRootKey.m +++ b/SignalServiceKit/Storage/AxolotlStore/Model/LegacyRootKey.m @@ -35,7 +35,7 @@ static NSString *const kCoderData = @"kCoderData"; { self = [super init]; - OWSAssert(data.length == 32); + OWSPrecondition(data.length == 32); if (self) { _keyData = data; diff --git a/SignalServiceKit/Storage/AxolotlStore/Model/LegacySendingChain.m b/SignalServiceKit/Storage/AxolotlStore/Model/LegacySendingChain.m index 23c8e286c7..827a26ff17 100644 --- a/SignalServiceKit/Storage/AxolotlStore/Model/LegacySendingChain.m +++ b/SignalServiceKit/Storage/AxolotlStore/Model/LegacySendingChain.m @@ -41,8 +41,8 @@ static NSString *const kCoderSenderRatchet = @"kCoderSenderRatchet"; { self = [super init]; - OWSAssert(chainKey.key.length == 32); - OWSAssert(keyPair); + OWSPrecondition(chainKey.key.length == 32); + OWSPrecondition(keyPair); if (self) { _chainKey = chainKey; diff --git a/SignalServiceKit/Storage/AxolotlStore/Model/LegacySessionState.m b/SignalServiceKit/Storage/AxolotlStore/Model/LegacySessionState.m index 60747367b0..057c811725 100644 --- a/SignalServiceKit/Storage/AxolotlStore/Model/LegacySessionState.m +++ b/SignalServiceKit/Storage/AxolotlStore/Model/LegacySessionState.m @@ -22,7 +22,7 @@ static NSString *const kCoderBaseKey = @"kCoderBaseKey"; - (instancetype)initWithBaseKey:(NSData *)baseKey preKeyId:(int)preKeyId signedPreKeyId:(int)signedPrekeyId { - OWSAssert(baseKey); + OWSPrecondition(baseKey); self = [super init]; if (self) { @@ -143,8 +143,8 @@ static NSString *const kCoderPendingPrekey = @"kCoderPendingPrekey"; - (void)setSenderChain:(ECKeyPair *)senderRatchetKeyPair chainKey:(LegacyChainKey *)chainKey { - OWSAssert(senderRatchetKeyPair); - OWSAssert(chainKey); + OWSPrecondition(senderRatchetKeyPair); + OWSPrecondition(chainKey); self.sendingChain = [[LegacySendingChain alloc] initWithChainKey:chainKey senderRatchetKeyPair:senderRatchetKeyPair]; @@ -157,7 +157,7 @@ static NSString *const kCoderPendingPrekey = @"kCoderPendingPrekey"; - (void)setUnacknowledgedPreKeyMessage:(int)preKeyId signedPreKey:(int)signedPreKeyId baseKey:(NSData *)baseKey { - OWSAssert(baseKey); + OWSPrecondition(baseKey); LegacyPendingPreKey *pendingPreKey = [[LegacyPendingPreKey alloc] initWithBaseKey:baseKey preKeyId:preKeyId diff --git a/SignalServiceKit/Storage/AxolotlStore/Model/PreKeyRecord.m b/SignalServiceKit/Storage/AxolotlStore/Model/PreKeyRecord.m index 2b3e22b341..98c8fa94b1 100644 --- a/SignalServiceKit/Storage/AxolotlStore/Model/PreKeyRecord.m +++ b/SignalServiceKit/Storage/AxolotlStore/Model/PreKeyRecord.m @@ -21,7 +21,7 @@ static NSString *const kCoderCreatedAt = @"kCoderCreatedAt"; - (instancetype)initWithId:(int)identifier keyPair:(ECKeyPair *)keyPair createdAt:(NSDate *)createdAt { - OWSAssert(keyPair); + OWSPrecondition(keyPair); self = [super init]; diff --git a/SignalServiceKit/Storage/AxolotlStore/SSKSignedPreKeyStore.m b/SignalServiceKit/Storage/AxolotlStore/SSKSignedPreKeyStore.m index 60fc9b5155..067ac7d5e8 100644 --- a/SignalServiceKit/Storage/AxolotlStore/SSKSignedPreKeyStore.m +++ b/SignalServiceKit/Storage/AxolotlStore/SSKSignedPreKeyStore.m @@ -90,7 +90,7 @@ NSString *const kLastPreKeyRotationDate = @"lastKeyRotationDate"; - (SignedPreKeyRecord *)generateRandomSignedRecord { ECKeyPair *_Nullable identityKeyPair = [OWSIdentityManagerObjCBridge identityKeyPairForIdentity:_identity]; - OWSAssert(identityKeyPair); + OWSPrecondition(identityKeyPair); return [SSKSignedPreKeyStore generateSignedPreKeyWithSignedBy:identityKeyPair]; } diff --git a/SignalServiceKit/Storage/Database/DatabaseRecovery.swift b/SignalServiceKit/Storage/Database/DatabaseRecovery.swift index d9e2ffbd99..c08c56a8c0 100644 --- a/SignalServiceKit/Storage/Database/DatabaseRecovery.swift +++ b/SignalServiceKit/Storage/Database/DatabaseRecovery.swift @@ -481,7 +481,7 @@ public extension DatabaseRecovery { from: SDSDatabaseStorage, to: SDSDatabaseStorage ) -> TableCopyResult { - owsAssert(SqliteUtil.isSafe(sqlName: tableName)) + owsPrecondition(SqliteUtil.isSafe(sqlName: tableName)) do { return try from.readThrows { fromTransaction -> TableCopyResult in @@ -554,7 +554,7 @@ public extension DatabaseRecovery { } private static func getColumnNames(db: Database, tableName: String) throws -> [String] { - owsAssert(SqliteUtil.isSafe(sqlName: tableName)) + owsPrecondition(SqliteUtil.isSafe(sqlName: tableName)) var result = [String]() let cursor = try Row.fetchCursor(db, sql: "PRAGMA table_info(\(tableName))") @@ -568,9 +568,9 @@ public extension DatabaseRecovery { } private static func insertSql(tableName: String, columnNames: [String]) -> String { - owsAssert(SqliteUtil.isSafe(sqlName: tableName)) + owsPrecondition(SqliteUtil.isSafe(sqlName: tableName)) for columnName in columnNames { - owsAssert(SqliteUtil.isSafe(sqlName: columnName)) + owsPrecondition(SqliteUtil.isSafe(sqlName: columnName)) } let columnNamesSql = columnNames.joined(separator: ", ") diff --git a/SignalServiceKit/Storage/Database/GRDBDatabaseStorageAdapter.swift b/SignalServiceKit/Storage/Database/GRDBDatabaseStorageAdapter.swift index 3cb8d2f2bd..68a7c294e5 100644 --- a/SignalServiceKit/Storage/Database/GRDBDatabaseStorageAdapter.swift +++ b/SignalServiceKit/Storage/Database/GRDBDatabaseStorageAdapter.swift @@ -327,8 +327,8 @@ extension GRDBDatabaseStorageAdapter { // We're already in an unexpected (but recoverable) state. However if the currently active transfer // path is a file or a non-empty directory, we're too close to losing data and we should fail. if FileManager.default.fileExists(atPath: transferDatabaseDir.path, isDirectory: &isDirectory) { - owsAssert(isDirectory.boolValue) - owsAssert(try! FileManager.default.contentsOfDirectory(atPath: transferDatabaseDir.path).isEmpty) + owsPrecondition(isDirectory.boolValue) + owsPrecondition(try! FileManager.default.contentsOfDirectory(atPath: transferDatabaseDir.path).isEmpty) } OWSFileSystem.deleteFileIfExists(transferDatabaseDir.path) clearTransferDirectory() @@ -346,7 +346,7 @@ extension GRDBDatabaseStorageAdapter { } public static func promoteTransferDirectoryToPrimary() { - owsAssert(CurrentAppContext().isMainApp, "Only the main app can swap databases") + owsPrecondition(CurrentAppContext().isMainApp, "Only the main app can swap databases") // Ordering matters here. We should be able to crash and recover without issue // A prior run may have already performed the swap but crashed, so we should not expect a transfer folder @@ -904,7 +904,7 @@ public struct GRDBKeyFetcher { /// - Note: Will fatally assert if not running in a debug or test build. /// - Returns: The key data, if available. public func debugOnly_keyData() -> Data? { - owsAssert(DebugFlags.internalSettings) + owsPrecondition(DebugFlags.internalSettings) return try? fetchData() } } diff --git a/SignalServiceKit/Storage/Database/SDSKeyValueStore/SDSKeyValueStore+ObjC.m b/SignalServiceKit/Storage/Database/SDSKeyValueStore/SDSKeyValueStore+ObjC.m index 0440a01200..2185c9eaa4 100644 --- a/SignalServiceKit/Storage/Database/SDSKeyValueStore/SDSKeyValueStore+ObjC.m +++ b/SignalServiceKit/Storage/Database/SDSKeyValueStore/SDSKeyValueStore+ObjC.m @@ -34,7 +34,7 @@ NS_ASSUME_NONNULL_BEGIN id _Nullable value = [self.keyValueStore getObjectForKey:key transaction:transaction]; - OWSAssert(!value || [value isKindOfClass:klass]); + OWSPrecondition(!value || [value isKindOfClass:klass]); return value; } @@ -44,7 +44,7 @@ NS_ASSUME_NONNULL_BEGIN transaction:(SDSAnyWriteTransaction *)transaction { OWSAssertDebug(key.length > 0); - OWSAssert([object isKindOfClass:klass]); + OWSPrecondition([object isKindOfClass:klass]); [self.keyValueStore setObject:object key:key transaction:transaction]; } diff --git a/SignalServiceKit/Subscriptions/Paypal+WebAuthentication.swift b/SignalServiceKit/Subscriptions/Paypal+WebAuthentication.swift index 207c883b77..a86612924a 100644 --- a/SignalServiceKit/Subscriptions/Paypal+WebAuthentication.swift +++ b/SignalServiceKit/Subscriptions/Paypal+WebAuthentication.swift @@ -26,7 +26,7 @@ public extension Paypal { ) session.presentationContextProvider = presentationContext - owsAssert( + owsPrecondition( session.start(), "[Donations] Failed to start PayPal authentication session. Was it set up correctly?" ) diff --git a/SignalServiceKit/Subscriptions/ReceiptCredentialRequestError.swift b/SignalServiceKit/Subscriptions/ReceiptCredentialRequestError.swift index ea0ce17d52..e5414d4cdc 100644 --- a/SignalServiceKit/Subscriptions/ReceiptCredentialRequestError.swift +++ b/SignalServiceKit/Subscriptions/ReceiptCredentialRequestError.swift @@ -47,7 +47,7 @@ public struct ReceiptCredentialRequestError: Codable, Equatable { amount: FiatMoney, paymentMethod: DonationPaymentMethod ) { - owsAssert( + owsPrecondition( chargeFailureCodeIfPaymentFailed == nil || errorCode == .paymentFailed, "Charge failure must only be populated if the error code is payment failed!" ) diff --git a/SignalServiceKit/Subscriptions/SubscriptionManagerImpl.swift b/SignalServiceKit/Subscriptions/SubscriptionManagerImpl.swift index 8a62edc6b0..f6cf37e178 100644 --- a/SignalServiceKit/Subscriptions/SubscriptionManagerImpl.swift +++ b/SignalServiceKit/Subscriptions/SubscriptionManagerImpl.swift @@ -642,7 +642,7 @@ public class SubscriptionManagerImpl: NSObject { errorCode: ReceiptCredentialRequestError.ErrorCode, chargeFailureCodeIfPaymentFailed: String? = nil ) { - owsAssert( + owsPrecondition( chargeFailureCodeIfPaymentFailed == nil || errorCode == .paymentFailed, "Must only provide a charge failure if payment failed!" ) diff --git a/SignalServiceKit/TSConstants.swift b/SignalServiceKit/TSConstants.swift index 1ef888600e..d1ed2d3f56 100644 --- a/SignalServiceKit/TSConstants.swift +++ b/SignalServiceKit/TSConstants.swift @@ -147,7 +147,7 @@ public struct MrEnclave: Equatable { // This is a constant -- it should never fail to parse. self.dataValue = Data.data(fromHex: self.stringValue)! // All of our MrEnclave values are currently 32 bytes. - owsAssert(self.dataValue.count == 32) + owsPrecondition(self.dataValue.count == 32) } public static func == (lhs: Self, rhs: Self) -> Bool { diff --git a/SignalServiceKit/TestUtils/MockSSKEnvironment.swift b/SignalServiceKit/TestUtils/MockSSKEnvironment.swift index e0a7c359db..04ff8cbede 100644 --- a/SignalServiceKit/TestUtils/MockSSKEnvironment.swift +++ b/SignalServiceKit/TestUtils/MockSSKEnvironment.swift @@ -54,7 +54,7 @@ public class MockSSKEnvironment: NSObject { backgroundScheduler: SyncScheduler(), mainScheduler: SyncScheduler() ) - owsAssert(finalContinuation.isSealed) + owsPrecondition(finalContinuation.isSealed) } @objc diff --git a/SignalServiceKit/TestUtils/TestProtocolRunner.swift b/SignalServiceKit/TestUtils/TestProtocolRunner.swift index 604ae5a8d1..07c19b96eb 100644 --- a/SignalServiceKit/TestUtils/TestProtocolRunner.swift +++ b/SignalServiceKit/TestUtils/TestProtocolRunner.swift @@ -116,7 +116,7 @@ public struct TestProtocolRunner { recipientClient: TestSignalClient, sender: ProtocolAddress, context: StoreContext) throws -> Data { - owsAssert(cipherMessage.messageType == .whisper, "only bare SignalMessages are supported") + owsPrecondition(cipherMessage.messageType == .whisper, "only bare SignalMessages are supported") let message = try SignalMessage(bytes: cipherMessage.serialize()) return Data(try signalDecrypt(message: message, from: sender, diff --git a/SignalServiceKit/Util/Currency.swift b/SignalServiceKit/Util/Currency.swift index 12d1762ee6..10e546531a 100644 --- a/SignalServiceKit/Util/Currency.swift +++ b/SignalServiceKit/Util/Currency.swift @@ -37,7 +37,7 @@ public struct Currency { shouldSort: Bool ) -> [Info] { #if TESTABLE_BUILD - owsAssert(Array(codes).count == Set(codes).count) + owsPrecondition(Array(codes).count == Set(codes).count) #endif var infos = codes.compactMap { Info(code: $0, ignoreMissingName: ignoreMissingNames) } if shouldSort { infos.sort { $0.name < $1.name } } diff --git a/SignalServiceKit/Util/ImageMetadata/PngChunker.swift b/SignalServiceKit/Util/ImageMetadata/PngChunker.swift index 5fbc05d517..cfa357f4d9 100644 --- a/SignalServiceKit/Util/ImageMetadata/PngChunker.swift +++ b/SignalServiceKit/Util/ImageMetadata/PngChunker.swift @@ -183,7 +183,7 @@ public class PngChunker { extension Data { func asPngUInt32() throws -> UInt32 { - owsAssert(count == 4) + owsPrecondition(count == 4) var result: UInt32 = 0 for (i, byte) in reversed().enumerated() { result += UInt32(byte) * (1 << (8 * i)) diff --git a/SignalServiceKit/Util/ModelReadCache.swift b/SignalServiceKit/Util/ModelReadCache.swift index 8d0b10a870..7239dc9bf3 100644 --- a/SignalServiceKit/Util/ModelReadCache.swift +++ b/SignalServiceKit/Util/ModelReadCache.swift @@ -313,7 +313,7 @@ class ModelReadCache: Dependencies, Ca func add(lease: ModelReadCacheSizeLease) { performSync { // It's a bug to add an already-added lease. - owsAssert(!leases.contains(lease)) + owsPrecondition(!leases.contains(lease)) leases.add(lease) updateMaxSize() diff --git a/SignalServiceKit/Util/NSData+OWS.m b/SignalServiceKit/Util/NSData+OWS.m index 9d4bf4e0f2..d32a9da6e5 100644 --- a/SignalServiceKit/Util/NSData+OWS.m +++ b/SignalServiceKit/Util/NSData+OWS.m @@ -11,7 +11,7 @@ NS_ASSUME_NONNULL_BEGIN + (NSData *)join:(NSArray *)datas { - OWSAssert(datas); + OWSPrecondition(datas); NSMutableData *result = [NSMutableData new]; for (NSData *data in datas) { diff --git a/SignalServiceKit/Util/OWSFileSystem.m b/SignalServiceKit/Util/OWSFileSystem.m index 43adf036eb..305bacc0ef 100644 --- a/SignalServiceKit/Util/OWSFileSystem.m +++ b/SignalServiceKit/Util/OWSFileSystem.m @@ -100,7 +100,7 @@ NS_ASSUME_NONNULL_BEGIN static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); - OWSAssert(paths.count >= 1); + OWSPrecondition(paths.count >= 1); result = paths[0]; }); return result; @@ -267,7 +267,7 @@ NSString *OWSTemporaryDirectory(void) NSString *dirName = [NSString stringWithFormat:@"ows_temp_%@", NSUUID.UUID.UUIDString]; dirPath = [NSTemporaryDirectory() stringByAppendingPathComponent:dirName]; BOOL success = [OWSFileSystem ensureDirectoryExists:dirPath fileProtectionType:NSFileProtectionComplete]; - OWSCAssert(success); + OWSCPrecondition(success); }); return dirPath; } @@ -277,7 +277,7 @@ NSString *OWSTemporaryDirectoryAccessibleAfterFirstAuth(void) NSString *dirPath = NSTemporaryDirectory(); BOOL success = [OWSFileSystem ensureDirectoryExists:dirPath fileProtectionType:NSFileProtectionCompleteUntilFirstUserAuthentication]; - OWSCAssert(success); + OWSCPrecondition(success); return dirPath; } diff --git a/SignalServiceKit/Util/OrderedDictionary.swift b/SignalServiceKit/Util/OrderedDictionary.swift index b5cef1cff3..4396b83e34 100644 --- a/SignalServiceKit/Util/OrderedDictionary.swift +++ b/SignalServiceKit/Util/OrderedDictionary.swift @@ -30,7 +30,7 @@ public struct OrderedDictionary { } public mutating func insert(key: KeyType, at index: Int, value: ValueType) { - owsAssert(keyValueMap[key] == nil, "Key already in dictionary: \(key)") + owsPrecondition(keyValueMap[key] == nil, "Key already in dictionary: \(key)") owsAssertDebug(!orderedKeys.contains(key), "Unexpected duplicate key in key list: \(key)") keyValueMap[key] = value @@ -125,7 +125,7 @@ extension OrderedDictionary: RandomAccessCollection { public var endIndex: Int { self.orderedKeys.count } public subscript(position: Int) -> (key: KeyType, value: ValueType) { - owsAssert(indices.contains(position)) + owsPrecondition(indices.contains(position)) let key = orderedKeys[position] guard let value = keyValueMap[key] else { owsFail("Missing value") diff --git a/SignalServiceKit/Util/SqliteUtil.swift b/SignalServiceKit/Util/SqliteUtil.swift index ccdbb13bb5..2d0d73da82 100644 --- a/SignalServiceKit/Util/SqliteUtil.swift +++ b/SignalServiceKit/Util/SqliteUtil.swift @@ -154,7 +154,7 @@ public enum SqliteUtil { ftsTableName: String, compareToExternalContentTable: Bool ) throws -> IntegrityCheckResult { - owsAssert(SqliteUtil.isSafe(sqlName: ftsTableName)) + owsPrecondition(SqliteUtil.isSafe(sqlName: ftsTableName)) let sql: String if compareToExternalContentTable { @@ -187,7 +187,7 @@ public enum SqliteUtil { /// /// [rebuild command]: https://www.sqlite.org/fts5.html#the_rebuild_command public static func rebuild(db: Database, ftsTableName: String) throws { - owsAssert(SqliteUtil.isSafe(sqlName: ftsTableName)) + owsPrecondition(SqliteUtil.isSafe(sqlName: ftsTableName)) try db.execute( sql: "INSERT INTO \(ftsTableName) (\(ftsTableName)) VALUES ('rebuild')" @@ -217,7 +217,7 @@ public enum SqliteUtil { ) throws -> MergeResult { let totalChangesBefore = db.totalChangesCount - owsAssert(SqliteUtil.isSafe(sqlName: ftsTableName)) + owsPrecondition(SqliteUtil.isSafe(sqlName: ftsTableName)) try db.execute( sql: "INSERT INTO \(ftsTableName) (\(ftsTableName), rank) VALUES ('merge', ?)", arguments: [isFirstBatch ? -numberOfPages : numberOfPages] diff --git a/SignalServiceKit/tests/Account/PreKeys/SignedPreKeyDeletionTests.swift b/SignalServiceKit/tests/Account/PreKeys/SignedPreKeyDeletionTests.swift index 50c0d9b901..f93a648c21 100644 --- a/SignalServiceKit/tests/Account/PreKeys/SignedPreKeyDeletionTests.swift +++ b/SignalServiceKit/tests/Account/PreKeys/SignedPreKeyDeletionTests.swift @@ -18,7 +18,7 @@ final class SignedPreKeyDeletionTests: SSKBaseTest { var justUploadedRecord: SignedPreKeyRecord! for daysAgo in stride(from: 0, through: maxDaysAgo, by: 5) { let secondsAgo: TimeInterval = Double(daysAgo - maxDaysAgo) * kDayInterval - owsAssert(secondsAgo <= 0, "Time in past must be negative!") + owsPrecondition(secondsAgo <= 0, "Time in past must be negative!") let record = SignedPreKeyRecord( id: Int32(daysAgo), @@ -62,7 +62,7 @@ final class SignedPreKeyDeletionTests: SSKBaseTest { // All these keys will be considered "old", since they were created // more than 30 days ago. let secondsAgo: TimeInterval = Double(idx - 40) * kDayInterval - owsAssert(secondsAgo <= 0, "Time in past must be negative!") + owsPrecondition(secondsAgo <= 0, "Time in past must be negative!") let record = SignedPreKeyRecord( id: Int32(idx), diff --git a/SignalServiceKit/tests/Messages/DisappearingMessageFinderTest.swift b/SignalServiceKit/tests/Messages/DisappearingMessageFinderTest.swift index 9803fdec6b..9f27fcb69e 100644 --- a/SignalServiceKit/tests/Messages/DisappearingMessageFinderTest.swift +++ b/SignalServiceKit/tests/Messages/DisappearingMessageFinderTest.swift @@ -38,7 +38,7 @@ final class DisappearingMessageFinderTest: SSKBaseTest { write { transaction -> TSIncomingMessage in // It only makes sense to "mark as read" if expiration hasn't started, // since we don't start expiration for unread incoming messages. - owsAssert(!markAsRead || expireStartedAt == 0) + owsPrecondition(!markAsRead || expireStartedAt == 0) let thread = self.thread(with: transaction) diff --git a/SignalServiceKit/tests/Storage/Database/DatabaseRecoveryTest.swift b/SignalServiceKit/tests/Storage/Database/DatabaseRecoveryTest.swift index 430362f6c0..39ebb0728c 100644 --- a/SignalServiceKit/tests/Storage/Database/DatabaseRecoveryTest.swift +++ b/SignalServiceKit/tests/Storage/Database/DatabaseRecoveryTest.swift @@ -371,7 +371,7 @@ final class DatabaseRecoveryTest: SSKBaseTest { let db = transaction.unwrapGrdbRead.database let sql = "SELECT name FROM sqlite_schema WHERE type IS 'table'" let allTableNames = Set((try? String.fetchAll(db, sql: sql)) ?? []) - owsAssert(!allTableNames.isEmpty, "No tables were found!") + owsPrecondition(!allTableNames.isEmpty, "No tables were found!") let tableNamesToSkip: Set = ["grdb_migrations", "sqlite_sequence"] return allTableNames.filter { tableName in diff --git a/SignalShareExtension/ShareViewController.swift b/SignalShareExtension/ShareViewController.swift index f5c6511d8f..609ae5fc00 100644 --- a/SignalShareExtension/ShareViewController.swift +++ b/SignalShareExtension/ShareViewController.swift @@ -207,7 +207,7 @@ public class ShareViewController: UIViewController, ShareViewDelegate, SAEFailed private func setAppIsReady() { Logger.debug("") AssertIsOnMainThread() - owsAssert(!AppReadiness.isAppReady) + owsPrecondition(!AppReadiness.isAppReady) // We don't need to use LaunchJobs in the SAE. diff --git a/SignalUI/ContactSharing/ContactShareField.swift b/SignalUI/ContactSharing/ContactShareField.swift index ad41ba9f82..ec882fb769 100644 --- a/SignalUI/ContactSharing/ContactShareField.swift +++ b/SignalUI/ContactSharing/ContactShareField.swift @@ -38,7 +38,7 @@ class ContactShareFieldBase: ContactShareFiel class ContactSharePhoneNumber: ContactShareFieldBase { override func applyToContact(contact: ContactShareDraft) { - owsAssert(isIncluded) + owsPrecondition(isIncluded) var values = [OWSContactPhoneNumber]() values += contact.phoneNumbers @@ -50,7 +50,7 @@ class ContactSharePhoneNumber: ContactShareFieldBase { class ContactShareEmail: ContactShareFieldBase { override func applyToContact(contact: ContactShareDraft) { - owsAssert(isIncluded) + owsPrecondition(isIncluded) var values = [OWSContactEmail]() values += contact.emails @@ -62,7 +62,7 @@ class ContactShareEmail: ContactShareFieldBase { class ContactShareAddress: ContactShareFieldBase { override func applyToContact(contact: ContactShareDraft) { - owsAssert(isIncluded) + owsPrecondition(isIncluded) var values = [OWSContactAddress]() values += contact.addresses @@ -94,7 +94,7 @@ class OWSContactAvatar: NSObject, OWSContactField { class ContactShareAvatarField: ContactShareFieldBase { override func applyToContact(contact: ContactShareDraft) { - owsAssert(isIncluded) + owsPrecondition(isIncluded) contact.avatarImageData = value.avatarData contact.existingAvatarAttachment = value.existingAttachment diff --git a/SignalUI/ContactSharing/ContactShareViewController.swift b/SignalUI/ContactSharing/ContactShareViewController.swift index 9f0098ce25..00e666739c 100644 --- a/SignalUI/ContactSharing/ContactShareViewController.swift +++ b/SignalUI/ContactSharing/ContactShareViewController.swift @@ -201,7 +201,7 @@ public class ContactShareViewController: OWSTableViewController2 { } let filteredContactShare = filteredContactShare() - owsAssert(filteredContactShare.ows_isValid) + owsPrecondition(filteredContactShare.ows_isValid) shareDelegate.contactShareViewController(self, didApproveContactShare: filteredContactShare) } diff --git a/SignalUI/RecipientPickers/DeleteSystemContactViewController.swift b/SignalUI/RecipientPickers/DeleteSystemContactViewController.swift index 301790d032..da743d7556 100644 --- a/SignalUI/RecipientPickers/DeleteSystemContactViewController.swift +++ b/SignalUI/RecipientPickers/DeleteSystemContactViewController.swift @@ -74,7 +74,7 @@ class DeleteSystemContactViewController: OWSTableViewController2 { // This screen is for primary devices only. If a non primary // manages to get here bad things could happen. - owsAssert(DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice) + owsPrecondition(DependenciesBridge.shared.tsAccountManager.registrationStateWithMaybeSneakyTransaction.isRegisteredPrimaryDevice) self.navigationItem.leftBarButtonItem = .cancelButton(dismissingFrom: self) }