import { computeEpochAtSlot } from "@lodestar/state-transition";
import { toRootHex } from "@lodestar/utils";
import { getSlotFromSignedBeaconBlockSerialized } from "../../../util/sszBytes.js";
export async function* onBeaconBlocksByRoot(requestBody, chain, db) {
    for (const blockRoot of requestBody) {
        const root = blockRoot;
        const summary = chain.forkChoice.getBlock(root);
        let blockBytes = null;
        // finalized block has summary in forkchoice but it stays in blockArchive db
        if (summary) {
            blockBytes = await db.block.getBinary(root);
        }
        let slot = undefined;
        if (!blockBytes) {
            const blockEntry = await db.blockArchive.getBinaryEntryByRoot(root);
            if (blockEntry) {
                slot = blockEntry.key;
                blockBytes = blockEntry.value;
            }
        }
        if (blockBytes) {
            if (slot === undefined) {
                const slotFromBytes = getSlotFromSignedBeaconBlockSerialized(blockBytes);
                if (slotFromBytes === null) {
                    throw Error(`Invalid block bytes for block root ${toRootHex(root)}`);
                }
                slot = slotFromBytes;
            }
            yield {
                data: blockBytes,
                boundary: chain.config.getForkBoundaryAtEpoch(computeEpochAtSlot(slot)),
            };
        }
    }
}
//# sourceMappingURL=beaconBlocksByRoot.js.map