"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GroupKeyManager = void 0;
const protocol_1 = require("@streamr/protocol");
const utils_1 = require("@streamr/utils");
const crypto_1 = __importDefault(require("crypto"));
const tsyringe_1 = require("tsyringe");
const Authentication_1 = require("../Authentication");
const Config_1 = require("../Config");
const DestroySignal_1 = require("../DestroySignal");
const events_1 = require("../events");
const uuid_1 = require("../utils/uuid");
const GroupKey_1 = require("./GroupKey");
const LitProtocolFacade_1 = require("./LitProtocolFacade");
const LocalGroupKeyStore_1 = require("./LocalGroupKeyStore");
const SubscriberKeyExchange_1 = require("./SubscriberKeyExchange");
let GroupKeyManager = class GroupKeyManager {
    subscriberKeyExchange;
    litProtocolFacade;
    localGroupKeyStore;
    config;
    authentication;
    eventEmitter;
    destroySignal;
    constructor(subscriberKeyExchange, litProtocolFacade, localGroupKeyStore, config, authentication, eventEmitter, destroySignal) {
        this.subscriberKeyExchange = subscriberKeyExchange;
        this.litProtocolFacade = litProtocolFacade;
        this.localGroupKeyStore = localGroupKeyStore;
        this.config = config;
        this.authentication = authentication;
        this.eventEmitter = eventEmitter;
        this.destroySignal = destroySignal;
    }
    async fetchKey(streamPartId, groupKeyId, publisherId) {
        const streamId = protocol_1.StreamPartIDUtils.getStreamID(streamPartId);
        // 1st try: local storage
        let groupKey = await this.localGroupKeyStore.get(groupKeyId, publisherId);
        if (groupKey !== undefined) {
            return groupKey;
        }
        // 2nd try: lit-protocol
        if (this.config.encryption.litProtocolEnabled) {
            groupKey = await this.litProtocolFacade.get(streamId, groupKeyId);
            if (groupKey !== undefined) {
                await this.localGroupKeyStore.set(groupKey.id, publisherId, groupKey.data);
                return groupKey;
            }
        }
        // 3rd try: Streamr key-exchange
        await this.subscriberKeyExchange.requestGroupKey(groupKeyId, publisherId, streamPartId);
        const groupKeyIds = await (0, utils_1.waitForEvent)(
        // TODO remove "as any" type casing in NET-889
        this.eventEmitter, 'storeEncryptionKeyToLocalStore', this.config.encryption.keyRequestTimeout, (storedGroupKeyId) => storedGroupKeyId === groupKeyId, this.destroySignal.abortSignal);
        groupKey = await this.localGroupKeyStore.get(groupKeyIds[0], publisherId);
        return groupKey;
    }
    async fetchLatestEncryptionKey(publisherId, streamId) {
        if (publisherId !== (await this.authentication.getAddress())) {
            throw new Error('storeKey: fetching latest encryption keys for other publishers not supported.');
        }
        const keyId = await this.localGroupKeyStore.getLatestEncryptionKeyId(publisherId, streamId);
        return keyId !== undefined ? this.localGroupKeyStore.get(keyId, publisherId) : undefined;
    }
    async storeKey(groupKey, publisherId, streamId) {
        if (publisherId !== (await this.authentication.getAddress())) { // TODO: unit test?
            throw new Error('storeKey: storing latest encryption keys for other publishers not supported.');
        }
        if (groupKey === undefined) {
            const keyData = crypto_1.default.randomBytes(32);
            // 1st try lit-protocol, if a key cannot be generated and stored, then generate group key locally
            if (this.config.encryption.litProtocolEnabled) {
                groupKey = await this.litProtocolFacade.store(streamId, keyData);
            }
            if (groupKey === undefined) {
                groupKey = new GroupKey_1.GroupKey((0, uuid_1.uuid)('GroupKey'), keyData);
            }
        }
        await this.localGroupKeyStore.set(groupKey.id, publisherId, groupKey.data);
        await this.localGroupKeyStore.setLatestEncryptionKeyId(groupKey.id, publisherId, streamId);
        return groupKey;
    }
    addKeyToLocalStore(groupKey, publisherId) {
        return this.localGroupKeyStore.set(groupKey.id, publisherId, groupKey.data);
    }
};
exports.GroupKeyManager = GroupKeyManager;
exports.GroupKeyManager = GroupKeyManager = __decorate([
    (0, tsyringe_1.scoped)(tsyringe_1.Lifecycle.ContainerScoped),
    __param(3, (0, tsyringe_1.inject)(Config_1.ConfigInjectionToken)),
    __param(4, (0, tsyringe_1.inject)(Authentication_1.AuthenticationInjectionToken)),
    __metadata("design:paramtypes", [SubscriberKeyExchange_1.SubscriberKeyExchange,
        LitProtocolFacade_1.LitProtocolFacade,
        LocalGroupKeyStore_1.LocalGroupKeyStore, Object, Object, events_1.StreamrClientEventEmitter,
        DestroySignal_1.DestroySignal])
], GroupKeyManager);
//# sourceMappingURL=GroupKeyManager.js.map