private void handleUntrustedIdentityMessage(
      MasterSecret masterSecret, TextSecureEnvelope envelope, Optional<Long> smsMessageId) {
    try {
      EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context);
      Recipients recipients =
          RecipientFactory.getRecipientsFromString(context, envelope.getSource(), false);
      long recipientId = recipients.getPrimaryRecipient().getRecipientId();
      PreKeyWhisperMessage whisperMessage = new PreKeyWhisperMessage(envelope.getMessage());
      IdentityKey identityKey = whisperMessage.getIdentityKey();
      String encoded = Base64.encodeBytes(envelope.getMessage());
      IncomingTextMessage textMessage =
          new IncomingTextMessage(
              envelope.getSource(),
              envelope.getSourceDevice(),
              envelope.getTimestamp(),
              encoded,
              Optional.<TextSecureGroup>absent());

      if (!smsMessageId.isPresent()) {
        IncomingPreKeyBundleMessage bundleMessage =
            new IncomingPreKeyBundleMessage(textMessage, encoded);
        Pair<Long, Long> messageAndThreadId =
            database.insertMessageInbox(masterSecret, bundleMessage);

        database.setMismatchedIdentity(messageAndThreadId.first, recipientId, identityKey);
        MessageNotifier.updateNotification(context, masterSecret, messageAndThreadId.second);
      } else {
        database.updateMessageBody(masterSecret, smsMessageId.get(), encoded);
        database.markAsPreKeyBundle(smsMessageId.get());
        database.setMismatchedIdentity(smsMessageId.get(), recipientId, identityKey);
      }
    } catch (InvalidMessageException | InvalidVersionException e) {
      throw new AssertionError(e);
    }
  }