"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.selectNodesFromReadyList = exports.isNodeSelectedReadyList = exports.drainFinishedSyncingRequest = exports.addFinishedSyncing = exports.newSyncFinishedNodes = void 0;
const NodeList = __importStar(require("../../NodeList"));
const CycleChain = __importStar(require("../../CycleChain"));
const Context_1 = require("../../Context");
const nestedCounters_1 = require("../../../utils/nestedCounters");
const Context_2 = require("../../Context");
const logger_1 = require("../../../logger");
const Self_1 = require("../../Self");
//** List of synced nodes */
exports.newSyncFinishedNodes = new Map();
/**
 * Adds nodes to the local state synced node list.
 */
function addFinishedSyncing(finishedSyncRequest) {
    const node = NodeList.byIdOrder.find((node) => node.id === finishedSyncRequest.nodeId);
    // validate
    // lookup node by id in payload and use pubkey and compare to sig.owner
    const publicKeysMatch = (node?.publicKey || Context_1.crypto.keypair.publicKey) === finishedSyncRequest.sign.owner;
    if (!publicKeysMatch) {
        if (logger_1.logFlags.verbose)
            console.log(`addFinishedSyncing(): public key in addFinishedSyncing does not match public key of node`, finishedSyncRequest.nodeId);
        /* prettier-ignore */ nestedCounters_1.nestedCountersInstance.countEvent('syncFinished.ts', `addFinishedSyncing(): publicKeysMatch failed`);
        return {
            success: false,
            reason: 'public key in addFinishedSyncing does not match public key of node',
            fatal: false,
        };
    }
    // cycle number check
    const cycleNumber = CycleChain.getNewest().counter;
    if (cycleNumber !== finishedSyncRequest.cycleNumber) {
        if (logger_1.logFlags.console)
            console.log(`addFinishedSyncing(): cycleNumber in request does not match cycleNumber of node`, finishedSyncRequest.nodeId);
        /* prettier-ignore */ nestedCounters_1.nestedCountersInstance.countEvent('syncFinished.ts', `addFinishedSyncing(): cycleNumber match failed`);
        return {
            success: false,
            reason: `cycleNumber in request does not match cycleNumber of node`,
            fatal: false,
        };
    }
    // return false if already in local list
    if (exports.newSyncFinishedNodes.has(finishedSyncRequest.nodeId) === true) {
        if (logger_1.logFlags.console)
            console.log(`addFinishedSyncing(): Node already in newSyncFinishedNodes list`, finishedSyncRequest.nodeId);
        /* prettier-ignore */ nestedCounters_1.nestedCountersInstance.countEvent('syncFinished.ts', `addFinishedSyncing(): already in local list`);
        return {
            success: false,
            reason: `node has already submitted syncFinished request`,
            fatal: false,
        };
    }
    // return false if signature is invalid
    if (!Context_1.crypto.verify(finishedSyncRequest, finishedSyncRequest.sign.owner)) {
        if (logger_1.logFlags.console)
            console.log(`addFinishedSyncing(): signature invalid`, finishedSyncRequest.nodeId);
        /* prettier-ignore */ nestedCounters_1.nestedCountersInstance.countEvent('syncFinished.ts', `addFinishedSyncing(): signature invalid`);
        return {
            success: false,
            reason: 'verification of syncFinished request failed',
            fatal: false,
        };
    }
    /* prettier-ignore */ if (logger_1.logFlags.verbose)
        console.log(`addFinishedSyncing: ${finishedSyncRequest.nodeId} port:${node?.externalPort}`);
    exports.newSyncFinishedNodes.set(finishedSyncRequest.nodeId, finishedSyncRequest);
    /* prettier-ignore */ nestedCounters_1.nestedCountersInstance.countEvent('syncFinished.ts', `addFinishedSyncing(): success`);
    return {
        success: true,
        reason: `Node ${finishedSyncRequest.nodeId} added to syncFinishedNodesInfo map`,
        fatal: false,
    };
}
exports.addFinishedSyncing = addFinishedSyncing;
/**
 * Returns the list of new synced nodes info and empties the list.
 *
 * @returns SyncCompletedRequest[]
 */
function drainFinishedSyncingRequest() {
    const tmp = Array.from(exports.newSyncFinishedNodes.values());
    exports.newSyncFinishedNodes = new Map();
    return tmp;
}
exports.drainFinishedSyncingRequest = drainFinishedSyncingRequest;
/**
 * Determines if a node is among the first N nodes in the pre-sorted list `readyByTimeAndIdOrder` when in 'processing' mode,
 * or within the entire list in other modes. The list is sorted by `readyTimestamp`, with `ID` as a tiebreaker.
 *
 * @param nodeId The ID of the node to check.
 * @returns True if the node is among the first N ready nodes in 'processing' mode or in the entire list in other modes, false otherwise.
 */
function isNodeSelectedReadyList(nodeId) {
    const mode = CycleChain.getNewest().mode;
    // Adjust the list based on the mode
    const listToCheck = mode === 'processing'
        ? NodeList.readyByTimeAndIdOrder.slice(0, Context_2.config.p2p.allowActivePerCycle)
        : NodeList.readyByTimeAndIdOrder;
    // Check if nodeId is in listToCheck
    return listToCheck.some((readyNode) => readyNode.id === nodeId);
}
exports.isNodeSelectedReadyList = isNodeSelectedReadyList;
function selectNodesFromReadyList(mode) {
    if (mode === 'processing') {
        let nodesToAllowActive = Context_2.config.p2p.allowActivePerCycle;
        if (Context_2.config.p2p.activeRecoveryEnabled) {
            // check if we are below desired allow more nodes to join
            if (CycleChain.newest != null) {
                const active = CycleChain.newest.active;
                const desired = CycleChain.newest.desired;
                const deficit = desired - active;
                if (deficit > 0) {
                    // This code is rotation safe because if allowActivePerCycleRecover is set to 1
                    // and allowActivePerCycle is set to 1 we will have the same boost
                    const boost = Math.min(Context_2.config.p2p.allowActivePerCycleRecover, deficit);
                    // apply the boost
                    nodesToAllowActive = Math.max(nodesToAllowActive, boost);
                }
            }
        }
        if (Context_2.config.debug.readyNodeDelay > 0) {
            nestedCounters_1.nestedCountersInstance.countEvent('p2p', `selectNodesFromReadyList: only returning nodes from the ready list that were added at least ${Context_2.config.debug.readyNodeDelay} seconds ago`);
            return NodeList.readyByTimeAndIdOrder
                .slice(0, nodesToAllowActive)
                .filter((node) => CycleChain.newest.start >= node.readyTimestamp + Context_2.config.debug.readyNodeDelay);
        }
        return NodeList.readyByTimeAndIdOrder.slice(0, nodesToAllowActive);
    }
    else {
        if (mode === 'forming' && Self_1.isFirst && NodeList.activeByIdOrder.length === 0)
            return NodeList.readyByTimeAndIdOrder;
        if (Context_2.config.debug.readyNodeDelay > 0) {
            nestedCounters_1.nestedCountersInstance.countEvent('p2p', `selectNodesFromReadyList: only returning nodes from the ready list that were added at least ${Context_2.config.debug.readyNodeDelay} seconds ago`);
            return NodeList.readyByTimeAndIdOrder.filter((node) => CycleChain.newest.start >= node.readyTimestamp + Context_2.config.debug.readyNodeDelay);
        }
        return NodeList.readyByTimeAndIdOrder;
    }
}
exports.selectNodesFromReadyList = selectNodesFromReadyList;
//# sourceMappingURL=syncFinished.js.map