"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RegisterKeysCommand = void 0;
const lisk_sdk_1 = require("lisk-sdk");
const constants_1 = require("../constants");
const schemas_1 = require("../schemas");
const keysRegistered_1 = require("../events/keysRegistered");
const { address: { getAddressFromPublicKey }, } = lisk_sdk_1.cryptography;
const validator = lisk_sdk_1.validator.validator;
class RegisterKeysCommand extends lisk_sdk_1.BaseCommand {
    constructor() {
        super(...arguments);
        this.schema = schemas_1.registerKeysParamsSchema;
        this.invalidBlsKey = constants_1.INVALID_BLS_KEY;
    }
    addDependencies(validatorsMethod, posMethod) {
        this._validatorsMethod = validatorsMethod;
        this._posMethod = posMethod;
    }
    async verify(ctx) {
        const params = ctx.params;
        try {
            validator.validate(schemas_1.registerKeysParamsSchema, params);
        }
        catch (err) {
            return {
                status: lisk_sdk_1.VerifyStatus.FAIL,
                error: err,
            };
        }
        const validatorAddress = getAddressFromPublicKey(ctx.transaction.senderPublicKey);
        const validatorKeys = await this._validatorsMethod.getValidatorKeys(ctx.getMethodContext(), validatorAddress);
        if (Buffer.compare(validatorKeys.blsKey, this.invalidBlsKey) !== 0) {
            return {
                status: lisk_sdk_1.VerifyStatus.FAIL,
                error: new Error('Validator already has a registered BLS key.'),
            };
        }
        return { status: lisk_sdk_1.VerifyStatus.OK };
    }
    async execute(ctx) {
        const params = ctx.params;
        const validatorAddress = getAddressFromPublicKey(ctx.transaction.senderPublicKey);
        await this._validatorsMethod.setValidatorGeneratorKey(ctx.getMethodContext(), validatorAddress, params.generatorKey);
        await this._validatorsMethod.setValidatorBLSKey(ctx.getMethodContext(), validatorAddress, params.blsKey, params.proofOfPossession);
        const keysRegisteredEvent = this.events.get(keysRegistered_1.KeysRegisteredEvent);
        keysRegisteredEvent.log(ctx.getMethodContext(), {
            address: validatorAddress,
            generatorKey: params.generatorKey,
            blsKey: params.blsKey,
        });
        await this._posMethod.unbanValidator(ctx.getMethodContext(), validatorAddress);
    }
}
exports.RegisterKeysCommand = RegisterKeysCommand;
//# sourceMappingURL=register_keys.js.map