Skip to content

feat: add functionality to encrypt a u64 vector#853

Merged
ctrlc03 merged 4 commits into
devfrom
feat/encrypt-u64-vector
Oct 16, 2025
Merged

feat: add functionality to encrypt a u64 vector#853
ctrlc03 merged 4 commits into
devfrom
feat/encrypt-u64-vector

Conversation

@ctrlc03

@ctrlc03 ctrlc03 commented Oct 15, 2025

Copy link
Copy Markdown
Collaborator

Add vector encryption function in bfv_helpers, wasm and enclave sdk. related to #687

Summary by CodeRabbit

Release Notes

  • New Features
    • Added vector encryption support for BFV protocol, enabling encryption of multiple values in a single operation.
    • Introduced verifiable vector encryption with zero-knowledge proof generation for encrypted data validation.
    • New SDK methods for vector encryption workflows with automatic public inputs extraction.

@ctrlc03 ctrlc03 requested a review from cedoor October 15, 2025 20:37
@vercel

vercel Bot commented Oct 15, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
crisp Ready Ready Preview Comment Oct 16, 2025 11:19am
enclave-docs Ready Ready Preview Comment Oct 16, 2025 11:19am

@coderabbitai

coderabbitai Bot commented Oct 15, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Vector-based BFV encryption is extended across the stack: new functions (bfv_encrypt_v64, bfv_verifiable_encrypt_v64) are added in Rust helpers, exposed via WebAssembly bindings, and surfaced through the TypeScript SDK with corresponding test coverage. A workspace dependency is updated for the CRISP example.

Changes

Cohort / File(s) Summary
Rust BFV Helpers
crates/bfv-helpers/src/client.rs
Added bfv_encrypt_v64() for BFV vector encryption and bfv_verifiable_encrypt_v64() for verifiable vector encryption with circuit inputs generation; includes unit tests validating decryption correctness.
WebAssembly Bindings
crates/wasm/src/lib.rs
Added bfv_encrypt_vector() and bfv_verifiable_encrypt_vector() that wrap the new Rust v64 helpers for WASM exposure, delegating to underlying implementations and mapping errors to JsValue.
TypeScript SDK
packages/enclave-sdk/src/enclave-sdk.ts
Added three public methods: encryptVector(), encryptVectorAndGenerateInputs(), and encryptVectorAndGenProof() for BFV vector encryption workflows; imported new WASM bindings and EncryptedValueAndPublicInputs type.
TypeScript Types
packages/enclave-sdk/src/types.ts
Introduced new public interface EncryptedValueAndPublicInputs containing encryptedVector (Uint8Array) and publicInputs (Object) fields.
Tests
packages/enclave-sdk/tests/sdk.test.ts
Added two new test cases for vector encryption and vector encryption with proof generation, validating output types and sizes.
Configuration
examples/CRISP/sdk/package.json
Updated @enclave-e3/sdk dependency from "^0.1.5" to "workspace:\*" for local workspace resolution.

Sequence Diagram

sequenceDiagram
    participant Client
    participant SDK as TypeScript SDK
    participant WASM
    participant BFVHelper as BFV Helper (Rust)
    
    rect rgb(200, 220, 255)
    Note over Client,BFVHelper: Vector Encryption Flow
    Client->>SDK: encryptVector(data, publicKey)
    SDK->>WASM: bfv_encrypt_vector(data, publicKey, ...)
    WASM->>BFVHelper: bfv_encrypt_v64(data, publicKey, ...)
    BFVHelper->>BFVHelper: Deserialize pubkey
    BFVHelper->>BFVHelper: Encode plaintext
    BFVHelper->>BFVHelper: Encrypt vector
    BFVHelper-->>WASM: Vec<u8> (ciphertext)
    WASM-->>SDK: Uint8Array
    SDK-->>Client: Uint8Array
    end
    
    rect rgb(220, 255, 220)
    Note over Client,BFVHelper: Verifiable Encryption Flow
    Client->>SDK: encryptVectorAndGenProof(data, publicKey, circuit)
    SDK->>WASM: bfv_verifiable_encrypt_vector(data, publicKey, ...)
    WASM->>BFVHelper: bfv_verifiable_encrypt_v64(data, publicKey, ...)
    BFVHelper->>BFVHelper: Encrypt extended
    BFVHelper->>BFVHelper: Compute validation vectors
    BFVHelper->>BFVHelper: Generate circuit inputs (JSON)
    BFVHelper-->>WASM: VerifiableEncryptionResult
    WASM-->>SDK: Vec<JsValue>
    SDK->>SDK: Parse circuit inputs
    SDK->>SDK: generateProof(circuit, inputs)
    SDK-->>Client: VerifiableEncryptionResult
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Changes follow a consistent pattern of extending existing single-value encryption functions to vector variants across three layers (Rust, WASM, TypeScript). While the spread is moderate, the additions are mostly parallel implementations with homogeneous logic density and straightforward error handling. Tests validate core functionality adequately.

Possibly related PRs

  • feat: move wasm-crypto to the sdk #635: Extends the same BFV helper and WASM surfaces by adding single-value verifiable encryption (bfv_verifiable_encrypt_u64), establishing the pattern that this PR extends to vector operations.

Suggested reviewers

  • ryardley
  • auryn-macmillan
  • hmzakhalid

Poem

🐰 Vectors now flutter through encryption's gate,
From Rust to WASM, the data translates,
TypeScript calls out in harmonious refrain,
Verifiable proofs flow through the chain,
One number, then many—the pattern's complete!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "feat: add functionality to encrypt a u64 vector" directly and accurately summarizes the primary change across this changeset. The changes span multiple files (bfv-helpers, wasm, and enclave-sdk) but all converge on a single cohesive objective: adding vector-based encryption capabilities for u64 data types. The title is concise, specific, and uses proper semantic commit messaging, making it clear to reviewers that this PR introduces new vector encryption functionality without introducing any misleading or off-topic description.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Comment thread crates/bfv-helpers/src/client.rs
Comment thread crates/bfv-helpers/src/client.rs Outdated
Comment thread packages/enclave-sdk/tests/sdk.test.ts Outdated
cedoor
cedoor previously approved these changes Oct 16, 2025

@cedoor cedoor left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

utACK

Comment thread packages/enclave-sdk/src/enclave-sdk.ts
@cedoor

cedoor commented Oct 16, 2025

Copy link
Copy Markdown
Contributor

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Oct 16, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
packages/enclave-sdk/src/types.ts (1)

316-330: Tighten typing and fix doc wording

  • It returns public inputs, not a proof.
  • Avoid Object; use Record<string, unknown> (or a concrete schema).

Apply:

-/**
- * The result of encrypting a value and generating a proof
- */
+/**
+ * Result of encrypting a vector and producing circuit public inputs
+ */
 export interface EncryptedValueAndPublicInputs {
@@
-  publicInputs: Object;
+  publicInputs: Record<string, unknown>;
 }

Optional: consider harmonizing field names across types (e.g., use ciphertext instead of mixing encryptedVector/encryptedVote) to reduce confusion.

🧹 Nitpick comments (6)
examples/CRISP/sdk/package.json (1)

41-41: Avoid publishing with workspace: dependency*

"workspace:*" is not publishable to npm. This example has a publish script; prevent accidental publish or pin a real version.

Suggested patch to mark the example package as private:

 {
   "name": "@enclave/crisp-sdk",
   "version": "0.0.1",
   "type": "module",
+  "private": true,
   "files": [
     "dist"
   ],
packages/enclave-sdk/tests/sdk.test.ts (1)

53-60: Fix typos and avoid brittle size assertion

  • Spelling: "vector" and "environment".
  • Don’t pin ciphertext size; assert non‑empty instead.

Apply:

-it("should encrypt a vecor of numbers without crashing in a node environent", async () => {
+it("should encrypt a vector of numbers without crashing in a node environment", async () => {
@@
-  expect(value.length).to.equal(27_674);
+  expect(value.length).to.be.greaterThan(0);
@@
-it("should encrypt a vector and generate a proof without crashing in a node environent", async () => {
+it("should encrypt a vector and generate a proof without crashing in a node environment", async () => {

Also applies to: 62-72

crates/wasm/src/lib.rs (2)

42-70: Docstring nit: not “default params”

These functions take caller‑provided params. Suggest updating wording to avoid confusion.

-/// A function to encrypt a Vec<u64> value using BFV and default params.
+/// Encrypt a Vec<u64> using BFV with provided parameters.
@@
-/// * `moduli` - Modulus for BFV parameters
+/// * `moduli` - Modulus for BFV parameters (single modulus)

127-142: Docstring nit: clarify params and returns

Same as above; also clarify the two return elements’ meaning.

-/// A function to encrypt a Vec<u64> value using BFV and default params and
-/// generate circuit inputs for Greco
+/// Encrypt a Vec<u64> using BFV (with provided parameters) and
+/// generate circuit inputs for Greco.
@@
-/// Returns a `Result<Vec<JsValue>, JsValue>` containing the encrypted data, circuit inputs and any errors.
+/// Returns `[encrypted_ciphertext_bytes, circuit_inputs_json]` as `Vec<JsValue>`.
crates/bfv-helpers/src/client.rs (2)

58-98: Docstring corrections and minor API polish

  • “Vector of moduli” -> single‑element array [u64; 1].
  • Error list includes input‑validation vectors, which don’t apply here.
-/// * `moduli` - Vector of moduli for BFV parameters
+/// * `moduli` - Single‑element array of moduli for BFV parameters
@@
-/// - Input validation vector computation fails
+/// - (n/a for non‑verifiable variant)

Optional: accept impl AsRef<[u64]> instead of Vec<u64> to avoid unnecessary allocations.


191-233: Rename votedata and fix docs

Use neutral naming and correct docs to reflect Vec<u64> and actual Result type.

Apply:

-pub fn bfv_verifiable_encrypt_v64(
-    vote: Vec<u64>,
+pub fn bfv_verifiable_encrypt_v64(
+    data: Vec<u64>,
@@
-    let plaintext = Plaintext::try_encode(&vote, Encoding::poly(), &params)
+    let plaintext = Plaintext::try_encode(&data, Encoding::poly(), &params)
         .map_err(|e| anyhow!("Error encoding plaintext: {}", e))?;

Doc fixes:

-/// Verifiably encrypt a u64 using BFV homomorphic encryption and generate circuit inputs
+/// Verifiably encrypt a Vec<u64> using BFV and generate circuit inputs
@@
-/// * `data` - The value to encrypt (u64)
+/// * `data` - The values to encrypt (Vec<u64>)
@@
-/// * `Result<VerifiableEncryptionResult, String>` - Contains encrypted u64 and circuit inputs for ZKP
+/// * `Result<VerifiableEncryptionResult>` - Contains encrypted data and circuit inputs for ZKP

Optional: consider renaming encrypted_vote in VerifiableEncryptionResult to ciphertext for consistency across layers.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0a96b8e and 9d86f47.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • crates/bfv-helpers/src/client.rs (4 hunks)
  • crates/wasm/src/lib.rs (3 hunks)
  • examples/CRISP/sdk/package.json (1 hunks)
  • packages/enclave-sdk/src/enclave-sdk.ts (3 hunks)
  • packages/enclave-sdk/src/types.ts (1 hunks)
  • packages/enclave-sdk/tests/sdk.test.ts (1 hunks)
🧰 Additional context used
🪛 Biome (2.1.2)
packages/enclave-sdk/src/enclave-sdk.ts

[error] 219-225: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Safe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 227-227: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Safe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 229-229: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Safe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 253-259: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Safe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 261-261: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Safe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

🔇 Additional comments (3)
crates/bfv-helpers/src/client.rs (1)

262-288: LGTM: vector encrypt/verifiable tests

Happy path decryption checks look good and cover both variants.

Also applies to: 312-338

packages/enclave-sdk/src/enclave-sdk.ts (2)

37-37: LGTM!

The new imports for vector encryption functionality are correctly structured and necessary for the new methods.

Also applies to: 41-41, 43-43


143-166: LGTM!

The encryptVector method correctly follows the established pattern from encryptNumber, properly initializes WASM, and passes the protocol parameters to the underlying BFV encryption function.

Comment thread packages/enclave-sdk/src/enclave-sdk.ts
Comment thread packages/enclave-sdk/src/enclave-sdk.ts
@ctrlc03 ctrlc03 force-pushed the feat/encrypt-u64-vector branch from b14916b to e1ad867 Compare October 16, 2025 09:37
@vercel vercel Bot temporarily deployed to Preview – enclave-docs October 16, 2025 09:37 Inactive
@vercel vercel Bot temporarily deployed to Preview – crisp October 16, 2025 09:37 Inactive
@ctrlc03 ctrlc03 requested review from cedoor and ryardley October 16, 2025 09:52
@ctrlc03 ctrlc03 self-assigned this Oct 16, 2025
@ctrlc03 ctrlc03 enabled auto-merge (squash) October 16, 2025 11:22
@ctrlc03 ctrlc03 merged commit e9a8b9b into dev Oct 16, 2025
23 checks passed
@ctrlc03 ctrlc03 deleted the feat/encrypt-u64-vector branch October 16, 2025 11:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants