Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/blockchain/adapters/cascade-port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,14 @@ export class BlockchainActionAdapter implements CascadeChainPort {
);
}

// LEP-5 SVC params — zero means use defaults
const svcChallengeCount = parseInt(params.svc_challenge_count, 10) || 0;
const svcMinChunksForChallenge = parseInt(params.svc_min_chunks_for_challenge, 10) || 0;

return {
max_raptor_q_symbols: maxRaptorQSymbols,
svc_challenge_count: svcChallengeCount,
svc_min_chunks_for_challenge: svcMinChunksForChallenge,
};
}

Expand Down Expand Up @@ -212,6 +218,7 @@ export class BlockchainActionAdapter implements CascadeChainPort {
rq_ids_ic: metadata.rq_ids_ic,
signatures: metadata.signatures,
public: metadata.public,
...(metadata.availability_commitment ? { availability_commitment: metadata.availability_commitment } : {}),
}),
price: priceAmount+"ulume",
expirationTime: input.expirationTime,
Expand Down
2 changes: 2 additions & 0 deletions src/blockchain/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ class RpcActionQuery implements ActionQuery {
fee_base: params?.baseActionFee?.amount ?? "0",
fee_per_kb: params?.feePerKbyte?.amount ?? "0",
max_raptor_q_symbols: params?.maxRaptorQSymbols?.toString() ?? "0",
svc_challenge_count: params?.svcChallengeCount?.toString() ?? "0",
svc_min_chunks_for_challenge: params?.svcMinChunksForChallenge?.toString() ?? "0",
};
}

Expand Down
4 changes: 4 additions & 0 deletions src/blockchain/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ export interface ActionParams {
fee_per_kb: string;
/** Maximum number of RaptorQ symbols allowed */
max_raptor_q_symbols: string;
/** LEP-5: Number of chunks to challenge during SVC (0 = default 8) */
svc_challenge_count: string;
/** LEP-5: Minimum chunks for SVC (0 = default 4) */
svc_min_chunks_for_challenge: string;
}

/**
Expand Down
25 changes: 21 additions & 4 deletions src/cascade/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,14 +229,31 @@ export class SNApiClient {
* ```
*/
async getTaskStatus(taskId: string): Promise<TaskStatus> {
// Prefer the versioned path; fall back to legacy/non-versioned path on 404
// `/status` is SSE on sn-api-server and can block when polled via fetch text.
// Use `/history` for polling and return the latest status entry.
try {
return await this.http.get(`/api/v1/actions/cascade/tasks/${taskId}/status`);
const history = await this.http.get<Array<Record<string, unknown>>>(`/api/v1/actions/cascade/tasks/${taskId}/history`);
if (Array.isArray(history) && history.length > 0) {
return history[history.length - 1] as unknown as TaskStatus;
}
} catch (err) {
if (err instanceof HttpError && err.statusCode === 404) {
if (!(err instanceof HttpError && err.statusCode === 404)) {
throw err;
}
const legacyHistory = await this.http.get<Array<Record<string, unknown>>>(`/api/actions/cascade/tasks/${taskId}/history`);
if (Array.isArray(legacyHistory) && legacyHistory.length > 0) {
return legacyHistory[legacyHistory.length - 1] as unknown as TaskStatus;
}
}

// Fallback to explicit status endpoint for deployments where it is plain JSON.
try {
return await this.http.get(`/api/v1/actions/cascade/tasks/${taskId}/status`);
} catch (statusErr) {
if (statusErr instanceof HttpError && statusErr.statusCode === 404) {
return this.http.get(`/api/actions/cascade/tasks/${taskId}/status`);
}
throw err;
throw statusErr;
}
}

Expand Down
207 changes: 207 additions & 0 deletions src/cascade/commitment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
/**
* LEP-5 Availability Commitment - Merkle tree construction and challenge index derivation.
*
* This module implements the client-side commitment logic for the Storage
* Verification Challenge (SVC). It builds a BLAKE3 Merkle tree over file chunks,
* derives deterministic challenge indices from the root, and produces an
* AvailabilityCommitment that gets submitted on-chain during cascade registration.
*
* Must produce identical commitments to the Go implementation in
* supernode/pkg/cascadekit/commitment.go.
*
* @module cascade/commitment
*/

import { blake3HashBytes } from '../internal/hash';
import type { AvailabilityCommitment } from '../codegen/lumera/action/v1/metadata';
import { HashAlgo } from '../codegen/lumera/action/v1/metadata';

/** Default chunk size: 256 KiB */
export const DEFAULT_CHUNK_SIZE = 262144;

/** Minimum number of bytes for commitment (below this, skip SVC) */
export const MIN_TOTAL_SIZE = 4;

/** Commitment type string matching the Go constant */
export const COMMITMENT_TYPE = "lep5/chunk-merkle/v1";

/** Default SVC challenge count (matches chain default) */
export const DEFAULT_SVC_CHALLENGE_COUNT = 8;

/** Default minimum chunks for challenge (matches chain default) */
export const DEFAULT_SVC_MIN_CHUNKS_FOR_CHALLENGE = 4;

/**
* Select the chunk size for a given file.
* Starts at DEFAULT_CHUNK_SIZE and halves until there are at least minChunks chunks.
*/
export function selectChunkSize(fileSize: number, minChunks: number): number {
let chunkSize = DEFAULT_CHUNK_SIZE;
while (chunkSize > 1 && Math.ceil(fileSize / chunkSize) < minChunks) {
chunkSize = Math.floor(chunkSize / 2);
}
return chunkSize;
}

/**
* Split file bytes into chunks of the given size.
*/
export function chunkBytes(data: Uint8Array, chunkSize: number): Uint8Array[] {
const chunks: Uint8Array[] = [];
for (let offset = 0; offset < data.length; offset += chunkSize) {
chunks.push(data.subarray(offset, Math.min(offset + chunkSize, data.length)));
}
return chunks;
}

/**
* Hash a leaf node: BLAKE3(0x00 || index_be32 || data)
* Must match lumera/x/action/v1/merkle.HashLeaf
*/
export async function hashLeaf(index: number, data: Uint8Array): Promise<Uint8Array> {
const buf = new Uint8Array(1 + 4 + data.length);
buf[0] = 0x00; // leaf domain separator
buf[1] = (index >>> 24) & 0xff;
buf[2] = (index >>> 16) & 0xff;
buf[3] = (index >>> 8) & 0xff;
buf[4] = index & 0xff;
buf.set(data, 5);
return blake3HashBytes(buf);
}

/**
* Hash an internal node: BLAKE3(0x01 || left || right)
* Must match lumera/x/action/v1/merkle.HashNode
*/
export async function hashNode(left: Uint8Array, right: Uint8Array): Promise<Uint8Array> {
const buf = new Uint8Array(1 + left.length + right.length);
buf[0] = 0x01; // internal node domain separator
buf.set(left, 1);
buf.set(right, 1 + left.length);
return blake3HashBytes(buf);
}

/**
* Build a Merkle tree from leaf hashes.
* Returns all levels: tree[0] = leaves, tree[last] = [root].
*/
export async function buildTree(leafHashes: Uint8Array[]): Promise<Uint8Array[][]> {
if (leafHashes.length === 0) {
throw new Error("cannot build tree from zero leaves");
}

const levels: Uint8Array[][] = [leafHashes];
let current = leafHashes;

while (current.length > 1) {
const next: Uint8Array[] = [];
for (let i = 0; i < current.length; i += 2) {
if (i + 1 < current.length) {
next.push(await hashNode(current[i], current[i + 1]));
} else {
// Odd node: promote to next level
next.push(current[i]);
}
}
levels.push(next);
current = next;
}

return levels;
}

/**
* Derive deterministic challenge indices from the Merkle root.
* Uses BLAKE3(root || uint32be(counter)) mod numChunks.
* Must match supernode/pkg/cascadekit/commitment.go:deriveSimpleIndices
*/
export async function deriveIndices(
root: Uint8Array,
numChunks: number,
challengeCount: number
): Promise<number[]> {
const indices: number[] = [];
const seen = new Set<number>();
let counter = 0;

while (indices.length < challengeCount && indices.length < numChunks) {
// BLAKE3(root || uint32be(counter))
const buf = new Uint8Array(root.length + 4);
buf.set(root, 0);
buf[root.length] = (counter >>> 24) & 0xff;
buf[root.length + 1] = (counter >>> 16) & 0xff;
buf[root.length + 2] = (counter >>> 8) & 0xff;
buf[root.length + 3] = counter & 0xff;

const h = await blake3HashBytes(buf);

// Use first 8 bytes as uint64 mod numChunks
// DataView for big-endian reading
const view = new DataView(h.buffer, h.byteOffset, h.byteLength);
const hi32 = view.getUint32(0, false); // big-endian
const lo32 = view.getUint32(4, false);
// Compute (hi32 * 2^32 + lo32) mod numChunks using BigInt for precision
const val = (BigInt(hi32) << 32n) | BigInt(lo32);
const idx = Number(val % BigInt(numChunks));

if (!seen.has(idx)) {
seen.add(idx);
indices.push(idx);
}
counter++;

// Safety: avoid infinite loop if numChunks < challengeCount
if (counter > challengeCount * 100) {
break;
}
}

return indices;
}

/**
* Build an AvailabilityCommitment from file bytes.
*
* @param fileBytes - Raw file content
* @param challengeCount - Number of challenge indices (from chain params, default 8)
* @param minChunks - Minimum chunks for SVC (from chain params, default 4)
* @returns The commitment (or undefined if file is too small) and the Merkle tree levels
*/
export async function buildCommitment(
fileBytes: Uint8Array,
challengeCount: number = DEFAULT_SVC_CHALLENGE_COUNT,
minChunks: number = DEFAULT_SVC_MIN_CHUNKS_FOR_CHALLENGE,
): Promise<{ commitment: AvailabilityCommitment; tree: Uint8Array[][] } | undefined> {
if (fileBytes.length < MIN_TOTAL_SIZE) {
return undefined;
}

const chunkSize = selectChunkSize(fileBytes.length, minChunks);
const chunks = chunkBytes(fileBytes, chunkSize);
const numChunks = chunks.length;

// Hash all leaves
const leafHashes: Uint8Array[] = [];
for (let i = 0; i < chunks.length; i++) {
leafHashes.push(await hashLeaf(i, chunks[i]));
}

// Build tree
const tree = await buildTree(leafHashes);
const root = tree[tree.length - 1][0];

// Derive challenge indices
const challengeIndices = await deriveIndices(root, numChunks, challengeCount);

const commitment: AvailabilityCommitment = {
commitmentType: COMMITMENT_TYPE,
hashAlgo: HashAlgo.HASH_ALGO_BLAKE3,
chunkSize,
totalSize: BigInt(fileBytes.length),
numChunks,
root,
challengeIndices,
};

return { commitment, tree };
}
12 changes: 12 additions & 0 deletions src/cascade/ports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,18 @@ export interface CascadeActionParams {
* Used for layout ID derivation in LEP-1.
*/
max_raptor_q_symbols: number;

/**
* LEP-5: Number of chunks to challenge during SVC.
* Zero means use default (8).
*/
svc_challenge_count: number;

/**
* LEP-5: Minimum chunks required for SVC.
* Zero means use default (4).
*/
svc_min_chunks_for_challenge: number;
}

/**
Expand Down
53 changes: 45 additions & 8 deletions src/cascade/uploader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ import { toBase64, toCanonicalJsonBytes } from '../internal/encoding';
import { createSingleBlockLayout, generateIds, buildIndexFile } from '../wasm/lep1';
import type { UniversalSigner, ArbitrarySignResponse } from '../wallets/signer';
import { createDefaultSignaturePrompter } from '../wallets/prompter';
import { buildCommitment, DEFAULT_SVC_CHALLENGE_COUNT, DEFAULT_SVC_MIN_CHUNKS_FOR_CHALLENGE } from './commitment';
import type { AvailabilityCommitment } from '../codegen/lumera/action/v1/metadata';

export type CascadeSignatureKind = "layout" | "index" | "auth";

Expand Down Expand Up @@ -237,7 +239,9 @@ export class CascadeUploader {
// Step 1: Get action params from blockchain
const actionParams = await this.chainPort.getActionParams();
const rq_ids_max = actionParams.max_raptor_q_symbols;
console.debug('CascadeUploader.registerAction actionParams', { actionParams });
const svcChallengeCount = actionParams.svc_challenge_count || DEFAULT_SVC_CHALLENGE_COUNT;
const svcMinChunks = actionParams.svc_min_chunks_for_challenge || DEFAULT_SVC_MIN_CHUNKS_FOR_CHALLENGE;
console.debug('CascadeUploader.registerAction actionParams', { actionParams, svcChallengeCount, svcMinChunks });

// Step 2: Generate random initial counter for layout ID derivation
const rq_ids_ic = Math.floor(Math.random() * rq_ids_max);
Expand Down Expand Up @@ -302,6 +306,18 @@ export class CascadeUploader {
const indexWithSignature = `${indexFileB64}.${indexSignatureResponse.signature}`;
console.debug('CascadeUploader.registerAction indexWithSignature', { indexWithSignature });

// Step 7b: Build LEP-5 availability commitment (Merkle tree over file chunks)
let availabilityCommitment: AvailabilityCommitment | undefined;
const commitmentResult = await buildCommitment(fileBytes, svcChallengeCount, svcMinChunks);
if (commitmentResult) {
availabilityCommitment = commitmentResult.commitment;
console.debug('CascadeUploader.registerAction built availability commitment', {
chunkSize: availabilityCommitment.chunkSize,
numChunks: availabilityCommitment.numChunks,
challengeIndices: availabilityCommitment.challengeIndices,
});
}

// Step 8: Prepare auth_signature for upload
const authSignatureResponse = await this.requestSignature(
"auth",
Expand All @@ -313,14 +329,35 @@ export class CascadeUploader {
console.debug('CascadeUploader.registerAction authSignature', { authSignature });

// Step 9: Register the action on-chain
const msg: Record<string, unknown> = {
data_hash: dataHash,
file_name: params.fileName,
rq_ids_ic,
signatures: indexWithSignature,
public: params.isPublic,
};
if (availabilityCommitment) {
msg.availability_commitment = {
commitment_type: availabilityCommitment.commitmentType,
hash_algo: availabilityCommitment.hashAlgo,
chunk_size: availabilityCommitment.chunkSize,
total_size: (() => {
const v = availabilityCommitment.totalSize;
if (typeof v === "bigint") {
if (v > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new Error(`availability_commitment.total_size exceeds Number.MAX_SAFE_INTEGER: ${v.toString()}`);
}
return Number(v);
}
return v;
})(),
num_chunks: availabilityCommitment.numChunks,
root: Array.from(availabilityCommitment.root),
challenge_indices: availabilityCommitment.challengeIndices,
};
}
Comment on lines +339 to +358
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This availability_commitment is attached to msg here, but BlockchainActionAdapter.requestActionTx (cascade-port.ts lines 215-221) hardcodes exactly five fields when serializing the metadata into JSON.stringify: data_hash, file_name, rq_ids_ic, signatures, public. The availability_commitment key is silently dropped and never reaches the chain. The adapter's JSON.stringify call needs to be updated to forward this field as well, otherwise the entire commitment computation is wasted.

Fix it with Roo Code or mention @roomote and request a fix.

const txOutcome = await this.chainPort.requestActionTx({
msg: {
data_hash: dataHash,
file_name: params.fileName,
rq_ids_ic,
signatures: indexWithSignature,
public: params.isPublic,
},
msg,
expirationTime: params.expirationTime,
txPrompter: params.txPrompter,
}, fileBytes.length);
Expand Down
Loading