Skip to content

Conversation

@Forostovec
Copy link

@Forostovec Forostovec commented Nov 17, 2025

Refactor customHasher in common/src/utils/hash.ts to accept Array<string | bigint | number> and normalize inputs once to bigint[], eliminating repeated conversions. Replace the object-wrapped per-round input structure with a simple bigint[][] to reduce allocations and property lookups. Update packBytesAndPoseidon to pass the bigint[] from packBytesArray directly into customHasher, removing the bigint→string→bigint round-trip and the redundant .toString() call. These changes preserve the public API behavior, keep tests compatible with string inputs used by circom formatting, and reduce allocation pressure and runtime overhead in hashing hot paths.


Note

Refactors hashing utilities to accept mixed input types, normalize once to bigint[], use block-based Poseidon rounds, and remove redundant string conversions.

  • common/src/utils/hash.ts
    • customHasher now accepts Array<string | bigint | number> and normalizes inputs once to bigint[].
    • Replaces per-round object structures with bigint[][] blocks; computes Poseidon rounds via poseidon16 and aggregates with flexiblePoseidon.
    • Updates packBytesAndPoseidon to pass the packed array directly to customHasher, removing string conversions and extra .toString().

Written by Cursor Bugbot for commit 9e25c95. This will update automatically on new commits. Configure here.

Summary by CodeRabbit

  • Refactor
    • Enhanced hash utility with optimized block processing approach
    • Extended input format compatibility for improved flexibility

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 17, 2025

Walkthrough

The customHasher function signature was updated to accept mixed-type inputs (string | bigint | number) instead of only strings, with internal refactoring to convert all inputs to BigInt and implement 16-element block processing for multi-block hashing operations.

Changes

Cohort / File(s) Summary
Hash utility refactoring
common/src/utils/hash.ts
Updated customHasher signature to accept Array<string | bigint | number> instead of string[]. Refactored internal logic to convert inputs to BigInt, implement multi-block hashing with 16-element block arrays, and update packBytesAndPoseidon to pass packed arrays directly without string mapping.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Areas requiring extra attention:

  • Cryptographic correctness: Verify the 16-element block processing approach produces identical hashes to the prior implementation for backward compatibility
  • Type safety: Ensure all callers of customHasher are compatible with the new mixed-type signature and handle edge cases appropriately
  • Input validation: Confirm bounds checking and rounding calculations work correctly with the new BigInt-based length calculations
  • Block array construction: Validate the 2D blocks array initialization and filling logic maintains algorithm integrity

Poem

🔐 Blocks align in hexadecimal grace,
BigInts dancing through hashing space,
Sixteen elements, a tighter embrace,
Types now flexible, keeping the pace,
Poseidon smiles at the refactored trace. ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: optimizing customHasher inputs and removing unnecessary allocations through refactoring to accept bigint/number types and eliminating redundant conversions.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining why this PR is needed, why this solution was chosen, and what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 03e471c and 9e25c95.

📒 Files selected for processing (1)
  • common/src/utils/hash.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
common/src/**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

common/src/**/*.{ts,tsx,js,jsx}: Review shared utilities for:

  • Reusability and modular design
  • Type safety and error handling
  • Side-effect management
  • Documentation and naming clarity

Files:

  • common/src/utils/hash.ts
🧬 Code graph analysis (1)
common/src/utils/hash.ts (1)
common/index.ts (2)
  • customHasher (116-116)
  • flexiblePoseidon (117-117)
🔇 Additional comments (1)
common/src/utils/hash.ts (1)

188-191: LGTM! Optimization eliminates redundant conversions.

The change correctly removes the bigint → string → bigint round-trip by passing the bigint[] from packBytesArray directly to customHasher. This reduces allocations and achieves the PR's optimization goal while preserving behavior.

Comment on lines +44 to +47
export function customHasher(pubKeyFormatted: Array<string | bigint | number>) {
const asBigints: bigint[] = pubKeyFormatted.map((v) =>
typeof v === 'bigint' ? v : BigInt(v)
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add input validation and error handling for BigInt conversion.

The BigInt() conversion can throw TypeError for invalid inputs (non-numeric strings, undefined, null, etc.). Since customHasher is a public exported utility, unvalidated inputs could cause runtime crashes without helpful error messages.

Consider adding validation:

 export function customHasher(pubKeyFormatted: Array<string | bigint | number>) {
+  if (!Array.isArray(pubKeyFormatted) || pubKeyFormatted.length === 0) {
+    throw new Error('customHasher requires a non-empty array');
+  }
+  
+  try {
     const asBigints: bigint[] = pubKeyFormatted.map((v) =>
       typeof v === 'bigint' ? v : BigInt(v)
     );
+  } catch (error) {
+    throw new Error(`Invalid input for customHasher: ${error instanceof Error ? error.message : 'Cannot convert to BigInt'}`);
+  }
🤖 Prompt for AI Agents
In common/src/utils/hash.ts around lines 44 to 47, the direct BigInt conversion
can throw for invalid inputs; add input validation and error handling before
mapping: first verify pubKeyFormatted is an array and not null/undefined, then
for each element explicitly check for null/undefined and for allowed types
(bigint, number, numeric-string) and reject or coerce others; wrap the BigInt
conversion in a try/catch (or validate numeric-string with a regexp) and throw a
clear, descriptive TypeError that includes the offending value and its index so
callers get actionable errors instead of uncaught exceptions.

@transphorm
Copy link
Member

@seshanthS or @Nesopie could you review this pull request?

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.

2 participants