"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyBook = void 0;
const interface_datastore_1 = require("interface-datastore");
const datastore_core_1 = require("datastore-core");
const threads_core_1 = require("@textile/threads-core");
const threads_crypto_1 = require("@textile/threads-crypto");
/**
 * Public and private keys are stored under the following db key pattern:
 *    /threads/keys/<b32 thread id no padding>/<b32 log id no padding>:(pub|priv)
 * Follow and read keys are stored under the following db key pattern:
 *    /threads/keys/<b32 thread id no padding>:(repl|read)
 */
const baseKey = new interface_datastore_1.Key('/thread/keys');
const getKey = (id, log, suffix) => {
    const idString = log.toB58String();
    return new interface_datastore_1.Key(id.toString()).child(new interface_datastore_1.Key(suffix ? `${idString}:${suffix}` : idString));
};
/**
 * KeyBook stores Thread/Log keys.
 */
class KeyBook {
    constructor(datastore) {
        this.datastore = datastore;
        this.datastore = new datastore_core_1.NamespaceDatastore(datastore, baseKey);
    }
    /**
     * pubKey retrieves the public key of a log.
     * @param id The Thread ID.
     * @param log The Log ID.
     */
    pubKey(id, log) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const key = yield this.datastore.get(getKey(id, log, 'pub'));
                return threads_crypto_1.keys.unmarshalPublicKey(key);
            }
            catch (err) {
                return;
            }
        });
    }
    /**
     * addPubKey adds a public key under a log.
     * @param id The Thread ID.
     * @param log The Log ID.
     * @param pubKey The public key from a symmetric key pair.
     */
    addPubKey(id, log, pubKey) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!log.equals(yield threads_core_1.LogID.fromPublicKey(pubKey))) {
                throw new Error('Public Key Mismatch');
            }
            const key = Buffer.from(pubKey.bytes);
            return this.datastore.put(getKey(id, log, 'pub'), key);
        });
    }
    /**
     * privKey retrieves the private key of a log.
     * @param id The Thread ID.
     * @param log The Log ID.
     */
    privKey(id, log) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const key = yield this.datastore.get(getKey(id, log, 'priv'));
                return threads_crypto_1.keys.unmarshalPrivateKey(key);
            }
            catch (err) {
                return;
            }
        });
    }
    /**
     * addPrivKey adds a private key under a log.
     * @param id The Thread ID.
     * @param log The Log ID.
     * @param privKey The private key from a symmetric key pair.
     */
    addPrivKey(id, log, privKey) {
        return __awaiter(this, void 0, void 0, function* () {
            const check = yield threads_core_1.LogID.fromPrivateKey(privKey);
            if (!log.equals(check)) {
                throw new Error('Private Key Mismatch');
            }
            const key = Buffer.from(privKey.bytes);
            return this.datastore.put(getKey(id, log, 'priv'), key);
        });
    }
    /**
     * readKey retrieves the read key of a log.
     * @param id The Thread ID.
     */
    readKey(id) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                return yield this.datastore.get(new interface_datastore_1.Key(id.toString()).child(new interface_datastore_1.Key('read')));
            }
            catch (err) {
                return;
            }
        });
    }
    /**
     * addReadKey adds a read key under a thread.
     * @param id The Thread ID.
     * @param key The asymmetric read key, of length 44 bytes.
     */
    addReadKey(id, key) {
        return this.datastore.put(new interface_datastore_1.Key(id.toString()).child(new interface_datastore_1.Key('read')), Buffer.from(key));
    }
    /**
     * serviceKey retrieves the replicator key of a thread.
     */
    serviceKey(id) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                return yield this.datastore.get(new interface_datastore_1.Key(id.toString()).child(new interface_datastore_1.Key('repl')));
            }
            catch (err) {
                return;
            }
        });
    }
    /**
     * addServiceKey adds a replicator key under a given thread.
     * @param id The Thread ID.
     * @param key The asymmetric replicator key, of length 44 bytes.
     */
    addServiceKey(id, key) {
        return this.datastore.put(new interface_datastore_1.Key(id.toString()).child(new interface_datastore_1.Key('repl')), Buffer.from(key));
    }
    threads() {
        var e_1, _a;
        return __awaiter(this, void 0, void 0, function* () {
            const threads = new Set();
            try {
                for (var _b = __asyncValues(this.datastore.query({
                    prefix: baseKey.toString(),
                    keysOnly: true,
                })), _c; _c = yield _b.next(), !_c.done;) {
                    const { key } = _c.value;
                    // We only care about threads we can replicate
                    if (key.name() === 'repl') {
                        threads.add(threads_core_1.ThreadID.fromString(key.parent().toString()));
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return threads;
        });
    }
    logs(id) {
        var e_2, _a;
        return __awaiter(this, void 0, void 0, function* () {
            const logs = new Set();
            const q = { keysOnly: true, prefix: id.toString() };
            try {
                for (var _b = __asyncValues(this.datastore.query(q)), _c; _c = yield _b.next(), !_c.done;) {
                    const { key } = _c.value;
                    if (['priv', 'pub'].includes(key.name())) {
                        const log = threads_core_1.LogID.fromB58String(key.type());
                        logs.add(log);
                    }
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
                }
                finally { if (e_2) throw e_2.error; }
            }
            return logs;
        });
    }
    /**
     * clearThreadKeys deletes all keys under a given thread.
     * @param id Thread ID.
     */
    clearThreadKeys(id) {
        var e_3, _a;
        return __awaiter(this, void 0, void 0, function* () {
            const batch = this.datastore.batch();
            try {
                for (var _b = __asyncValues(this.datastore.query({
                    prefix: baseKey.child(new interface_datastore_1.Key(id.toString())).toString(),
                    keysOnly: true,
                })), _c; _c = yield _b.next(), !_c.done;) {
                    const { key } = _c.value;
                    batch.delete(key);
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
                }
                finally { if (e_3) throw e_3.error; }
            }
            return batch.commit();
        });
    }
    /**
     * clearLogKeys deletes all keys under a given log.
     * @param id Thread ID.
     * @param log: Log ID.
     */
    clearLogKeys(id, log) {
        var e_4, _a;
        return __awaiter(this, void 0, void 0, function* () {
            const batch = this.datastore.batch();
            try {
                for (var _b = __asyncValues(this.datastore.query({
                    prefix: getKey(id, log).toString(),
                    keysOnly: true,
                })), _c; _c = yield _b.next(), !_c.done;) {
                    const { key } = _c.value;
                    batch.delete(key);
                }
            }
            catch (e_4_1) { e_4 = { error: e_4_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
                }
                finally { if (e_4) throw e_4.error; }
            }
            return batch.commit();
        });
    }
    close() {
        return this.datastore.close();
    }
}
exports.KeyBook = KeyBook;
//# sourceMappingURL=keybook.js.map