AxolotlService.java

   1package eu.siacs.conversations.crypto.axolotl;
   2
   3import android.support.annotation.NonNull;
   4import android.support.annotation.Nullable;
   5import android.util.Log;
   6
   7import org.bouncycastle.jce.provider.BouncyCastleProvider;
   8import org.whispersystems.libaxolotl.AxolotlAddress;
   9import org.whispersystems.libaxolotl.DuplicateMessageException;
  10import org.whispersystems.libaxolotl.IdentityKey;
  11import org.whispersystems.libaxolotl.IdentityKeyPair;
  12import org.whispersystems.libaxolotl.InvalidKeyException;
  13import org.whispersystems.libaxolotl.InvalidKeyIdException;
  14import org.whispersystems.libaxolotl.InvalidMessageException;
  15import org.whispersystems.libaxolotl.InvalidVersionException;
  16import org.whispersystems.libaxolotl.LegacyMessageException;
  17import org.whispersystems.libaxolotl.NoSessionException;
  18import org.whispersystems.libaxolotl.SessionBuilder;
  19import org.whispersystems.libaxolotl.SessionCipher;
  20import org.whispersystems.libaxolotl.UntrustedIdentityException;
  21import org.whispersystems.libaxolotl.ecc.Curve;
  22import org.whispersystems.libaxolotl.ecc.ECKeyPair;
  23import org.whispersystems.libaxolotl.ecc.ECPublicKey;
  24import org.whispersystems.libaxolotl.protocol.CiphertextMessage;
  25import org.whispersystems.libaxolotl.protocol.PreKeyWhisperMessage;
  26import org.whispersystems.libaxolotl.protocol.WhisperMessage;
  27import org.whispersystems.libaxolotl.state.AxolotlStore;
  28import org.whispersystems.libaxolotl.state.PreKeyBundle;
  29import org.whispersystems.libaxolotl.state.PreKeyRecord;
  30import org.whispersystems.libaxolotl.state.SessionRecord;
  31import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
  32import org.whispersystems.libaxolotl.util.KeyHelper;
  33
  34import java.security.Security;
  35import java.util.Arrays;
  36import java.util.HashMap;
  37import java.util.HashSet;
  38import java.util.List;
  39import java.util.Map;
  40import java.util.Random;
  41import java.util.Set;
  42
  43import eu.siacs.conversations.Config;
  44import eu.siacs.conversations.entities.Account;
  45import eu.siacs.conversations.entities.Contact;
  46import eu.siacs.conversations.entities.Conversation;
  47import eu.siacs.conversations.entities.Message;
  48import eu.siacs.conversations.parser.IqParser;
  49import eu.siacs.conversations.services.XmppConnectionService;
  50import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
  51import eu.siacs.conversations.xml.Element;
  52import eu.siacs.conversations.xmpp.OnIqPacketReceived;
  53import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  54import eu.siacs.conversations.xmpp.jid.Jid;
  55import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  56
  57public class AxolotlService {
  58
  59	public static final String PEP_PREFIX = "eu.siacs.conversations.axolotl";
  60	public static final String PEP_DEVICE_LIST = PEP_PREFIX + ".devicelist";
  61	public static final String PEP_BUNDLES = PEP_PREFIX + ".bundles";
  62
  63	public static final String LOGPREFIX = "AxolotlService";
  64
  65	public static final int NUM_KEYS_TO_PUBLISH = 10;
  66
  67	private final Account account;
  68	private final XmppConnectionService mXmppConnectionService;
  69	private final SQLiteAxolotlStore axolotlStore;
  70	private final SessionMap sessions;
  71	private final Map<Jid, Set<Integer>> deviceIds;
  72	private final Map<String, XmppAxolotlMessage> messageCache;
  73	private final FetchStatusMap fetchStatusMap;
  74	private final SerialSingleThreadExecutor executor;
  75
  76	public static class SQLiteAxolotlStore implements AxolotlStore {
  77
  78		public static final String PREKEY_TABLENAME = "prekeys";
  79		public static final String SIGNED_PREKEY_TABLENAME = "signed_prekeys";
  80		public static final String SESSION_TABLENAME = "sessions";
  81		public static final String IDENTITIES_TABLENAME = "identities";
  82		public static final String ACCOUNT = "account";
  83		public static final String DEVICE_ID = "device_id";
  84		public static final String ID = "id";
  85		public static final String KEY = "key";
  86		public static final String FINGERPRINT = "fingerprint";
  87		public static final String NAME = "name";
  88		public static final String TRUSTED = "trusted";
  89		public static final String OWN = "ownkey";
  90
  91		public static final String JSONKEY_REGISTRATION_ID = "axolotl_reg_id";
  92		public static final String JSONKEY_CURRENT_PREKEY_ID = "axolotl_cur_prekey_id";
  93
  94		private final Account account;
  95		private final XmppConnectionService mXmppConnectionService;
  96
  97		private IdentityKeyPair identityKeyPair;
  98		private int localRegistrationId;
  99		private int currentPreKeyId = 0;
 100
 101		public enum Trust {
 102			UNDECIDED(0),
 103			TRUSTED(1),
 104			UNTRUSTED(2),
 105			COMPROMISED(3);
 106
 107			private static final Map<Integer, Trust> trustsByValue = new HashMap<>();
 108
 109			static {
 110				for (Trust trust : Trust.values()) {
 111					trustsByValue.put(trust.getCode(), trust);
 112				}
 113			}
 114
 115			private final int code;
 116
 117			Trust(int code){
 118				this.code = code;
 119			}
 120
 121			public int getCode() {
 122				return this.code;
 123			}
 124
 125			public String toString() {
 126				switch(this){
 127					case UNDECIDED:
 128						return "Trust undecided";
 129					case TRUSTED:
 130						return "Trusted";
 131					case UNTRUSTED:
 132					default:
 133						return "Untrusted";
 134				}
 135			}
 136
 137			public static Trust fromBoolean(Boolean trusted) {
 138				return trusted?TRUSTED:UNTRUSTED;
 139			}
 140
 141			public static Trust fromCode(int code) {
 142				return trustsByValue.get(code);
 143			}
 144		};
 145
 146		private static IdentityKeyPair generateIdentityKeyPair() {
 147			Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Generating axolotl IdentityKeyPair...");
 148			ECKeyPair identityKeyPairKeys = Curve.generateKeyPair();
 149			IdentityKeyPair ownKey = new IdentityKeyPair(new IdentityKey(identityKeyPairKeys.getPublicKey()),
 150					identityKeyPairKeys.getPrivateKey());
 151			return ownKey;
 152		}
 153
 154		private static int generateRegistrationId() {
 155			Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Generating axolotl registration ID...");
 156			int reg_id = KeyHelper.generateRegistrationId(true);
 157			return reg_id;
 158		}
 159
 160		public SQLiteAxolotlStore(Account account, XmppConnectionService service) {
 161			this.account = account;
 162			this.mXmppConnectionService = service;
 163			this.localRegistrationId = loadRegistrationId();
 164			this.currentPreKeyId = loadCurrentPreKeyId();
 165			for (SignedPreKeyRecord record : loadSignedPreKeys()) {
 166				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Got Axolotl signed prekey record:" + record.getId());
 167			}
 168		}
 169
 170		public int getCurrentPreKeyId() {
 171			return currentPreKeyId;
 172		}
 173
 174		// --------------------------------------
 175		// IdentityKeyStore
 176		// --------------------------------------
 177
 178		private IdentityKeyPair loadIdentityKeyPair() {
 179			String ownName = account.getJid().toBareJid().toString();
 180			IdentityKeyPair ownKey = mXmppConnectionService.databaseBackend.loadOwnIdentityKeyPair(account,
 181					ownName);
 182
 183			if (ownKey != null) {
 184				return ownKey;
 185			} else {
 186				Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Could not retrieve axolotl key for account " + ownName);
 187				ownKey = generateIdentityKeyPair();
 188				mXmppConnectionService.databaseBackend.storeOwnIdentityKeyPair(account, ownName, ownKey);
 189			}
 190			return ownKey;
 191		}
 192
 193		private int loadRegistrationId() {
 194			return loadRegistrationId(false);
 195		}
 196
 197		private int loadRegistrationId(boolean regenerate) {
 198			String regIdString = this.account.getKey(JSONKEY_REGISTRATION_ID);
 199			int reg_id;
 200			if (!regenerate && regIdString != null) {
 201				reg_id = Integer.valueOf(regIdString);
 202			} else {
 203				Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Could not retrieve axolotl registration id for account " + account.getJid());
 204				reg_id = generateRegistrationId();
 205				boolean success = this.account.setKey(JSONKEY_REGISTRATION_ID, Integer.toString(reg_id));
 206				if (success) {
 207					mXmppConnectionService.databaseBackend.updateAccount(account);
 208				} else {
 209					Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Failed to write new key to the database!");
 210				}
 211			}
 212			return reg_id;
 213		}
 214
 215		private int loadCurrentPreKeyId() {
 216			String regIdString = this.account.getKey(JSONKEY_CURRENT_PREKEY_ID);
 217			int reg_id;
 218			if (regIdString != null) {
 219				reg_id = Integer.valueOf(regIdString);
 220			} else {
 221				Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Could not retrieve current prekey id for account " + account.getJid());
 222				reg_id = 0;
 223			}
 224			return reg_id;
 225		}
 226
 227		public void regenerate() {
 228			mXmppConnectionService.databaseBackend.wipeAxolotlDb(account);
 229			account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(0));
 230			identityKeyPair = loadIdentityKeyPair();
 231			localRegistrationId = loadRegistrationId(true);
 232			currentPreKeyId = 0;
 233			mXmppConnectionService.updateAccountUi();
 234		}
 235
 236		/**
 237		 * Get the local client's identity key pair.
 238		 *
 239		 * @return The local client's persistent identity key pair.
 240		 */
 241		@Override
 242		public IdentityKeyPair getIdentityKeyPair() {
 243			if(identityKeyPair == null) {
 244				identityKeyPair = loadIdentityKeyPair();
 245			}
 246			return identityKeyPair;
 247		}
 248
 249		/**
 250		 * Return the local client's registration ID.
 251		 * <p/>
 252		 * Clients should maintain a registration ID, a random number
 253		 * between 1 and 16380 that's generated once at install time.
 254		 *
 255		 * @return the local client's registration ID.
 256		 */
 257		@Override
 258		public int getLocalRegistrationId() {
 259			return localRegistrationId;
 260		}
 261
 262		/**
 263		 * Save a remote client's identity key
 264		 * <p/>
 265		 * Store a remote client's identity key as trusted.
 266		 *
 267		 * @param name        The name of the remote client.
 268		 * @param identityKey The remote client's identity key.
 269		 */
 270		@Override
 271		public void saveIdentity(String name, IdentityKey identityKey) {
 272			if(!mXmppConnectionService.databaseBackend.loadIdentityKeys(account, name).contains(identityKey)) {
 273				mXmppConnectionService.databaseBackend.storeIdentityKey(account, name, identityKey);
 274			}
 275		}
 276
 277		/**
 278		 * Verify a remote client's identity key.
 279		 * <p/>
 280		 * Determine whether a remote client's identity is trusted.  Convention is
 281		 * that the TextSecure protocol is 'trust on first use.'  This means that
 282		 * an identity key is considered 'trusted' if there is no entry for the recipient
 283		 * in the local store, or if it matches the saved key for a recipient in the local
 284		 * store.  Only if it mismatches an entry in the local store is it considered
 285		 * 'untrusted.'
 286		 *
 287		 * @param name        The name of the remote client.
 288		 * @param identityKey The identity key to verify.
 289		 * @return true if trusted, false if untrusted.
 290		 */
 291		@Override
 292		public boolean isTrustedIdentity(String name, IdentityKey identityKey) {
 293			return true;
 294		}
 295
 296		public Trust getFingerprintTrust(String fingerprint) {
 297			return mXmppConnectionService.databaseBackend.isIdentityKeyTrusted(account, fingerprint);
 298		}
 299
 300		public void setFingerprintTrust(String fingerprint, Trust trust) {
 301			mXmppConnectionService.databaseBackend.setIdentityKeyTrust(account, fingerprint, trust);
 302		}
 303
 304		public Set<IdentityKey> getContactUndecidedKeys(String bareJid, Trust trust) {
 305			return mXmppConnectionService.databaseBackend.loadIdentityKeys(account, bareJid, trust);
 306		}
 307
 308		public long getContactNumTrustedKeys(String bareJid) {
 309			return mXmppConnectionService.databaseBackend.numTrustedKeys(account, bareJid);
 310		}
 311
 312		// --------------------------------------
 313		// SessionStore
 314		// --------------------------------------
 315
 316		/**
 317		 * Returns a copy of the {@link SessionRecord} corresponding to the recipientId + deviceId tuple,
 318		 * or a new SessionRecord if one does not currently exist.
 319		 * <p/>
 320		 * It is important that implementations return a copy of the current durable information.  The
 321		 * returned SessionRecord may be modified, but those changes should not have an effect on the
 322		 * durable session state (what is returned by subsequent calls to this method) without the
 323		 * store method being called here first.
 324		 *
 325		 * @param address The name and device ID of the remote client.
 326		 * @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple, or
 327		 * a new SessionRecord if one does not currently exist.
 328		 */
 329		@Override
 330		public SessionRecord loadSession(AxolotlAddress address) {
 331			SessionRecord session = mXmppConnectionService.databaseBackend.loadSession(this.account, address);
 332			return (session != null) ? session : new SessionRecord();
 333		}
 334
 335		/**
 336		 * Returns all known devices with active sessions for a recipient
 337		 *
 338		 * @param name the name of the client.
 339		 * @return all known sub-devices with active sessions.
 340		 */
 341		@Override
 342		public List<Integer> getSubDeviceSessions(String name) {
 343			return mXmppConnectionService.databaseBackend.getSubDeviceSessions(account,
 344					new AxolotlAddress(name, 0));
 345		}
 346
 347		/**
 348		 * Commit to storage the {@link SessionRecord} for a given recipientId + deviceId tuple.
 349		 *
 350		 * @param address the address of the remote client.
 351		 * @param record  the current SessionRecord for the remote client.
 352		 */
 353		@Override
 354		public void storeSession(AxolotlAddress address, SessionRecord record) {
 355			mXmppConnectionService.databaseBackend.storeSession(account, address, record);
 356		}
 357
 358		/**
 359		 * Determine whether there is a committed {@link SessionRecord} for a recipientId + deviceId tuple.
 360		 *
 361		 * @param address the address of the remote client.
 362		 * @return true if a {@link SessionRecord} exists, false otherwise.
 363		 */
 364		@Override
 365		public boolean containsSession(AxolotlAddress address) {
 366			return mXmppConnectionService.databaseBackend.containsSession(account, address);
 367		}
 368
 369		/**
 370		 * Remove a {@link SessionRecord} for a recipientId + deviceId tuple.
 371		 *
 372		 * @param address the address of the remote client.
 373		 */
 374		@Override
 375		public void deleteSession(AxolotlAddress address) {
 376			mXmppConnectionService.databaseBackend.deleteSession(account, address);
 377		}
 378
 379		/**
 380		 * Remove the {@link SessionRecord}s corresponding to all devices of a recipientId.
 381		 *
 382		 * @param name the name of the remote client.
 383		 */
 384		@Override
 385		public void deleteAllSessions(String name) {
 386			mXmppConnectionService.databaseBackend.deleteAllSessions(account,
 387					new AxolotlAddress(name, 0));
 388		}
 389
 390		// --------------------------------------
 391		// PreKeyStore
 392		// --------------------------------------
 393
 394		/**
 395		 * Load a local PreKeyRecord.
 396		 *
 397		 * @param preKeyId the ID of the local PreKeyRecord.
 398		 * @return the corresponding PreKeyRecord.
 399		 * @throws InvalidKeyIdException when there is no corresponding PreKeyRecord.
 400		 */
 401		@Override
 402		public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
 403			PreKeyRecord record = mXmppConnectionService.databaseBackend.loadPreKey(account, preKeyId);
 404			if (record == null) {
 405				throw new InvalidKeyIdException("No such PreKeyRecord: " + preKeyId);
 406			}
 407			return record;
 408		}
 409
 410		/**
 411		 * Store a local PreKeyRecord.
 412		 *
 413		 * @param preKeyId the ID of the PreKeyRecord to store.
 414		 * @param record   the PreKeyRecord.
 415		 */
 416		@Override
 417		public void storePreKey(int preKeyId, PreKeyRecord record) {
 418			mXmppConnectionService.databaseBackend.storePreKey(account, record);
 419			currentPreKeyId = preKeyId;
 420			boolean success = this.account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(preKeyId));
 421			if (success) {
 422				mXmppConnectionService.databaseBackend.updateAccount(account);
 423			} else {
 424				Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Failed to write new prekey id to the database!");
 425			}
 426		}
 427
 428		/**
 429		 * @param preKeyId A PreKeyRecord ID.
 430		 * @return true if the store has a record for the preKeyId, otherwise false.
 431		 */
 432		@Override
 433		public boolean containsPreKey(int preKeyId) {
 434			return mXmppConnectionService.databaseBackend.containsPreKey(account, preKeyId);
 435		}
 436
 437		/**
 438		 * Delete a PreKeyRecord from local storage.
 439		 *
 440		 * @param preKeyId The ID of the PreKeyRecord to remove.
 441		 */
 442		@Override
 443		public void removePreKey(int preKeyId) {
 444			mXmppConnectionService.databaseBackend.deletePreKey(account, preKeyId);
 445		}
 446
 447		// --------------------------------------
 448		// SignedPreKeyStore
 449		// --------------------------------------
 450
 451		/**
 452		 * Load a local SignedPreKeyRecord.
 453		 *
 454		 * @param signedPreKeyId the ID of the local SignedPreKeyRecord.
 455		 * @return the corresponding SignedPreKeyRecord.
 456		 * @throws InvalidKeyIdException when there is no corresponding SignedPreKeyRecord.
 457		 */
 458		@Override
 459		public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
 460			SignedPreKeyRecord record = mXmppConnectionService.databaseBackend.loadSignedPreKey(account, signedPreKeyId);
 461			if (record == null) {
 462				throw new InvalidKeyIdException("No such SignedPreKeyRecord: " + signedPreKeyId);
 463			}
 464			return record;
 465		}
 466
 467		/**
 468		 * Load all local SignedPreKeyRecords.
 469		 *
 470		 * @return All stored SignedPreKeyRecords.
 471		 */
 472		@Override
 473		public List<SignedPreKeyRecord> loadSignedPreKeys() {
 474			return mXmppConnectionService.databaseBackend.loadSignedPreKeys(account);
 475		}
 476
 477		/**
 478		 * Store a local SignedPreKeyRecord.
 479		 *
 480		 * @param signedPreKeyId the ID of the SignedPreKeyRecord to store.
 481		 * @param record         the SignedPreKeyRecord.
 482		 */
 483		@Override
 484		public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
 485			mXmppConnectionService.databaseBackend.storeSignedPreKey(account, record);
 486		}
 487
 488		/**
 489		 * @param signedPreKeyId A SignedPreKeyRecord ID.
 490		 * @return true if the store has a record for the signedPreKeyId, otherwise false.
 491		 */
 492		@Override
 493		public boolean containsSignedPreKey(int signedPreKeyId) {
 494			return mXmppConnectionService.databaseBackend.containsSignedPreKey(account, signedPreKeyId);
 495		}
 496
 497		/**
 498		 * Delete a SignedPreKeyRecord from local storage.
 499		 *
 500		 * @param signedPreKeyId The ID of the SignedPreKeyRecord to remove.
 501		 */
 502		@Override
 503		public void removeSignedPreKey(int signedPreKeyId) {
 504			mXmppConnectionService.databaseBackend.deleteSignedPreKey(account, signedPreKeyId);
 505		}
 506	}
 507
 508	public static class XmppAxolotlSession {
 509		private final SessionCipher cipher;
 510		private Integer preKeyId = null;
 511		private final SQLiteAxolotlStore sqLiteAxolotlStore;
 512		private final AxolotlAddress remoteAddress;
 513		private final Account account;
 514		private String fingerprint = null;
 515
 516		public XmppAxolotlSession(Account account, SQLiteAxolotlStore store, AxolotlAddress remoteAddress, String fingerprint) {
 517			this(account, store, remoteAddress);
 518			this.fingerprint = fingerprint;
 519		}
 520
 521		public XmppAxolotlSession(Account account, SQLiteAxolotlStore store, AxolotlAddress remoteAddress) {
 522			this.cipher = new SessionCipher(store, remoteAddress);
 523			this.remoteAddress = remoteAddress;
 524			this.sqLiteAxolotlStore = store;
 525			this.account = account;
 526		}
 527
 528		public Integer getPreKeyId() {
 529			return preKeyId;
 530		}
 531
 532		public void resetPreKeyId() {
 533
 534			preKeyId = null;
 535		}
 536
 537		public String getFingerprint() {
 538			return fingerprint;
 539		}
 540
 541		private SQLiteAxolotlStore.Trust getTrust() {
 542			return sqLiteAxolotlStore.getFingerprintTrust(fingerprint);
 543		}
 544
 545		@Nullable
 546		public byte[] processReceiving(XmppAxolotlMessage.XmppAxolotlMessageHeader incomingHeader) {
 547			byte[] plaintext = null;
 548			switch (getTrust()) {
 549				case UNDECIDED:
 550				case UNTRUSTED:
 551				case TRUSTED:
 552					try {
 553						try {
 554							PreKeyWhisperMessage message = new PreKeyWhisperMessage(incomingHeader.getContents());
 555							Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"PreKeyWhisperMessage received, new session ID:" + message.getSignedPreKeyId() + "/" + message.getPreKeyId());
 556							String fingerprint = message.getIdentityKey().getFingerprint().replaceAll("\\s", "");
 557							if (this.fingerprint != null && !this.fingerprint.equals(fingerprint)) {
 558								Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Had session with fingerprint "+ this.fingerprint+", received message with fingerprint "+fingerprint);
 559							} else {
 560								this.fingerprint = fingerprint;
 561								plaintext = cipher.decrypt(message);
 562								if (message.getPreKeyId().isPresent()) {
 563									preKeyId = message.getPreKeyId().get();
 564								}
 565							}
 566						} catch (InvalidMessageException | InvalidVersionException e) {
 567							Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"WhisperMessage received");
 568							WhisperMessage message = new WhisperMessage(incomingHeader.getContents());
 569							plaintext = cipher.decrypt(message);
 570						} catch (InvalidKeyException | InvalidKeyIdException | UntrustedIdentityException e) {
 571							Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
 572						}
 573					} catch (LegacyMessageException | InvalidMessageException | DuplicateMessageException | NoSessionException  e) {
 574						Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
 575					}
 576
 577					break;
 578
 579				case COMPROMISED:
 580				default:
 581					// ignore
 582					break;
 583			}
 584			return plaintext;
 585		}
 586
 587		@Nullable
 588		public XmppAxolotlMessage.XmppAxolotlMessageHeader processSending(@NonNull byte[] outgoingMessage) {
 589			SQLiteAxolotlStore.Trust trust = getTrust();
 590			if (trust == SQLiteAxolotlStore.Trust.TRUSTED) {
 591				CiphertextMessage ciphertextMessage = cipher.encrypt(outgoingMessage);
 592				XmppAxolotlMessage.XmppAxolotlMessageHeader header =
 593						new XmppAxolotlMessage.XmppAxolotlMessageHeader(remoteAddress.getDeviceId(),
 594								ciphertextMessage.serialize());
 595				return header;
 596			} else {
 597				return null;
 598			}
 599		}
 600	}
 601
 602	private static class AxolotlAddressMap<T> {
 603		protected Map<String, Map<Integer, T>> map;
 604		protected final Object MAP_LOCK = new Object();
 605
 606		public AxolotlAddressMap() {
 607			this.map = new HashMap<>();
 608		}
 609
 610		public void put(AxolotlAddress address, T value) {
 611			synchronized (MAP_LOCK) {
 612				Map<Integer, T> devices = map.get(address.getName());
 613				if (devices == null) {
 614					devices = new HashMap<>();
 615					map.put(address.getName(), devices);
 616				}
 617				devices.put(address.getDeviceId(), value);
 618			}
 619		}
 620
 621		public T get(AxolotlAddress address) {
 622			synchronized (MAP_LOCK) {
 623				Map<Integer, T> devices = map.get(address.getName());
 624				if (devices == null) {
 625					return null;
 626				}
 627				return devices.get(address.getDeviceId());
 628			}
 629		}
 630
 631		public Map<Integer, T> getAll(AxolotlAddress address) {
 632			synchronized (MAP_LOCK) {
 633				Map<Integer, T> devices = map.get(address.getName());
 634				if (devices == null) {
 635					return new HashMap<>();
 636				}
 637				return devices;
 638			}
 639		}
 640
 641		public boolean hasAny(AxolotlAddress address) {
 642			synchronized (MAP_LOCK) {
 643				Map<Integer, T> devices = map.get(address.getName());
 644				return devices != null && !devices.isEmpty();
 645			}
 646		}
 647
 648		public void clear() {
 649			map.clear();
 650		}
 651
 652	}
 653
 654	private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
 655		private final XmppConnectionService xmppConnectionService;
 656		private final Account account;
 657
 658		public SessionMap(XmppConnectionService service, SQLiteAxolotlStore store, Account account) {
 659			super();
 660			this.xmppConnectionService = service;
 661			this.account = account;
 662			this.fillMap(store);
 663		}
 664
 665		private void putDevicesForJid(String bareJid, List<Integer> deviceIds, SQLiteAxolotlStore store) {
 666			for (Integer deviceId : deviceIds) {
 667				AxolotlAddress axolotlAddress = new AxolotlAddress(bareJid, deviceId);
 668				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Building session for remote address: "+axolotlAddress.toString());
 669				String fingerprint = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey().getFingerprint().replaceAll("\\s", "");
 670				this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, fingerprint));
 671			}
 672		}
 673
 674		private void fillMap(SQLiteAxolotlStore store) {
 675			List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().toBareJid().toString());
 676			putDevicesForJid(account.getJid().toBareJid().toString(), deviceIds, store);
 677			for (Contact contact : account.getRoster().getContacts()) {
 678				Jid bareJid = contact.getJid().toBareJid();
 679				if (bareJid == null) {
 680					continue; // FIXME: handle this?
 681				}
 682				String address = bareJid.toString();
 683				deviceIds = store.getSubDeviceSessions(address);
 684				putDevicesForJid(address, deviceIds, store);
 685			}
 686
 687		}
 688
 689		@Override
 690		public void put(AxolotlAddress address, XmppAxolotlSession value) {
 691			super.put(address, value);
 692			xmppConnectionService.syncRosterToDisk(account);
 693		}
 694	}
 695
 696	private static enum FetchStatus {
 697		PENDING,
 698		SUCCESS,
 699		ERROR
 700	}
 701
 702	private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
 703
 704	}
 705	
 706	public static String getLogprefix(Account account) {
 707		return LOGPREFIX+" ("+account.getJid().toBareJid().toString()+"): ";
 708	}
 709
 710	public AxolotlService(Account account, XmppConnectionService connectionService) {
 711		if (Security.getProvider("BC") == null) {
 712			Security.addProvider(new BouncyCastleProvider());
 713		}
 714		this.mXmppConnectionService = connectionService;
 715		this.account = account;
 716		this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
 717		this.deviceIds = new HashMap<>();
 718		this.messageCache = new HashMap<>();
 719		this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
 720		this.fetchStatusMap = new FetchStatusMap();
 721		this.executor = new SerialSingleThreadExecutor();
 722	}
 723
 724	public IdentityKey getOwnPublicKey() {
 725		return axolotlStore.getIdentityKeyPair().getPublicKey();
 726	}
 727
 728	public Set<IdentityKey> getKeysWithTrust(SQLiteAxolotlStore.Trust trust) {
 729		return axolotlStore.getContactUndecidedKeys(account.getJid().toBareJid().toString(), trust);
 730	}
 731
 732	public Set<IdentityKey> getKeysWithTrust(SQLiteAxolotlStore.Trust trust, Contact contact) {
 733		return axolotlStore.getContactUndecidedKeys(contact.getJid().toBareJid().toString(), trust);
 734	}
 735
 736	public long getNumTrustedKeys(Contact contact) {
 737		return axolotlStore.getContactNumTrustedKeys(contact.getJid().toBareJid().toString());
 738	}
 739
 740	private AxolotlAddress getAddressForJid(Jid jid) {
 741		return new AxolotlAddress(jid.toString(), 0);
 742	}
 743
 744	private Set<XmppAxolotlSession> findOwnSessions() {
 745		AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
 746		Set<XmppAxolotlSession> ownDeviceSessions = new HashSet<>(this.sessions.getAll(ownAddress).values());
 747		return ownDeviceSessions;
 748	}
 749
 750	private Set<XmppAxolotlSession> findSessionsforContact(Contact contact) {
 751		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
 752		Set<XmppAxolotlSession> sessions = new HashSet<>(this.sessions.getAll(contactAddress).values());
 753		return sessions;
 754	}
 755
 756	private boolean hasAny(Contact contact) {
 757		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
 758		return sessions.hasAny(contactAddress);
 759	}
 760
 761	public void regenerateKeys() {
 762		axolotlStore.regenerate();
 763		sessions.clear();
 764		fetchStatusMap.clear();
 765		publishBundlesIfNeeded();
 766		publishOwnDeviceIdIfNeeded();
 767	}
 768
 769	public int getOwnDeviceId() {
 770		return axolotlStore.loadRegistrationId();
 771	}
 772
 773	public Set<Integer> getOwnDeviceIds() {
 774		return this.deviceIds.get(account.getJid().toBareJid());
 775	}
 776
 777	public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
 778		if(deviceIds.contains(getOwnDeviceId())) {
 779			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Skipping own Device ID:"+ jid + ":"+getOwnDeviceId());
 780			deviceIds.remove(getOwnDeviceId());
 781		}
 782		for(Integer i:deviceIds) {
 783			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding Device ID:"+ jid + ":"+i);
 784		}
 785		this.deviceIds.put(jid, deviceIds);
 786		publishOwnDeviceIdIfNeeded();
 787	}
 788
 789	public void wipeOtherPepDevices() {
 790		Set<Integer> deviceIds = new HashSet<>();
 791		deviceIds.add(getOwnDeviceId());
 792		IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
 793		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Wiping all other devices from Pep:" + publish);
 794		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 795			@Override
 796			public void onIqPacketReceived(Account account, IqPacket packet) {
 797				// TODO: implement this!
 798			}
 799		});
 800	}
 801
 802	public void purgeKey(IdentityKey identityKey) {
 803		axolotlStore.setFingerprintTrust(identityKey.getFingerprint().replaceAll("\\s",""), SQLiteAxolotlStore.Trust.COMPROMISED);
 804	}
 805
 806	public void publishOwnDeviceIdIfNeeded() {
 807		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
 808		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 809			@Override
 810			public void onIqPacketReceived(Account account, IqPacket packet) {
 811				Element item = mXmppConnectionService.getIqParser().getItem(packet);
 812				Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
 813				if (deviceIds == null) {
 814					deviceIds = new HashSet<Integer>();
 815				}
 816				if (!deviceIds.contains(getOwnDeviceId())) {
 817					deviceIds.add(getOwnDeviceId());
 818					IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
 819					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Own device " + getOwnDeviceId() + " not in PEP devicelist. Publishing: " + publish);
 820					mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 821						@Override
 822						public void onIqPacketReceived(Account account, IqPacket packet) {
 823							// TODO: implement this!
 824						}
 825					});
 826				}
 827			}
 828		});
 829	}
 830
 831	public void publishBundlesIfNeeded() {
 832		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
 833		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 834			@Override
 835			public void onIqPacketReceived(Account account, IqPacket packet) {
 836				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
 837				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
 838				boolean flush = false;
 839				if (bundle == null) {
 840					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received invalid bundle:" + packet);
 841					bundle = new PreKeyBundle(-1, -1, -1 , null, -1, null, null, null);
 842					flush = true;
 843				}
 844				if (keys == null) {
 845					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received invalid prekeys:" + packet);
 846				}
 847				try {
 848					boolean changed = false;
 849					// Validate IdentityKey
 850					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
 851					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
 852						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
 853						changed = true;
 854					}
 855
 856					// Validate signedPreKeyRecord + ID
 857					SignedPreKeyRecord signedPreKeyRecord;
 858					int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
 859					try {
 860						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
 861						if ( flush
 862								||!bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
 863								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
 864							Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 865							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 866							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 867							changed = true;
 868						}
 869					} catch (InvalidKeyIdException e) {
 870						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 871						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 872						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 873						changed = true;
 874					}
 875
 876					// Validate PreKeys
 877					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
 878					if (keys != null) {
 879						for (Integer id : keys.keySet()) {
 880							try {
 881								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
 882								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
 883									preKeyRecords.add(preKeyRecord);
 884								}
 885							} catch (InvalidKeyIdException ignored) {
 886							}
 887						}
 888					}
 889					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
 890					if (newKeys > 0) {
 891						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
 892								axolotlStore.getCurrentPreKeyId()+1, newKeys);
 893						preKeyRecords.addAll(newRecords);
 894						for (PreKeyRecord record : newRecords) {
 895							axolotlStore.storePreKey(record.getId(), record);
 896						}
 897						changed = true;
 898						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding " + newKeys + " new preKeys to PEP.");
 899					}
 900
 901
 902					if(changed) {
 903						IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
 904								signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
 905								preKeyRecords, getOwnDeviceId());
 906						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+ ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
 907						mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 908							@Override
 909							public void onIqPacketReceived(Account account, IqPacket packet) {
 910								// TODO: implement this!
 911								Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Published bundle, got: " + packet);
 912							}
 913						});
 914					}
 915				} catch (InvalidKeyException e) {
 916						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
 917						return;
 918				}
 919			}
 920		});
 921	}
 922
 923	public boolean isContactAxolotlCapable(Contact contact) {
 924
 925		Jid jid = contact.getJid().toBareJid();
 926		AxolotlAddress address = new AxolotlAddress(jid.toString(), 0);
 927		return sessions.hasAny(address) ||
 928				( deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
 929	}
 930	public SQLiteAxolotlStore.Trust getFingerprintTrust(String fingerprint) {
 931		return axolotlStore.getFingerprintTrust(fingerprint);
 932	}
 933
 934	public void setFingerprintTrust(String fingerprint, SQLiteAxolotlStore.Trust trust) {
 935		axolotlStore.setFingerprintTrust(fingerprint, trust);
 936	}
 937
 938	private void buildSessionFromPEP(final Conversation conversation, final AxolotlAddress address, final boolean flushWaitingQueueAfterFetch) {
 939		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.getDeviceId());
 940
 941		try {
 942			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
 943					Jid.fromString(address.getName()), address.getDeviceId());
 944			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Retrieving bundle: " + bundlesPacket);
 945			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
 946				private void finish() {
 947					AxolotlAddress ownAddress = new AxolotlAddress(conversation.getAccount().getJid().toBareJid().toString(),0);
 948					AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(),0);
 949					if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
 950							&& !fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING)) {
 951						if (flushWaitingQueueAfterFetch) {
 952							conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_AXOLOTL,
 953									new Conversation.OnMessageFound() {
 954										@Override
 955										public void onMessageFound(Message message) {
 956											processSending(message,false);
 957										}
 958									});
 959						}
 960						mXmppConnectionService.newKeysAvailable();
 961					}
 962				}
 963
 964				@Override
 965				public void onIqPacketReceived(Account account, IqPacket packet) {
 966					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received preKey IQ packet, processing...");
 967					final IqParser parser = mXmppConnectionService.getIqParser();
 968					final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
 969					final PreKeyBundle bundle = parser.bundle(packet);
 970					if (preKeyBundleList.isEmpty() || bundle == null) {
 971						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"preKey IQ packet invalid: " + packet);
 972						fetchStatusMap.put(address, FetchStatus.ERROR);
 973						finish();
 974						return;
 975					}
 976					Random random = new Random();
 977					final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
 978					if (preKey == null) {
 979						//should never happen
 980						fetchStatusMap.put(address, FetchStatus.ERROR);
 981						finish();
 982						return;
 983					}
 984
 985					final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
 986							preKey.getPreKeyId(), preKey.getPreKey(),
 987							bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
 988							bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
 989
 990					axolotlStore.saveIdentity(address.getName(), bundle.getIdentityKey());
 991
 992					try {
 993						SessionBuilder builder = new SessionBuilder(axolotlStore, address);
 994						builder.process(preKeyBundle);
 995						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", ""));
 996						sessions.put(address, session);
 997						fetchStatusMap.put(address, FetchStatus.SUCCESS);
 998					} catch (UntrustedIdentityException|InvalidKeyException e) {
 999						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Error building session for " + address + ": "
1000								+ e.getClass().getName() + ", " + e.getMessage());
1001						fetchStatusMap.put(address, FetchStatus.ERROR);
1002					}
1003
1004					finish();
1005				}
1006			});
1007		} catch (InvalidJidException e) {
1008			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Got address with invalid jid: " + address.getName());
1009		}
1010	}
1011
1012	public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
1013		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + conversation.getContact().getJid().toBareJid());
1014		Jid contactJid = conversation.getContact().getJid().toBareJid();
1015		Set<AxolotlAddress> addresses = new HashSet<>();
1016		if(deviceIds.get(contactJid) != null) {
1017			for(Integer foreignId:this.deviceIds.get(contactJid)) {
1018				AxolotlAddress address = new AxolotlAddress(contactJid.toString(), foreignId);
1019				if(sessions.get(address) == null) {
1020					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1021					if ( identityKey != null ) {
1022						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Already have session for " +  address.toString() + ", adding to cache...");
1023						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
1024						sessions.put(address, session);
1025					} else {
1026						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + foreignId);
1027						addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
1028					}
1029				}
1030			}
1031		} else {
1032			Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
1033		}
1034		if(deviceIds.get(account.getJid().toBareJid()) != null) {
1035			for(Integer ownId:this.deviceIds.get(account.getJid().toBareJid())) {
1036				AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toString(), ownId);
1037				if(sessions.get(address) == null) {
1038					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1039					if ( identityKey != null ) {
1040						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Already have session for " +  address.toString() + ", adding to cache...");
1041						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
1042						sessions.put(address, session);
1043					} else {
1044						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
1045						addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
1046					}
1047				}
1048			}
1049		}
1050
1051		return addresses;
1052	}
1053
1054	public boolean createSessionsIfNeeded(final Conversation conversation, final boolean flushWaitingQueueAfterFetch) {
1055		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
1056		boolean newSessions = false;
1057		Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
1058		for (AxolotlAddress address : addresses) {
1059			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
1060			FetchStatus status = fetchStatusMap.get(address);
1061			if ( status == null || status == FetchStatus.ERROR ) {
1062					fetchStatusMap.put(address, FetchStatus.PENDING);
1063					this.buildSessionFromPEP(conversation, address, flushWaitingQueueAfterFetch);
1064					newSessions = true;
1065			} else {
1066				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Already fetching bundle for " +  address.toString());
1067			}
1068		}
1069
1070		return newSessions;
1071	}
1072
1073	public boolean hasPendingKeyFetches(Conversation conversation) {
1074		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(),0);
1075		AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(),0);
1076		return fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
1077				||fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING);
1078
1079	}
1080
1081	@Nullable
1082	public XmppAxolotlMessage encrypt(Message message ){
1083		final String content;
1084		if (message.hasFileOnRemoteHost()) {
1085				content = message.getFileParams().url.toString();
1086		} else {
1087			content = message.getBody();
1088		}
1089		final XmppAxolotlMessage axolotlMessage;
1090		try {
1091			axolotlMessage = new XmppAxolotlMessage(message.getContact().getJid().toBareJid(),
1092					getOwnDeviceId(), content);
1093		} catch (CryptoFailedException e) {
1094			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
1095			return null;
1096		}
1097
1098		if(findSessionsforContact(message.getContact()).isEmpty()) {
1099			return null;
1100		}
1101		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Building axolotl foreign headers...");
1102		for (XmppAxolotlSession session : findSessionsforContact(message.getContact())) {
1103			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account)+session.remoteAddress.toString());
1104			//if(!session.isTrusted()) {
1105			// TODO: handle this properly
1106			//              continue;
1107			//        }
1108			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
1109		}
1110		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Building axolotl own headers...");
1111		for (XmppAxolotlSession session : findOwnSessions()) {
1112			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account)+session.remoteAddress.toString());
1113			//        if(!session.isTrusted()) {
1114			// TODO: handle this properly
1115			//          continue;
1116			//    }
1117			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
1118		}
1119
1120		return axolotlMessage;
1121	}
1122
1123	private void processSending(final Message message, final boolean delay) {
1124		executor.execute(new Runnable() {
1125			@Override
1126			public void run() {
1127				XmppAxolotlMessage axolotlMessage = encrypt(message);
1128				if (axolotlMessage == null) {
1129					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1130					//mXmppConnectionService.updateConversationUi();
1131				} else {
1132					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Generated message, caching: " + message.getUuid());
1133					messageCache.put(message.getUuid(), axolotlMessage);
1134					mXmppConnectionService.resendMessage(message,delay);
1135				}
1136			}
1137		});
1138	}
1139
1140	public void prepareMessage(final Message message,final boolean delay) {
1141		if (!messageCache.containsKey(message.getUuid())) {
1142			boolean newSessions = createSessionsIfNeeded(message.getConversation(), true);
1143			if (!newSessions) {
1144				this.processSending(message,delay);
1145			}
1146		}
1147	}
1148
1149	public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
1150		XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
1151		if (axolotlMessage != null) {
1152			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Cache hit: " + message.getUuid());
1153			messageCache.remove(message.getUuid());
1154		} else {
1155			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Cache miss: " + message.getUuid());
1156		}
1157		return axolotlMessage;
1158	}
1159
1160	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceiving(XmppAxolotlMessage message) {
1161		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
1162		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
1163				message.getSenderDeviceId());
1164
1165		boolean newSession = false;
1166		XmppAxolotlSession session = sessions.get(senderAddress);
1167		if (session == null) {
1168			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Account: "+account.getJid()+" No axolotl session found while parsing received message " + message);
1169			// TODO: handle this properly
1170			IdentityKey identityKey = axolotlStore.loadSession(senderAddress).getSessionState().getRemoteIdentityKey();
1171			if ( identityKey != null ) {
1172				session = new XmppAxolotlSession(account, axolotlStore, senderAddress, identityKey.getFingerprint().replaceAll("\\s", ""));
1173			} else {
1174				session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
1175			}
1176			newSession = true;
1177		}
1178
1179		for (XmppAxolotlMessage.XmppAxolotlMessageHeader header : message.getHeaders()) {
1180			if (header.getRecipientDeviceId() == getOwnDeviceId()) {
1181				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Found axolotl header matching own device ID, processing...");
1182				byte[] payloadKey = session.processReceiving(header);
1183				if (payloadKey != null) {
1184					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Got payload key from axolotl header. Decrypting message...");
1185					try{
1186						plaintextMessage = message.decrypt(session, payloadKey, session.getFingerprint());
1187					} catch (CryptoFailedException e) {
1188						Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
1189						break;
1190					}
1191				}
1192				Integer preKeyId = session.getPreKeyId();
1193				if (preKeyId != null) {
1194					publishBundlesIfNeeded();
1195					session.resetPreKeyId();
1196				}
1197				break;
1198			}
1199		}
1200
1201		if (newSession && plaintextMessage != null) {
1202			sessions.put(senderAddress, session);
1203		}
1204
1205		return plaintextMessage;
1206	}
1207}