/** * Challenge responder: produce a response given a challenge + BlockStore. * * For MST challenges: generates MST proofs via generateMstProof. * For block-sample challenges: checks block availability and returns prefixes. */ import type { BlockStore } from "../../ipfs.js"; import type { StorageChallenge, StorageChallengeResponse, BlockResult, } from "./types.js"; import { DEFAULT_CHALLENGE_CONFIG } from "./types.js"; import { generateMstProof, type MstProof } from "../mst-proof.js"; /** * Produce a challenge response. * * Calls generateMstProof for MST challenges, checks block availability * and provides prefixes for block-sample challenges. */ export async function respondToChallenge( challenge: StorageChallenge, blockStore: BlockStore, responderDid: string, config?: { blockPrefixLength?: number }, ): Promise { const prefixLength = config?.blockPrefixLength ?? DEFAULT_CHALLENGE_CONFIG.blockPrefixLength; let mstProofs: MstProof[] | undefined; let blockResults: BlockResult[] | undefined; // Handle MST proof challenges if ( challenge.challengeType === "mst-proof" || challenge.challengeType === "combined" ) { mstProofs = []; for (const recordPath of challenge.recordPaths) { try { const proof = await generateMstProof( blockStore, challenge.commitCid, recordPath, ); mstProofs.push(proof); } catch { // If we can't generate a proof (missing blocks), add an empty proof mstProofs.push({ commitBlock: { cid: challenge.commitCid, bytes: new Uint8Array(0), }, nodes: [], recordCid: null, found: false, }); } } } // Handle block-sample challenges if ( challenge.challengeType === "block-sample" || challenge.challengeType === "combined" ) { if (challenge.blockCids) { blockResults = []; for (const cid of challenge.blockCids) { const bytes = await blockStore.getBlock(cid); if (bytes) { blockResults.push({ cid, available: true, prefix: bytes.slice(0, prefixLength), }); } else { blockResults.push({ cid, available: false, }); } } } } return { challengeId: challenge.id, responderDid, mstProofs, blockResults, respondedAt: new Date().toISOString(), }; }