import { GENESIS_SLOT } from "@lodestar/params";
import { getBlockProposerSignatureSet } from "@lodestar/state-transition";
import { ssz } from "@lodestar/types";
import { BackfillSyncError, BackfillSyncErrorCode } from "./errors.js";
export function verifyBlockSequence(config, blocks, anchorRoot) {
    let nextRoot = anchorRoot;
    let nextAnchor = null;
    const verifiedBlocks = [];
    for (const block of blocks.reverse()) {
        const blockRoot = config.getForkTypes(block.message.slot).BeaconBlock.hashTreeRoot(block.message);
        if (!ssz.Root.equals(blockRoot, nextRoot)) {
            if (ssz.Root.equals(nextRoot, anchorRoot)) {
                throw new BackfillSyncError({ code: BackfillSyncErrorCode.NOT_ANCHORED });
            }
            return { nextAnchor, verifiedBlocks, error: BackfillSyncErrorCode.NOT_LINEAR };
        }
        verifiedBlocks.push(block);
        nextAnchor = { block: block, slot: block.message.slot, root: nextRoot };
        nextRoot = block.message.parentRoot;
    }
    return { nextAnchor, verifiedBlocks };
}
export async function verifyBlockProposerSignature(config, bls, blocks) {
    if (blocks.length === 1 && blocks[0].message.slot === GENESIS_SLOT)
        return;
    const signatures = blocks.reduce((sigs, block) => {
        // genesis block doesn't have valid signature
        if (block.message.slot !== GENESIS_SLOT)
            sigs.push(getBlockProposerSignatureSet(config, block));
        return sigs;
    }, []);
    if (!(await bls.verifySignatureSets(signatures, { batchable: true }))) {
        throw new BackfillSyncError({ code: BackfillSyncErrorCode.INVALID_SIGNATURE });
    }
}
//# sourceMappingURL=verify.js.map