TypeScript
Software Design: Functions over Comments

by Benny Neugebauer

public async deserialize(payload: SerializedCryptobox) {
  await this.deleteData();
  await this.importIdentity(payload.identity);
  await this.importPreKeys(payload.prekeys);
}

private async deleteData(): Promise <void> {
  this.cachedSessions = new LRUCache(DEFAULT_CAPACITY);
  this.identity = undefined;
  this.lastResortPreKey = undefined;
  this.queues = new LRUCache < PriorityQueue > (DEFAULT_CAPACITY);
  await this.store.delete_all();
}

private async importIdentity(payload: string): Promise <void> {
  const identityBuffer = Decoder.fromBase64(payload).asBytes.buffer;
  const identity = ProteusKeys.IdentityKeyPair.deserialise(identityBuffer);
  await this.save_identity(identity);
}

private async importPreKeys(payload: string[]): Promise <void> {
  const preKeys = payload.prekeys.map(preKey => {
    const preKeyBuffer = Decoder.fromBase64(preKey).asBytes.buffer;
    const proteusPreKey = ProteusKeys.PreKey.deserialise(preKeyBuffer);
    if (proteusPreKey.key_id === ProteusKeys.PreKey.MAX_PREKEY_ID) {
      this.lastResortPreKey = proteusPreKey;
    }
    return proteusPreKey;
  });
  await this.store.save_prekeys(preKeys);
}

public async deserialize(payload: SerializedCryptobox) {
  // Delete Data
  this.cachedSessions = new LRUCache(DEFAULT_CAPACITY);
  this.identity = undefined;
  this.lastResortPreKey = undefined;
  this.queues = new LRUCache < PriorityQueue > (DEFAULT_CAPACITY);
  await this.store.delete_all();

  // Import Identity
  const identityBuffer = Decoder.fromBase64(payload.identity).asBytes.buffer;
  const identity = ProteusKeys.IdentityKeyPair.deserialise(identityBuffer);
  await this.save_identity(identity);

  // Import PreKeys
  const preKeys = payload.prekeys.map(preKey => {
    const preKeyBuffer = Decoder.fromBase64(preKey).asBytes.buffer;
    const proteusPreKey = ProteusKeys.PreKey.deserialise(preKeyBuffer);
    if (proteusPreKey.key_id === ProteusKeys.PreKey.MAX_PREKEY_ID) {
      this.lastResortPreKey = proteusPreKey;
    }
    return proteusPreKey;
  });
  await this.store.save_prekeys(preKeys);
}