"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.PublisherKeyExchange = void 0;
const protocol_1 = require("@streamr/protocol");
const trackerless_network_1 = require("@streamr/trackerless-network");
const without_1 = __importDefault(require("lodash/without"));
const tsyringe_1 = require("tsyringe");
const Authentication_1 = require("../Authentication");
const NetworkNodeFacade_1 = require("../NetworkNodeFacade");
const MessageFactory_1 = require("../publish/MessageFactory");
const messageChain_1 = require("../publish/messageChain");
const StreamRegistry_1 = require("../registry/StreamRegistry");
const LoggerFactory_1 = require("../utils/LoggerFactory");
const validateStreamMessage_1 = require("../utils/validateStreamMessage");
const EncryptionUtil_1 = require("./EncryptionUtil");
const LocalGroupKeyStore_1 = require("./LocalGroupKeyStore");
/*
 * Sends group key responses
 */
let PublisherKeyExchange = class PublisherKeyExchange {
    networkNodeFacade;
    streamRegistry;
    store;
    authentication;
    logger;
    constructor(networkNodeFacade, streamRegistry, store, authentication, loggerFactory) {
        this.networkNodeFacade = networkNodeFacade;
        this.streamRegistry = streamRegistry;
        this.store = store;
        this.authentication = authentication;
        this.logger = loggerFactory.createLogger(module);
        networkNodeFacade.once('start', async () => {
            const node = await networkNodeFacade.getNode();
            node.addMessageListener((msg) => this.onMessage(msg));
            this.logger.debug('Started');
        });
    }
    async onMessage(request) {
        if (protocol_1.GroupKeyRequest.is(request)) {
            try {
                const authenticatedUser = await this.authentication.getAddress();
                const { recipient, requestId, rsaPublicKey, groupKeyIds } = (0, trackerless_network_1.convertBytesToGroupKeyRequest)(request.content);
                if (recipient === authenticatedUser) {
                    this.logger.debug('Handling group key request', { requestId });
                    await (0, validateStreamMessage_1.validateStreamMessage)(request, this.streamRegistry);
                    const keys = (0, without_1.default)(await Promise.all(groupKeyIds.map((id) => this.store.get(id, authenticatedUser))), undefined);
                    if (keys.length > 0) {
                        const response = await this.createResponse(keys, request.getStreamPartID(), rsaPublicKey, request.getPublisherId(), requestId);
                        const node = await this.networkNodeFacade.getNode();
                        await node.broadcast(response);
                        this.logger.debug('Handled group key request (found keys)', {
                            groupKeyIds: keys.map((k) => k.id).join(),
                            recipient: request.getPublisherId()
                        });
                    }
                    else {
                        this.logger.debug('Handled group key request (no keys found)', {
                            requestId,
                            recipient: request.getPublisherId()
                        });
                    }
                }
            }
            catch (err) {
                this.logger.debug('Failed to handle group key request', err);
            }
        }
    }
    async createResponse(keys, streamPartId, rsaPublicKey, recipient, requestId) {
        const encryptedGroupKeys = await Promise.all(keys.map((key) => {
            const encryptedGroupKey = EncryptionUtil_1.EncryptionUtil.encryptWithRSAPublicKey(key.data, rsaPublicKey);
            return new protocol_1.EncryptedGroupKey(key.id, encryptedGroupKey);
        }));
        const responseContent = new protocol_1.GroupKeyResponse({
            recipient,
            requestId,
            encryptedGroupKeys
        });
        const response = (0, MessageFactory_1.createSignedMessage)({
            messageId: new protocol_1.MessageID(protocol_1.StreamPartIDUtils.getStreamID(streamPartId), protocol_1.StreamPartIDUtils.getStreamPartition(streamPartId), Date.now(), 0, await this.authentication.getAddress(), (0, messageChain_1.createRandomMsgChainId)()),
            content: (0, trackerless_network_1.convertGroupKeyResponseToBytes)(responseContent),
            contentType: protocol_1.ContentType.BINARY,
            messageType: protocol_1.StreamMessageType.GROUP_KEY_RESPONSE,
            encryptionType: protocol_1.EncryptionType.NONE,
            authentication: this.authentication,
            signatureType: protocol_1.SignatureType.SECP256K1,
        });
        return response;
    }
};
exports.PublisherKeyExchange = PublisherKeyExchange;
exports.PublisherKeyExchange = PublisherKeyExchange = __decorate([
    (0, tsyringe_1.scoped)(tsyringe_1.Lifecycle.ContainerScoped),
    __param(3, (0, tsyringe_1.inject)(Authentication_1.AuthenticationInjectionToken)),
    __metadata("design:paramtypes", [NetworkNodeFacade_1.NetworkNodeFacade,
        StreamRegistry_1.StreamRegistry,
        LocalGroupKeyStore_1.LocalGroupKeyStore, Object, LoggerFactory_1.LoggerFactory])
], PublisherKeyExchange);
//# sourceMappingURL=PublisherKeyExchange.js.map