DatabaseBackend.java

   1package eu.siacs.conversations.persistance;
   2
   3import android.content.ContentValues;
   4import android.content.Context;
   5import android.database.Cursor;
   6import android.database.DatabaseUtils;
   7import android.database.sqlite.SQLiteCantOpenDatabaseException;
   8import android.database.sqlite.SQLiteDatabase;
   9import android.database.sqlite.SQLiteOpenHelper;
  10import android.util.Base64;
  11import android.util.Log;
  12import android.util.Pair;
  13
  14import org.json.JSONObject;
  15import org.whispersystems.libaxolotl.AxolotlAddress;
  16import org.whispersystems.libaxolotl.IdentityKey;
  17import org.whispersystems.libaxolotl.IdentityKeyPair;
  18import org.whispersystems.libaxolotl.InvalidKeyException;
  19import org.whispersystems.libaxolotl.state.PreKeyRecord;
  20import org.whispersystems.libaxolotl.state.SessionRecord;
  21import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
  22
  23import java.io.ByteArrayInputStream;
  24import java.io.IOException;
  25import java.security.cert.CertificateEncodingException;
  26import java.security.cert.CertificateException;
  27import java.security.cert.CertificateFactory;
  28import java.security.cert.X509Certificate;
  29import java.util.ArrayList;
  30import java.util.HashMap;
  31import java.util.HashSet;
  32import java.util.Iterator;
  33import java.util.List;
  34import java.util.Map;
  35import java.util.Set;
  36import java.util.concurrent.CopyOnWriteArrayList;
  37import org.json.JSONException;
  38
  39import eu.siacs.conversations.Config;
  40import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  41import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  42import eu.siacs.conversations.crypto.axolotl.SQLiteAxolotlStore;
  43import eu.siacs.conversations.entities.Account;
  44import eu.siacs.conversations.entities.Contact;
  45import eu.siacs.conversations.entities.Conversation;
  46import eu.siacs.conversations.entities.Message;
  47import eu.siacs.conversations.entities.PresenceTemplate;
  48import eu.siacs.conversations.entities.Roster;
  49import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  50import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  51import eu.siacs.conversations.xmpp.jid.Jid;
  52
  53public class DatabaseBackend extends SQLiteOpenHelper {
  54
  55	private static DatabaseBackend instance = null;
  56
  57	private static final String DATABASE_NAME = "history";
  58	private static final int DATABASE_VERSION = 32;
  59
  60	private static String CREATE_CONTATCS_STATEMENT = "create table "
  61			+ Contact.TABLENAME + "(" + Contact.ACCOUNT + " TEXT, "
  62			+ Contact.SERVERNAME + " TEXT, " + Contact.SYSTEMNAME + " TEXT,"
  63			+ Contact.JID + " TEXT," + Contact.KEYS + " TEXT,"
  64			+ Contact.PHOTOURI + " TEXT," + Contact.OPTIONS + " NUMBER,"
  65			+ Contact.SYSTEMACCOUNT + " NUMBER, " + Contact.AVATAR + " TEXT, "
  66			+ Contact.LAST_PRESENCE + " TEXT, " + Contact.LAST_TIME + " NUMBER, "
  67			+ Contact.GROUPS + " TEXT, FOREIGN KEY(" + Contact.ACCOUNT + ") REFERENCES "
  68			+ Account.TABLENAME + "(" + Account.UUID
  69			+ ") ON DELETE CASCADE, UNIQUE(" + Contact.ACCOUNT + ", "
  70			+ Contact.JID + ") ON CONFLICT REPLACE);";
  71
  72	private static String CREATE_DISCOVERY_RESULTS_STATEMENT = "create table "
  73			+ ServiceDiscoveryResult.TABLENAME + "("
  74			+ ServiceDiscoveryResult.HASH + " TEXT, "
  75			+ ServiceDiscoveryResult.VER + " TEXT, "
  76			+ ServiceDiscoveryResult.RESULT + " TEXT, "
  77			+ "UNIQUE(" + ServiceDiscoveryResult.HASH + ", "
  78			+ ServiceDiscoveryResult.VER + ") ON CONFLICT REPLACE);";
  79
  80	private static String CREATE_PRESENCE_TEMPLATES_STATEMENT = "CREATE TABLE "
  81			+ PresenceTemplate.TABELNAME + "("
  82			+ PresenceTemplate.UUID + " TEXT, "
  83			+ PresenceTemplate.LAST_USED + " NUMBER,"
  84			+ PresenceTemplate.MESSAGE + " TEXT,"
  85			+ PresenceTemplate.STATUS + " TEXT,"
  86			+ "UNIQUE("+PresenceTemplate.MESSAGE + "," +PresenceTemplate.STATUS+") ON CONFLICT REPLACE);";
  87
  88	private static String CREATE_PREKEYS_STATEMENT = "CREATE TABLE "
  89			+ SQLiteAxolotlStore.PREKEY_TABLENAME + "("
  90			+ SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
  91			+ SQLiteAxolotlStore.ID + " INTEGER, "
  92			+ SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
  93			+ SQLiteAxolotlStore.ACCOUNT
  94			+ ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
  95			+ "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
  96			+ SQLiteAxolotlStore.ID
  97			+ ") ON CONFLICT REPLACE"
  98			+ ");";
  99
 100	private static String CREATE_SIGNED_PREKEYS_STATEMENT = "CREATE TABLE "
 101			+ SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME + "("
 102			+ SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 103			+ SQLiteAxolotlStore.ID + " INTEGER, "
 104			+ SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 105			+ SQLiteAxolotlStore.ACCOUNT
 106			+ ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 107			+ "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 108			+ SQLiteAxolotlStore.ID
 109			+ ") ON CONFLICT REPLACE" +
 110			");";
 111
 112	private static String CREATE_SESSIONS_STATEMENT = "CREATE TABLE "
 113			+ SQLiteAxolotlStore.SESSION_TABLENAME + "("
 114			+ SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 115			+ SQLiteAxolotlStore.NAME + " TEXT, "
 116			+ SQLiteAxolotlStore.DEVICE_ID + " INTEGER, "
 117			+ SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 118			+ SQLiteAxolotlStore.ACCOUNT
 119			+ ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 120			+ "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 121			+ SQLiteAxolotlStore.NAME + ", "
 122			+ SQLiteAxolotlStore.DEVICE_ID
 123			+ ") ON CONFLICT REPLACE"
 124			+ ");";
 125
 126	private static String CREATE_IDENTITIES_STATEMENT = "CREATE TABLE "
 127			+ SQLiteAxolotlStore.IDENTITIES_TABLENAME + "("
 128			+ SQLiteAxolotlStore.ACCOUNT + " TEXT,  "
 129			+ SQLiteAxolotlStore.NAME + " TEXT, "
 130			+ SQLiteAxolotlStore.OWN + " INTEGER, "
 131			+ SQLiteAxolotlStore.FINGERPRINT + " TEXT, "
 132			+ SQLiteAxolotlStore.CERTIFICATE + " BLOB, "
 133			+ SQLiteAxolotlStore.TRUST + " TEXT, "
 134			+ SQLiteAxolotlStore.ACTIVE + " NUMBER, "
 135			+ SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER,"
 136			+ SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
 137			+ SQLiteAxolotlStore.ACCOUNT
 138			+ ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
 139			+ "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
 140			+ SQLiteAxolotlStore.NAME + ", "
 141			+ SQLiteAxolotlStore.FINGERPRINT
 142			+ ") ON CONFLICT IGNORE"
 143			+ ");";
 144
 145	private static String START_TIMES_TABLE = "start_times";
 146
 147	private static String CREATE_START_TIMES_TABLE = "create table "+START_TIMES_TABLE+" (timestamp NUMBER);";
 148
 149	private DatabaseBackend(Context context) {
 150		super(context, DATABASE_NAME, null, DATABASE_VERSION);
 151	}
 152
 153	@Override
 154	public void onCreate(SQLiteDatabase db) {
 155		db.execSQL("PRAGMA foreign_keys=ON;");
 156		db.execSQL("create table " + Account.TABLENAME + "(" + Account.UUID+ " TEXT PRIMARY KEY,"
 157				+ Account.USERNAME + " TEXT,"
 158				+ Account.SERVER + " TEXT,"
 159				+ Account.PASSWORD + " TEXT,"
 160				+ Account.DISPLAY_NAME + " TEXT, "
 161				+ Account.STATUS + " TEXT,"
 162				+ Account.STATUS_MESSAGE + " TEXT,"
 163				+ Account.ROSTERVERSION + " TEXT,"
 164				+ Account.OPTIONS + " NUMBER, "
 165				+ Account.AVATAR + " TEXT, "
 166				+ Account.KEYS + " TEXT, "
 167				+ Account.HOSTNAME + " TEXT, "
 168				+ Account.PORT + " NUMBER DEFAULT 5222)");
 169		db.execSQL("create table " + Conversation.TABLENAME + " ("
 170				+ Conversation.UUID + " TEXT PRIMARY KEY, " + Conversation.NAME
 171				+ " TEXT, " + Conversation.CONTACT + " TEXT, "
 172				+ Conversation.ACCOUNT + " TEXT, " + Conversation.CONTACTJID
 173				+ " TEXT, " + Conversation.CREATED + " NUMBER, "
 174				+ Conversation.STATUS + " NUMBER, " + Conversation.MODE
 175				+ " NUMBER, " + Conversation.ATTRIBUTES + " TEXT, FOREIGN KEY("
 176				+ Conversation.ACCOUNT + ") REFERENCES " + Account.TABLENAME
 177				+ "(" + Account.UUID + ") ON DELETE CASCADE);");
 178		db.execSQL("create table " + Message.TABLENAME + "( " + Message.UUID
 179				+ " TEXT PRIMARY KEY, " + Message.CONVERSATION + " TEXT, "
 180				+ Message.TIME_SENT + " NUMBER, " + Message.COUNTERPART
 181				+ " TEXT, " + Message.TRUE_COUNTERPART + " TEXT,"
 182				+ Message.BODY + " TEXT, " + Message.ENCRYPTION + " NUMBER, "
 183				+ Message.STATUS + " NUMBER," + Message.TYPE + " NUMBER, "
 184				+ Message.RELATIVE_FILE_PATH + " TEXT, "
 185				+ Message.SERVER_MSG_ID + " TEXT, "
 186				+ Message.FINGERPRINT + " TEXT, "
 187				+ Message.CARBON + " INTEGER, "
 188				+ Message.EDITED + " TEXT, "
 189				+ Message.READ + " NUMBER DEFAULT 1, "
 190				+ Message.OOB + " INTEGER, "
 191				+ Message.ERROR_MESSAGE + " TEXT,"
 192				+ Message.REMOTE_MSG_ID + " TEXT, FOREIGN KEY("
 193				+ Message.CONVERSATION + ") REFERENCES "
 194				+ Conversation.TABLENAME + "(" + Conversation.UUID
 195				+ ") ON DELETE CASCADE);");
 196
 197		db.execSQL(CREATE_CONTATCS_STATEMENT);
 198		db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
 199		db.execSQL(CREATE_SESSIONS_STATEMENT);
 200		db.execSQL(CREATE_PREKEYS_STATEMENT);
 201		db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
 202		db.execSQL(CREATE_IDENTITIES_STATEMENT);
 203		db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
 204		db.execSQL(CREATE_START_TIMES_TABLE);
 205	}
 206
 207	@Override
 208	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 209		if (oldVersion < 2 && newVersion >= 2) {
 210			db.execSQL("update " + Account.TABLENAME + " set "
 211					+ Account.OPTIONS + " = " + Account.OPTIONS + " | 8");
 212		}
 213		if (oldVersion < 3 && newVersion >= 3) {
 214			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 215					+ Message.TYPE + " NUMBER");
 216		}
 217		if (oldVersion < 5 && newVersion >= 5) {
 218			db.execSQL("DROP TABLE " + Contact.TABLENAME);
 219			db.execSQL(CREATE_CONTATCS_STATEMENT);
 220			db.execSQL("UPDATE " + Account.TABLENAME + " SET "
 221					+ Account.ROSTERVERSION + " = NULL");
 222		}
 223		if (oldVersion < 6 && newVersion >= 6) {
 224			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 225					+ Message.TRUE_COUNTERPART + " TEXT");
 226		}
 227		if (oldVersion < 7 && newVersion >= 7) {
 228			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 229					+ Message.REMOTE_MSG_ID + " TEXT");
 230			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 231					+ Contact.AVATAR + " TEXT");
 232			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN "
 233					+ Account.AVATAR + " TEXT");
 234		}
 235		if (oldVersion < 8 && newVersion >= 8) {
 236			db.execSQL("ALTER TABLE " + Conversation.TABLENAME + " ADD COLUMN "
 237					+ Conversation.ATTRIBUTES + " TEXT");
 238		}
 239		if (oldVersion < 9 && newVersion >= 9) {
 240			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 241					+ Contact.LAST_TIME + " NUMBER");
 242			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 243					+ Contact.LAST_PRESENCE + " TEXT");
 244		}
 245		if (oldVersion < 10 && newVersion >= 10) {
 246			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 247					+ Message.RELATIVE_FILE_PATH + " TEXT");
 248		}
 249		if (oldVersion < 11 && newVersion >= 11) {
 250			db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
 251					+ Contact.GROUPS + " TEXT");
 252			db.execSQL("delete from " + Contact.TABLENAME);
 253			db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
 254		}
 255		if (oldVersion < 12 && newVersion >= 12) {
 256			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 257					+ Message.SERVER_MSG_ID + " TEXT");
 258		}
 259		if (oldVersion < 13 && newVersion >= 13) {
 260			db.execSQL("delete from " + Contact.TABLENAME);
 261			db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
 262		}
 263		if (oldVersion < 14 && newVersion >= 14) {
 264			canonicalizeJids(db);
 265		}
 266		if (oldVersion < 15 && newVersion >= 15) {
 267			recreateAxolotlDb(db);
 268			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 269					+ Message.FINGERPRINT + " TEXT");
 270		} else if (oldVersion < 22 && newVersion >= 22) {
 271			db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.CERTIFICATE);
 272		}
 273		if (oldVersion < 16 && newVersion >= 16) {
 274			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
 275					+ Message.CARBON + " INTEGER");
 276		}
 277		if (oldVersion < 19 && newVersion >= 19) {
 278			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.DISPLAY_NAME + " TEXT");
 279		}
 280		if (oldVersion < 20 && newVersion >= 20) {
 281			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.HOSTNAME + " TEXT");
 282			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.PORT + " NUMBER DEFAULT 5222");
 283		}
 284		if (oldVersion < 26 && newVersion >= 26) {
 285			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS + " TEXT");
 286			db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS_MESSAGE + " TEXT");
 287		}
 288		/* Any migrations that alter the Account table need to happen BEFORE this migration, as it
 289		 * depends on account de-serialization.
 290		 */
 291		if (oldVersion < 17 && newVersion >= 17) {
 292			List<Account> accounts = getAccounts(db);
 293			for (Account account : accounts) {
 294				String ownDeviceIdString = account.getKey(SQLiteAxolotlStore.JSONKEY_REGISTRATION_ID);
 295				if (ownDeviceIdString == null) {
 296					continue;
 297				}
 298				int ownDeviceId = Integer.valueOf(ownDeviceIdString);
 299				AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), ownDeviceId);
 300				deleteSession(db, account, ownAddress);
 301				IdentityKeyPair identityKeyPair = loadOwnIdentityKeyPair(db, account);
 302				if (identityKeyPair != null) {
 303					String[] selectionArgs = {
 304							account.getUuid(),
 305							identityKeyPair.getPublicKey().getFingerprint().replaceAll("\\s", "")
 306					};
 307					ContentValues values = new ContentValues();
 308					values.put(SQLiteAxolotlStore.TRUSTED, 2);
 309					db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
 310							SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 311									+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
 312							selectionArgs);
 313				} else {
 314					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not load own identity key pair");
 315				}
 316			}
 317		}
 318		if (oldVersion < 18 && newVersion >= 18) {
 319			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.READ + " NUMBER DEFAULT 1");
 320		}
 321
 322		if (oldVersion < 21 && newVersion >= 21) {
 323			List<Account> accounts = getAccounts(db);
 324			for (Account account : accounts) {
 325				account.unsetPgpSignature();
 326				db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
 327						+ "=?", new String[]{account.getUuid()});
 328			}
 329		}
 330
 331		if (oldVersion < 23 && newVersion >= 23) {
 332			db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
 333		}
 334
 335		if (oldVersion < 24 && newVersion >= 24) {
 336			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.EDITED + " TEXT");
 337		}
 338
 339		if (oldVersion < 25 && newVersion >= 25) {
 340			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.OOB + " INTEGER");
 341		}
 342
 343		if (oldVersion <  26 && newVersion >= 26) {
 344			db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
 345		}
 346
 347		if (oldVersion < 27 && newVersion >= 27) {
 348			db.execSQL("DELETE FROM "+ServiceDiscoveryResult.TABLENAME);
 349		}
 350
 351		if (oldVersion < 28 && newVersion >= 28) {
 352			canonicalizeJids(db);
 353		}
 354
 355		if (oldVersion < 29 && newVersion >= 29) {
 356			db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.ERROR_MESSAGE + " TEXT");
 357		}
 358		if (oldVersion < 30 && newVersion >= 30) {
 359			db.execSQL(CREATE_START_TIMES_TABLE);
 360		}
 361		if (oldVersion < 31 && newVersion >= 31) {
 362			db.execSQL("ALTER TABLE "+ SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN "+SQLiteAxolotlStore.TRUST + " TEXT");
 363			db.execSQL("ALTER TABLE "+ SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN "+SQLiteAxolotlStore.ACTIVE + " NUMBER");
 364			HashMap<Integer,ContentValues> migration = new HashMap<>();
 365			migration.put(0,createFingerprintStatusContentValues(FingerprintStatus.Trust.UNDECIDED,true));
 366			migration.put(1,createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
 367			migration.put(2,createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, true));
 368			migration.put(3,createFingerprintStatusContentValues(FingerprintStatus.Trust.COMPROMISED, false));
 369			migration.put(4,createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
 370			migration.put(5,createFingerprintStatusContentValues(FingerprintStatus.Trust.UNDECIDED, false));
 371			migration.put(6,createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, false));
 372			migration.put(7,createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, true));
 373			migration.put(8,createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, false));
 374			for(Map.Entry<Integer,ContentValues> entry : migration.entrySet()) {
 375				String whereClause = SQLiteAxolotlStore.TRUSTED+"=?";
 376				String[] where = {String.valueOf(entry.getKey())};
 377				db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME,entry.getValue(),whereClause,where);
 378			}
 379
 380		}
 381		if (oldVersion < 32 && newVersion >= 32) {
 382			db.execSQL("ALTER TABLE "+ SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN "+SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER");
 383			ContentValues defaults = new ContentValues();
 384			defaults.put(SQLiteAxolotlStore.LAST_ACTIVATION,System.currentTimeMillis());
 385			db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME,defaults,null,null);
 386		}
 387	}
 388
 389	private static ContentValues createFingerprintStatusContentValues(FingerprintStatus.Trust trust, boolean active) {
 390		ContentValues values = new ContentValues();
 391		values.put(SQLiteAxolotlStore.TRUST,trust.toString());
 392		values.put(SQLiteAxolotlStore.ACTIVE,active ? 1 : 0);
 393		return values;
 394	}
 395
 396	private void canonicalizeJids(SQLiteDatabase db) {
 397		// migrate db to new, canonicalized JID domainpart representation
 398
 399		// Conversation table
 400		Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
 401		while (cursor.moveToNext()) {
 402			String newJid;
 403			try {
 404				newJid = Jid.fromString(
 405						cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
 406				).toPreppedString();
 407			} catch (InvalidJidException ignored) {
 408				Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID "
 409						+ cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
 410						+ ": " + ignored + ". Skipping...");
 411				continue;
 412			}
 413
 414			String updateArgs[] = {
 415					newJid,
 416					cursor.getString(cursor.getColumnIndex(Conversation.UUID)),
 417			};
 418			db.execSQL("update " + Conversation.TABLENAME
 419					+ " set " + Conversation.CONTACTJID + " = ? "
 420					+ " where " + Conversation.UUID + " = ?", updateArgs);
 421		}
 422		cursor.close();
 423
 424		// Contact table
 425		cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
 426		while (cursor.moveToNext()) {
 427			String newJid;
 428			try {
 429				newJid = Jid.fromString(
 430						cursor.getString(cursor.getColumnIndex(Contact.JID))
 431				).toPreppedString();
 432			} catch (InvalidJidException ignored) {
 433				Log.e(Config.LOGTAG, "Failed to migrate Contact JID "
 434						+ cursor.getString(cursor.getColumnIndex(Contact.JID))
 435						+ ": " + ignored + ". Skipping...");
 436				continue;
 437			}
 438
 439			String updateArgs[] = {
 440					newJid,
 441					cursor.getString(cursor.getColumnIndex(Contact.ACCOUNT)),
 442					cursor.getString(cursor.getColumnIndex(Contact.JID)),
 443			};
 444			db.execSQL("update " + Contact.TABLENAME
 445					+ " set " + Contact.JID + " = ? "
 446					+ " where " + Contact.ACCOUNT + " = ? "
 447					+ " AND " + Contact.JID + " = ?", updateArgs);
 448		}
 449		cursor.close();
 450
 451		// Account table
 452		cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
 453		while (cursor.moveToNext()) {
 454			String newServer;
 455			try {
 456				newServer = Jid.fromParts(
 457						cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
 458						cursor.getString(cursor.getColumnIndex(Account.SERVER)),
 459						"mobile"
 460				).getDomainpart();
 461			} catch (InvalidJidException ignored) {
 462				Log.e(Config.LOGTAG, "Failed to migrate Account SERVER "
 463						+ cursor.getString(cursor.getColumnIndex(Account.SERVER))
 464						+ ": " + ignored + ". Skipping...");
 465				continue;
 466			}
 467
 468			String updateArgs[] = {
 469					newServer,
 470					cursor.getString(cursor.getColumnIndex(Account.UUID)),
 471			};
 472			db.execSQL("update " + Account.TABLENAME
 473					+ " set " + Account.SERVER + " = ? "
 474					+ " where " + Account.UUID + " = ?", updateArgs);
 475		}
 476		cursor.close();
 477	}
 478
 479	public static synchronized DatabaseBackend getInstance(Context context) {
 480		if (instance == null) {
 481			instance = new DatabaseBackend(context);
 482		}
 483		return instance;
 484	}
 485
 486	public void createConversation(Conversation conversation) {
 487		SQLiteDatabase db = this.getWritableDatabase();
 488		db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
 489	}
 490
 491	public void createMessage(Message message) {
 492		SQLiteDatabase db = this.getWritableDatabase();
 493		db.insert(Message.TABLENAME, null, message.getContentValues());
 494	}
 495
 496	public void createAccount(Account account) {
 497		SQLiteDatabase db = this.getWritableDatabase();
 498		db.insert(Account.TABLENAME, null, account.getContentValues());
 499	}
 500
 501	public void insertDiscoveryResult(ServiceDiscoveryResult result) {
 502		SQLiteDatabase db = this.getWritableDatabase();
 503		db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
 504	}
 505
 506	public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
 507		SQLiteDatabase db = this.getReadableDatabase();
 508		String[] selectionArgs = {hash, ver};
 509		Cursor cursor = db.query(ServiceDiscoveryResult.TABLENAME, null,
 510				ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
 511				selectionArgs, null, null, null);
 512		if (cursor.getCount() == 0) {
 513			cursor.close();
 514			return null;
 515		}
 516		cursor.moveToFirst();
 517
 518		ServiceDiscoveryResult result = null;
 519		try {
 520			result = new ServiceDiscoveryResult(cursor);
 521		} catch (JSONException e) { /* result is still null */ }
 522
 523		cursor.close();
 524		return result;
 525	}
 526
 527	public void insertPresenceTemplate(PresenceTemplate template) {
 528		SQLiteDatabase db = this.getWritableDatabase();
 529		db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
 530	}
 531
 532	public List<PresenceTemplate> getPresenceTemplates() {
 533		ArrayList<PresenceTemplate> templates = new ArrayList<>();
 534		SQLiteDatabase db = this.getReadableDatabase();
 535		Cursor cursor = db.query(PresenceTemplate.TABELNAME,null,null,null,null,null,PresenceTemplate.LAST_USED+" desc");
 536		while (cursor.moveToNext()) {
 537			templates.add(PresenceTemplate.fromCursor(cursor));
 538		}
 539		cursor.close();
 540		return templates;
 541	}
 542
 543	public void deletePresenceTemplate(PresenceTemplate template) {
 544		Log.d(Config.LOGTAG,"deleting presence template with uuid "+template.getUuid());
 545		SQLiteDatabase db = this.getWritableDatabase();
 546		String where = PresenceTemplate.UUID+"=?";
 547		String[] whereArgs = {template.getUuid()};
 548		db.delete(PresenceTemplate.TABELNAME,where,whereArgs);
 549	}
 550
 551	public CopyOnWriteArrayList<Conversation> getConversations(int status) {
 552		CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
 553		SQLiteDatabase db = this.getReadableDatabase();
 554		String[] selectionArgs = {Integer.toString(status)};
 555		Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
 556				+ " where " + Conversation.STATUS + " = ? order by "
 557				+ Conversation.CREATED + " desc", selectionArgs);
 558		while (cursor.moveToNext()) {
 559			list.add(Conversation.fromCursor(cursor));
 560		}
 561		cursor.close();
 562		return list;
 563	}
 564
 565	public ArrayList<Message> getMessages(Conversation conversations, int limit) {
 566		return getMessages(conversations, limit, -1);
 567	}
 568
 569	public ArrayList<Message> getMessages(Conversation conversation, int limit,
 570										  long timestamp) {
 571		ArrayList<Message> list = new ArrayList<>();
 572		SQLiteDatabase db = this.getReadableDatabase();
 573		Cursor cursor;
 574		if (timestamp == -1) {
 575			String[] selectionArgs = {conversation.getUuid()};
 576			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 577					+ "=?", selectionArgs, null, null, Message.TIME_SENT
 578					+ " DESC", String.valueOf(limit));
 579		} else {
 580			String[] selectionArgs = {conversation.getUuid(),
 581					Long.toString(timestamp)};
 582			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 583							+ "=? and " + Message.TIME_SENT + "<?", selectionArgs,
 584					null, null, Message.TIME_SENT + " DESC",
 585					String.valueOf(limit));
 586		}
 587		if (cursor.getCount() > 0) {
 588			cursor.moveToLast();
 589			do {
 590				Message message = Message.fromCursor(cursor);
 591				message.setConversation(conversation);
 592				list.add(message);
 593			} while (cursor.moveToPrevious());
 594		}
 595		cursor.close();
 596		return list;
 597	}
 598
 599	public Iterable<Message> getMessagesIterable(final Conversation conversation) {
 600		return new Iterable<Message>() {
 601			@Override
 602			public Iterator<Message> iterator() {
 603				class MessageIterator implements Iterator<Message> {
 604					SQLiteDatabase db = getReadableDatabase();
 605					String[] selectionArgs = {conversation.getUuid()};
 606					Cursor cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 607							+ "=?", selectionArgs, null, null, Message.TIME_SENT
 608							+ " ASC", null);
 609
 610					public MessageIterator() {
 611						cursor.moveToFirst();
 612					}
 613
 614					@Override
 615					public boolean hasNext() {
 616						return !cursor.isAfterLast();
 617					}
 618
 619					@Override
 620					public Message next() {
 621						Message message = Message.fromCursor(cursor);
 622						cursor.moveToNext();
 623						return message;
 624					}
 625
 626					@Override
 627					public void remove() {
 628						throw new UnsupportedOperationException();
 629					}
 630				}
 631				return new MessageIterator();
 632			}
 633		};
 634	}
 635
 636	public Conversation findConversation(final Account account, final Jid contactJid) {
 637		SQLiteDatabase db = this.getReadableDatabase();
 638		String[] selectionArgs = {account.getUuid(),
 639				contactJid.toBareJid().toPreppedString() + "/%",
 640				contactJid.toBareJid().toPreppedString()
 641		};
 642		Cursor cursor = db.query(Conversation.TABLENAME, null,
 643				Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
 644						+ " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null);
 645		if (cursor.getCount() == 0) {
 646			cursor.close();
 647			return null;
 648		}
 649		cursor.moveToFirst();
 650		Conversation conversation = Conversation.fromCursor(cursor);
 651		cursor.close();
 652		return conversation;
 653	}
 654
 655	public void updateConversation(final Conversation conversation) {
 656		final SQLiteDatabase db = this.getWritableDatabase();
 657		final String[] args = {conversation.getUuid()};
 658		db.update(Conversation.TABLENAME, conversation.getContentValues(),
 659				Conversation.UUID + "=?", args);
 660	}
 661
 662	public List<Account> getAccounts() {
 663		SQLiteDatabase db = this.getReadableDatabase();
 664		return getAccounts(db);
 665	}
 666
 667	private List<Account> getAccounts(SQLiteDatabase db) {
 668		List<Account> list = new ArrayList<>();
 669		Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
 670				null, null);
 671		while (cursor.moveToNext()) {
 672			list.add(Account.fromCursor(cursor));
 673		}
 674		cursor.close();
 675		return list;
 676	}
 677
 678	public boolean updateAccount(Account account) {
 679		SQLiteDatabase db = this.getWritableDatabase();
 680		String[] args = {account.getUuid()};
 681		final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
 682		return rows == 1;
 683	}
 684
 685	public boolean deleteAccount(Account account) {
 686		SQLiteDatabase db = this.getWritableDatabase();
 687		String[] args = {account.getUuid()};
 688		final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
 689		return rows == 1;
 690	}
 691
 692	public boolean hasEnabledAccounts() {
 693		SQLiteDatabase db = this.getReadableDatabase();
 694		Cursor cursor = db.rawQuery("select count(" + Account.UUID + ")  from "
 695				+ Account.TABLENAME + " where not options & (1 <<1)", null);
 696		try {
 697			cursor.moveToFirst();
 698			int count = cursor.getInt(0);
 699			return (count > 0);
 700		} catch (SQLiteCantOpenDatabaseException e) {
 701			return true; // better safe than sorry
 702		} catch (RuntimeException e) {
 703			return true; // better safe than sorry
 704		} finally {
 705			if (cursor != null) {
 706				cursor.close();
 707			}
 708		}
 709	}
 710
 711	@Override
 712	public SQLiteDatabase getWritableDatabase() {
 713		SQLiteDatabase db = super.getWritableDatabase();
 714		db.execSQL("PRAGMA foreign_keys=ON;");
 715		return db;
 716	}
 717
 718	public void updateMessage(Message message) {
 719		SQLiteDatabase db = this.getWritableDatabase();
 720		String[] args = {message.getUuid()};
 721		db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
 722				+ "=?", args);
 723	}
 724
 725	public void updateMessage(Message message, String uuid) {
 726		SQLiteDatabase db = this.getWritableDatabase();
 727		String[] args = {uuid};
 728		db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
 729				+ "=?", args);
 730	}
 731
 732	public void readRoster(Roster roster) {
 733		SQLiteDatabase db = this.getReadableDatabase();
 734		Cursor cursor;
 735		String args[] = {roster.getAccount().getUuid()};
 736		cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null);
 737		while (cursor.moveToNext()) {
 738			roster.initContact(Contact.fromCursor(cursor));
 739		}
 740		cursor.close();
 741	}
 742
 743	public void writeRoster(final Roster roster) {
 744		final Account account = roster.getAccount();
 745		final SQLiteDatabase db = this.getWritableDatabase();
 746		db.beginTransaction();
 747		for (Contact contact : roster.getContacts()) {
 748			if (contact.getOption(Contact.Options.IN_ROSTER)) {
 749				db.insert(Contact.TABLENAME, null, contact.getContentValues());
 750			} else {
 751				String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
 752				String[] whereArgs = {account.getUuid(), contact.getJid().toPreppedString()};
 753				db.delete(Contact.TABLENAME, where, whereArgs);
 754			}
 755		}
 756		db.setTransactionSuccessful();
 757		db.endTransaction();
 758		account.setRosterVersion(roster.getVersion());
 759		updateAccount(account);
 760	}
 761
 762	public void deleteMessagesInConversation(Conversation conversation) {
 763		SQLiteDatabase db = this.getWritableDatabase();
 764		String[] args = {conversation.getUuid()};
 765		db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
 766	}
 767
 768	public Pair<Long, String> getLastMessageReceived(Account account) {
 769		Cursor cursor = null;
 770		try {
 771			SQLiteDatabase db = this.getReadableDatabase();
 772			String sql = "select messages.timeSent,messages.serverMsgId from accounts join conversations on accounts.uuid=conversations.accountUuid join messages on conversations.uuid=messages.conversationUuid where accounts.uuid=? and (messages.status=0 or messages.carbon=1 or messages.serverMsgId not null) order by messages.timesent desc limit 1";
 773			String[] args = {account.getUuid()};
 774			cursor = db.rawQuery(sql, args);
 775			if (cursor.getCount() == 0) {
 776				return null;
 777			} else {
 778				cursor.moveToFirst();
 779				return new Pair<>(cursor.getLong(0), cursor.getString(1));
 780			}
 781		} catch (Exception e) {
 782			return null;
 783		} finally {
 784			if (cursor != null) {
 785				cursor.close();
 786			}
 787		}
 788	}
 789
 790	public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
 791		String SQL = "select messages.timeSent from accounts join conversations on accounts.uuid=conversations.accountUuid join messages on conversations.uuid=messages.conversationUuid where accounts.uuid=? and messages.axolotl_fingerprint=? order by messages.timesent desc limit 1";
 792		String[] args = {account.getUuid(), fingerprint};
 793		Cursor cursor = getReadableDatabase().rawQuery(SQL,args);
 794		long time;
 795		if (cursor.moveToFirst()) {
 796			time = cursor.getLong(0);
 797		} else {
 798			time = 0;
 799		}
 800		cursor.close();
 801		return time;
 802	}
 803
 804	public Pair<Long,String> getLastClearDate(Account account) {
 805		SQLiteDatabase db = this.getReadableDatabase();
 806		String[] columns = {Conversation.ATTRIBUTES};
 807		String selection = Conversation.ACCOUNT + "=?";
 808		String[] args = {account.getUuid()};
 809		Cursor cursor = db.query(Conversation.TABLENAME,columns,selection,args,null,null,null);
 810		long maxClearDate = 0;
 811		while (cursor.moveToNext()) {
 812			try {
 813				final JSONObject jsonObject = new JSONObject(cursor.getString(0));
 814				maxClearDate = Math.max(maxClearDate, jsonObject.getLong(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY));
 815			} catch (Exception e) {
 816				//ignored
 817			}
 818		}
 819		cursor.close();
 820		return new Pair<>(maxClearDate,null);
 821	}
 822
 823	private Cursor getCursorForSession(Account account, AxolotlAddress contact) {
 824		final SQLiteDatabase db = this.getReadableDatabase();
 825		String[] selectionArgs = {account.getUuid(),
 826				contact.getName(),
 827				Integer.toString(contact.getDeviceId())};
 828		return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
 829				null,
 830				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 831						+ SQLiteAxolotlStore.NAME + " = ? AND "
 832						+ SQLiteAxolotlStore.DEVICE_ID + " = ? ",
 833				selectionArgs,
 834				null, null, null);
 835	}
 836
 837	public SessionRecord loadSession(Account account, AxolotlAddress contact) {
 838		SessionRecord session = null;
 839		Cursor cursor = getCursorForSession(account, contact);
 840		if (cursor.getCount() != 0) {
 841			cursor.moveToFirst();
 842			try {
 843				session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
 844			} catch (IOException e) {
 845				cursor.close();
 846				throw new AssertionError(e);
 847			}
 848		}
 849		cursor.close();
 850		return session;
 851	}
 852
 853	public List<Integer> getSubDeviceSessions(Account account, AxolotlAddress contact) {
 854		final SQLiteDatabase db = this.getReadableDatabase();
 855		return getSubDeviceSessions(db, account, contact);
 856	}
 857
 858	private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, AxolotlAddress contact) {
 859		List<Integer> devices = new ArrayList<>();
 860		String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
 861		String[] selectionArgs = {account.getUuid(),
 862				contact.getName()};
 863		Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
 864				columns,
 865				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 866						+ SQLiteAxolotlStore.NAME + " = ?",
 867				selectionArgs,
 868				null, null, null);
 869
 870		while (cursor.moveToNext()) {
 871			devices.add(cursor.getInt(
 872					cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
 873		}
 874
 875		cursor.close();
 876		return devices;
 877	}
 878
 879	public boolean containsSession(Account account, AxolotlAddress contact) {
 880		Cursor cursor = getCursorForSession(account, contact);
 881		int count = cursor.getCount();
 882		cursor.close();
 883		return count != 0;
 884	}
 885
 886	public void storeSession(Account account, AxolotlAddress contact, SessionRecord session) {
 887		SQLiteDatabase db = this.getWritableDatabase();
 888		ContentValues values = new ContentValues();
 889		values.put(SQLiteAxolotlStore.NAME, contact.getName());
 890		values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
 891		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
 892		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
 893		db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
 894	}
 895
 896	public void deleteSession(Account account, AxolotlAddress contact) {
 897		SQLiteDatabase db = this.getWritableDatabase();
 898		deleteSession(db, account, contact);
 899	}
 900
 901	private void deleteSession(SQLiteDatabase db, Account account, AxolotlAddress contact) {
 902		String[] args = {account.getUuid(),
 903				contact.getName(),
 904				Integer.toString(contact.getDeviceId())};
 905		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
 906				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 907						+ SQLiteAxolotlStore.NAME + " = ? AND "
 908						+ SQLiteAxolotlStore.DEVICE_ID + " = ? ",
 909				args);
 910	}
 911
 912	public void deleteAllSessions(Account account, AxolotlAddress contact) {
 913		SQLiteDatabase db = this.getWritableDatabase();
 914		String[] args = {account.getUuid(), contact.getName()};
 915		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
 916				SQLiteAxolotlStore.ACCOUNT + "=? AND "
 917						+ SQLiteAxolotlStore.NAME + " = ?",
 918				args);
 919	}
 920
 921	private Cursor getCursorForPreKey(Account account, int preKeyId) {
 922		SQLiteDatabase db = this.getReadableDatabase();
 923		String[] columns = {SQLiteAxolotlStore.KEY};
 924		String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
 925		Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
 926				columns,
 927				SQLiteAxolotlStore.ACCOUNT + "=? AND "
 928						+ SQLiteAxolotlStore.ID + "=?",
 929				selectionArgs,
 930				null, null, null);
 931
 932		return cursor;
 933	}
 934
 935	public PreKeyRecord loadPreKey(Account account, int preKeyId) {
 936		PreKeyRecord record = null;
 937		Cursor cursor = getCursorForPreKey(account, preKeyId);
 938		if (cursor.getCount() != 0) {
 939			cursor.moveToFirst();
 940			try {
 941				record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
 942			} catch (IOException e) {
 943				throw new AssertionError(e);
 944			}
 945		}
 946		cursor.close();
 947		return record;
 948	}
 949
 950	public boolean containsPreKey(Account account, int preKeyId) {
 951		Cursor cursor = getCursorForPreKey(account, preKeyId);
 952		int count = cursor.getCount();
 953		cursor.close();
 954		return count != 0;
 955	}
 956
 957	public void storePreKey(Account account, PreKeyRecord record) {
 958		SQLiteDatabase db = this.getWritableDatabase();
 959		ContentValues values = new ContentValues();
 960		values.put(SQLiteAxolotlStore.ID, record.getId());
 961		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
 962		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
 963		db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
 964	}
 965
 966	public void deletePreKey(Account account, int preKeyId) {
 967		SQLiteDatabase db = this.getWritableDatabase();
 968		String[] args = {account.getUuid(), Integer.toString(preKeyId)};
 969		db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
 970				SQLiteAxolotlStore.ACCOUNT + "=? AND "
 971						+ SQLiteAxolotlStore.ID + "=?",
 972				args);
 973	}
 974
 975	private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
 976		SQLiteDatabase db = this.getReadableDatabase();
 977		String[] columns = {SQLiteAxolotlStore.KEY};
 978		String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
 979		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
 980				columns,
 981				SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
 982				selectionArgs,
 983				null, null, null);
 984
 985		return cursor;
 986	}
 987
 988	public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
 989		SignedPreKeyRecord record = null;
 990		Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
 991		if (cursor.getCount() != 0) {
 992			cursor.moveToFirst();
 993			try {
 994				record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
 995			} catch (IOException e) {
 996				throw new AssertionError(e);
 997			}
 998		}
 999		cursor.close();
1000		return record;
1001	}
1002
1003	public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1004		List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1005		SQLiteDatabase db = this.getReadableDatabase();
1006		String[] columns = {SQLiteAxolotlStore.KEY};
1007		String[] selectionArgs = {account.getUuid()};
1008		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1009				columns,
1010				SQLiteAxolotlStore.ACCOUNT + "=?",
1011				selectionArgs,
1012				null, null, null);
1013
1014		while (cursor.moveToNext()) {
1015			try {
1016				prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1017			} catch (IOException ignored) {
1018			}
1019		}
1020		cursor.close();
1021		return prekeys;
1022	}
1023
1024	public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1025		Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1026		int count = cursor.getCount();
1027		cursor.close();
1028		return count != 0;
1029	}
1030
1031	public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1032		SQLiteDatabase db = this.getWritableDatabase();
1033		ContentValues values = new ContentValues();
1034		values.put(SQLiteAxolotlStore.ID, record.getId());
1035		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1036		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1037		db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1038	}
1039
1040	public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1041		SQLiteDatabase db = this.getWritableDatabase();
1042		String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1043		db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1044				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1045						+ SQLiteAxolotlStore.ID + "=?",
1046				args);
1047	}
1048
1049	private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1050		final SQLiteDatabase db = this.getReadableDatabase();
1051		return getIdentityKeyCursor(db, account, name, own);
1052	}
1053
1054	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1055		return getIdentityKeyCursor(db, account, name, own, null);
1056	}
1057
1058	private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1059		final SQLiteDatabase db = this.getReadableDatabase();
1060		return getIdentityKeyCursor(db, account, fingerprint);
1061	}
1062
1063	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1064		return getIdentityKeyCursor(db, account, null, null, fingerprint);
1065	}
1066
1067	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1068		String[] columns = {SQLiteAxolotlStore.TRUST,
1069				SQLiteAxolotlStore.ACTIVE,
1070				SQLiteAxolotlStore.LAST_ACTIVATION,
1071				SQLiteAxolotlStore.KEY};
1072		ArrayList<String> selectionArgs = new ArrayList<>(4);
1073		selectionArgs.add(account.getUuid());
1074		String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1075		if (name != null) {
1076			selectionArgs.add(name);
1077			selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1078		}
1079		if (fingerprint != null) {
1080			selectionArgs.add(fingerprint);
1081			selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1082		}
1083		if (own != null) {
1084			selectionArgs.add(own ? "1" : "0");
1085			selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1086		}
1087		Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1088				columns,
1089				selectionString,
1090				selectionArgs.toArray(new String[selectionArgs.size()]),
1091				null, null, null);
1092
1093		return cursor;
1094	}
1095
1096	public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1097		SQLiteDatabase db = getReadableDatabase();
1098		return loadOwnIdentityKeyPair(db, account);
1099	}
1100
1101	private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1102		String name = account.getJid().toBareJid().toPreppedString();
1103		IdentityKeyPair identityKeyPair = null;
1104		Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1105		if (cursor.getCount() != 0) {
1106			cursor.moveToFirst();
1107			try {
1108				identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1109			} catch (InvalidKeyException e) {
1110				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().toBareJid() + ", address: " + name);
1111			}
1112		}
1113		cursor.close();
1114
1115		return identityKeyPair;
1116	}
1117
1118	public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1119		return loadIdentityKeys(account, name, null);
1120	}
1121
1122	public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1123		Set<IdentityKey> identityKeys = new HashSet<>();
1124		Cursor cursor = getIdentityKeyCursor(account, name, false);
1125
1126		while (cursor.moveToNext()) {
1127			if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1128				continue;
1129			}
1130			try {
1131				String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1132				if (key != null) {
1133					identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1134				} else {
1135					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().toBareJid() + ", address: " + name);
1136				}
1137			} catch (InvalidKeyException e) {
1138				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().toBareJid() + ", address: " + name);
1139			}
1140		}
1141		cursor.close();
1142
1143		return identityKeys;
1144	}
1145
1146	public long numTrustedKeys(Account account, String name) {
1147		SQLiteDatabase db = getReadableDatabase();
1148		String[] args = {
1149				account.getUuid(),
1150				name,
1151				FingerprintStatus.Trust.TRUSTED.toString(),
1152				FingerprintStatus.Trust.VERIFIED.toString(),
1153				FingerprintStatus.Trust.VERIFIED_X509.toString()
1154		};
1155		return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1156				SQLiteAxolotlStore.ACCOUNT + " = ?"
1157						+ " AND " + SQLiteAxolotlStore.NAME + " = ?"
1158						+ " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " +SQLiteAxolotlStore.TRUST +" = ?)"
1159						+ " AND " +SQLiteAxolotlStore.ACTIVE + " > 0",
1160				args
1161		);
1162	}
1163
1164	private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1165		SQLiteDatabase db = this.getWritableDatabase();
1166		ContentValues values = new ContentValues();
1167		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1168		values.put(SQLiteAxolotlStore.NAME, name);
1169		values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1170		values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1171		values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1172		values.putAll(status.toContentValues());
1173		String where = SQLiteAxolotlStore.ACCOUNT+"=? AND "+SQLiteAxolotlStore.NAME+"=? AND "+SQLiteAxolotlStore.FINGERPRINT+" =?";
1174		String[] whereArgs = {account.getUuid(),name,fingerprint};
1175		int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME,values,where,whereArgs);
1176		if (rows == 0) {
1177			db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1178		}
1179	}
1180
1181	public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1182		SQLiteDatabase db = this.getWritableDatabase();
1183		ContentValues values = new ContentValues();
1184		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1185		values.put(SQLiteAxolotlStore.NAME, name);
1186		values.put(SQLiteAxolotlStore.OWN, 0);
1187		values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1188		values.putAll(status.toContentValues());
1189		db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1190	}
1191
1192	public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1193		Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1194		final FingerprintStatus status;
1195		if (cursor.getCount() > 0) {
1196			cursor.moveToFirst();
1197			status = FingerprintStatus.fromCursor(cursor);
1198		} else {
1199			status = null;
1200		}
1201		cursor.close();
1202		return status;
1203	}
1204
1205	public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1206		SQLiteDatabase db = this.getWritableDatabase();
1207		return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1208	}
1209
1210	private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1211		String[] selectionArgs = {
1212				account.getUuid(),
1213				fingerprint
1214		};
1215		int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1216				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1217						+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1218				selectionArgs);
1219		return rows == 1;
1220	}
1221
1222	public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1223		SQLiteDatabase db = this.getWritableDatabase();
1224		String[] selectionArgs = {
1225				account.getUuid(),
1226				fingerprint
1227		};
1228		try {
1229			ContentValues values = new ContentValues();
1230			values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1231			return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1232					SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1233							+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1234					selectionArgs) == 1;
1235		} catch (CertificateEncodingException e) {
1236			Log.d(Config.LOGTAG, "could not encode certificate");
1237			return false;
1238		}
1239	}
1240
1241	public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1242		SQLiteDatabase db = this.getReadableDatabase();
1243		String[] selectionArgs = {
1244				account.getUuid(),
1245				fingerprint
1246		};
1247		String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1248		String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1249		Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1250		if (cursor.getCount() < 1) {
1251			return null;
1252		} else {
1253			cursor.moveToFirst();
1254			byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1255			cursor.close();
1256			if (certificate == null || certificate.length == 0) {
1257				return null;
1258			}
1259			try {
1260				CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1261				return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1262			} catch (CertificateException e) {
1263				Log.d(Config.LOGTAG,"certificate exception "+e.getMessage());
1264				return null;
1265			}
1266		}
1267	}
1268
1269	public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1270		storeIdentityKey(account, name, false, identityKey.getFingerprint().replaceAll("\\s", ""), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1271	}
1272
1273	public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1274		storeIdentityKey(account, account.getJid().toBareJid().toPreppedString(), true, identityKeyPair.getPublicKey().getFingerprint().replaceAll("\\s", ""), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1275	}
1276
1277
1278	public void recreateAxolotlDb(SQLiteDatabase db) {
1279		Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1280		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1281		db.execSQL(CREATE_SESSIONS_STATEMENT);
1282		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1283		db.execSQL(CREATE_PREKEYS_STATEMENT);
1284		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1285		db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1286		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1287		db.execSQL(CREATE_IDENTITIES_STATEMENT);
1288	}
1289
1290	public void wipeAxolotlDb(Account account) {
1291		String accountName = account.getUuid();
1292		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1293		SQLiteDatabase db = this.getWritableDatabase();
1294		String[] deleteArgs = {
1295				accountName
1296		};
1297		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1298				SQLiteAxolotlStore.ACCOUNT + " = ?",
1299				deleteArgs);
1300		db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1301				SQLiteAxolotlStore.ACCOUNT + " = ?",
1302				deleteArgs);
1303		db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1304				SQLiteAxolotlStore.ACCOUNT + " = ?",
1305				deleteArgs);
1306		db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1307				SQLiteAxolotlStore.ACCOUNT + " = ?",
1308				deleteArgs);
1309	}
1310
1311	public boolean startTimeCountExceedsThreshold() {
1312		SQLiteDatabase db = this.getWritableDatabase();
1313		long cleanBeforeTimestamp = System.currentTimeMillis() - Config.FREQUENT_RESTARTS_DETECTION_WINDOW;
1314		db.execSQL("delete from "+START_TIMES_TABLE+" where timestamp < "+cleanBeforeTimestamp);
1315		ContentValues values = new ContentValues();
1316		values.put("timestamp",System.currentTimeMillis());
1317		db.insert(START_TIMES_TABLE,null,values);
1318		String[] columns = new String[]{"count(timestamp)"};
1319		Cursor cursor = db.query(START_TIMES_TABLE,columns,null,null,null,null,null);
1320		int count;
1321		if (cursor.moveToFirst()) {
1322			count = cursor.getInt(0);
1323		} else {
1324			count = 0;
1325		}
1326		cursor.close();
1327		Log.d(Config.LOGTAG,"start time counter reached "+count);
1328		return count >= Config.FREQUENT_RESTARTS_THRESHOLD;
1329	}
1330
1331	public void clearStartTimeCounter() {
1332		Log.d(Config.LOGTAG,"resetting start time counter");
1333		SQLiteDatabase db = this.getWritableDatabase();
1334		db.execSQL("delete from "+START_TIMES_TABLE);
1335	}
1336}