Skip to content

Conversation

@cwilvx
Copy link
Contributor

@cwilvx cwilvx commented Jun 9, 2025

Refactor signature verification & signing, node identity and other cryptography modules to work with the unified crypto module.

Summary by CodeRabbit

  • New Features

    • Introduced support for post-quantum cryptography (PQC) identities, including batch addition/removal and verification.
    • Added explicit handling for multiple signature algorithms and unified cryptographic identity management.
    • Extended transaction and identity models to store additional signature and address fields.
  • Improvements

    • Refactored all cryptographic operations to use a unified, asynchronous API supporting multiple algorithms.
    • Enhanced transaction validation, signing, and verification to support new signature formats and PQC.
    • Updated consensus and networking routines to streamline identity and signature handling, improving security and performance.
  • Bug Fixes

    • Improved existence checks for user identities in the database.
    • Fixed minor logic and formatting issues in identity and transaction management.
  • Chores

    • Updated dependencies and example environment variable templates.
    • Improved documentation and type definitions for identity structures.
    • Removed deprecated or redundant code related to consensus secretary management.

cwilvx added 26 commits May 7, 2025 14:46
+ refactor tx validation signature validation
+ refactor validation signatures
+ delete old secretary manager class
+ refactor
- Introduced methods for adding and removing PQC identities in GCRIdentityRoutines.
- Implemented PQC payload verification in IdentityManager.
- Updated handleIdentityRequest to support PQC identity assignments and removals.
- Added validation for adding and removing PQC identities, ensuring proper data structure and existence checks.
- Updated StoredIdentities type to include PQC identities structure.
- Improved error handling for missing or duplicate identities during operations.
- Refactored the `verifyWeb2Proof` function to include error handling and improved success messaging.
- Updated `GCRIdentityRoutines` to handle identities as objects, including address, signature, public key, and timestamp.
- Modified `IdentityManager` to accept the sender's ed25519 address for payload verification.
- Adjusted `handleIdentityRequest` to correctly process transaction data and sender information.
- Improved type definitions for stored identities to accommodate new structure.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 9, 2025

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

This update introduces a comprehensive refactor of cryptographic operations throughout the codebase, transitioning from direct Ed25519 key usage and synchronous cryptography to a unified, asynchronous API (ucrypto) with explicit signing algorithm handling. It also adds support for post-quantum cryptographic (PQC) identities, restructures transaction and identity data models, and updates consensus and networking layers to use the new cryptographic abstractions.

Changes

File(s) / Path(s) Change Summary
.env.example Added template for Twitter and GitHub credentials.
.eslintrc.cjs Relaxed naming convention to allow leading/trailing underscores.
package.json Updated dependencies: @kynesyslabs/demosdk and @the-convocation/twitter-scraper.
run Changed directory removal to use password-piped sudo for non-interactive cleaning.
src/features/incentive/PointSystem.ts Improved variable naming and logging for identity handling.
src/features/web2/Web2RequestManager.ts
src/features/web2/handleWeb2.ts
src/features/web2/dahr/DAHR.ts
Refactored to use async unified crypto for signing/verification; updated method signatures.
src/index.ts Initialized unified crypto identity; logs and saves public key using new API.
src/libs/abstraction/index.ts
src/libs/abstraction/web2/github.ts
src/libs/abstraction/web2/parsers.ts
src/libs/abstraction/web2/twitter.ts
Refactored proof parsing and verification to use signature type and unified crypto.
src/libs/blockchain/chain.ts Genesis block now uses dynamic signing algorithm and new signature format.
src/libs/blockchain/gcr/gcr_routines/GCRIdentityRoutines.ts
src/libs/blockchain/gcr/gcr_routines/identityManager.ts
src/libs/blockchain/gcr/gcr_routines/index.ts
Added PQC identity routines, enhanced XM identity storage, and improved existence checks.
src/libs/blockchain/mempool.ts
src/libs/blockchain/routines/validateTransaction.ts
src/libs/blockchain/transaction.ts
Major refactor: async crypto ops, multi-algorithm signature support, new transaction fields, and enhanced validation.
src/libs/blockchain/types/confirmation.ts Confirmation.signature now includes type and data fields.
src/libs/consensus/v2/PoRBFT.ts Removed unused isInShard function.
src/libs/consensus/v2/routines/broadcastBlockHash.ts
src/libs/consensus/v2/routines/createBlock.ts
src/libs/consensus/v2/routines/manageProposeBlockHash.ts
Updated block signing and verification to async unified crypto; streamlined public key usage.
src/libs/consensus/v2/routines/secretary.ts Entire Secretary class and logic removed.
src/libs/consensus/v2/types/secretaryManager.ts Removed signature-based authentication; now uses public key checks and process exit on unauthorized access.
src/libs/identity/identity.ts Simplified async return in getPublicIP.
src/libs/network/endpointHandlers.ts
src/libs/network/manageExecution.ts
src/libs/network/manageGCRRoutines.ts
src/libs/network/manageHelloPeer.ts
src/libs/network/manageNodeCall.ts
src/libs/network/routines/nodecalls/getPeerlist.ts
src/libs/network/routines/transactions/handleIdentityRequest.ts
src/libs/network/server_rpc.ts
Refactored all network handlers and routines to use async unified crypto, updated method signatures, and propagated sender identity.
src/libs/peer/Peer.ts
src/libs/peer/PeerManager.ts
src/libs/peer/routines/getPeerIdentity.ts
Peer management and authentication now use unified crypto and updated signature formats.
src/libs/utils/demostdlib/deriveMempoolOperation.ts Transaction creation uses async signing and new key references.
src/model/entities/Mempool.ts
src/model/entities/Transactions.ts
Added ed25519_signature and from_ed25519_address columns to transaction entities.
src/model/entities/types/IdentityTypes.ts Introduced detailed interfaces for XM and PQC identities; expanded identity storage types.
src/utilities/sharedState.ts Shared state now manages signing algorithm, keypair, and public key hex accessor.

Sequence Diagram(s)

sequenceDiagram
    participant NodeA as Node A
    participant NodeB as Node B
    participant ucrypto as Unified Crypto

    NodeA->>ucrypto: sign(message, signingAlgorithm)
    ucrypto-->>NodeA: signature { type, data }

    NodeA->>NodeB: send { message, signature: { type, data }, publicKey }

    NodeB->>ucrypto: verify({ algorithm, message, publicKey, signature })
    ucrypto-->>NodeB: verification result (true/false)
Loading
sequenceDiagram
    participant User
    participant Node
    participant GCR as GCRIdentityRoutines
    participant Repo as GCRMainRepository

    User->>Node: Request PQC identity add (batch)
    Node->>GCR: applyPqcIdentityAdd(editOperation, Repo, simulate)
    GCR->>Repo: Validate and store PQC identities
    Repo-->>GCR: Save result
    GCR-->>Node: Success/failure response
Loading

Possibly related issues

  • DEM-213: Implements unified cryptography and signature abstraction as described in the issue, addressing its objectives for inter-node communication and cryptographic operations.

Possibly related PRs

  • kynesyslabs/incentives#3: Both PRs integrate the unified crypto library and update signature/key handling, sharing the goal of standardizing cryptographic operations across components.

Poem

In the warren of code, a new crypto dawn,
Async and unified, the old keys are gone.
PQC hops in, with signatures in tow,
Transactions and peers now ready to grow.
The blockchain burrows deeper, secure and bright—
Rabbits rejoice in this cryptographic delight!
🐇✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@cwilvx
Copy link
Contributor Author

cwilvx commented Jun 9, 2025

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 9, 2025

✅ 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.

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: 31

🔭 Outside diff range comments (2)
src/features/web2/Web2RequestManager.ts (1)

127-143: ⚠️ Potential issue

Hashing mismatch makes every attestation invalid

validateWeb2RequestAndResult hashes { request.raw, result }, but
verifyWeb2RequestAndResult recomputes the hash only on request.raw.

That guarantees hashIsValid === false whenever result is non-empty.

-            const stringifiedContent = JSON.stringify(this.dahr.web2Request.raw)
+            const stringifiedContent = JSON.stringify({
+                request: this.dahr.web2Request.raw,
+                result: this.dahr.web2Request.result,
+            })
src/libs/blockchain/gcr/gcr_routines/GCRIdentityRoutines.ts (1)

512-538: ⚠️ Potential issue

Query parameters interpolated in JSON path – will not bind

Postgres placeholders (:chain, :subchain) cannot be used inside JSON
operators. The query is executed verbatim, so the planner sees the string
:chain, not its bound value, and the query always returns no rows.

You need string interpolation after sanitising the identifiers, or a
different approach (e.g. jsonb_extract_path_text) with constant column paths.

const query = `
  EXISTS (
    SELECT 1
    FROM jsonb_array_elements(gcr.identities->'xm'->'${chain}'->'${subchain}') AS xm_id
    WHERE xm_id->>'address' = :address
  )
`
qb.where(query, { address: addressToCheck })

Be sure to validate chain/subchain against an allow-list first.
[security]

♻️ Duplicate comments (1)
src/libs/peer/PeerManager.ts (1)

296-305: Same API-shape concern for ucrypto.sign as in createBlock.

Double-check that the positional-parameter overload is valid; otherwise
signature may be undefined.

🧹 Nitpick comments (29)
.env.example (1)

1-5: Consider security best practices for credential management.

While this example file appropriately provides empty placeholders, consider documenting secure credential management alternatives:

  • Use credential management tools (HashiCorp Vault, AWS Secrets Manager)
  • Implement OAuth flows instead of storing passwords
  • Use GitHub tokens with minimal required scopes

Consider adding security comments to the example:

+# Security Note: Avoid storing passwords in environment variables in production
+# Consider using OAuth, credential managers, or secure secret storage
 TWITTER_USERNAME=
 TWITTER_PASSWORD=
 TWITTER_EMAIL=

+# Generate tokens with minimal required scopes
 GITHUB_TOKEN=
src/libs/network/manageNodeCall.ts (1)

23-23: Side-effect-only import – consider tree-shaking friendly form

uint8ArrayToHex is imported solely for the "getPeerIdentity" branch. Keeping it here is fine, but if bundle size matters, consider dynamic import or exposing publicKeyHex directly from shared state.

src/libs/abstraction/web2/parsers.ts (1)

43-44: Add validation for SigningAlgorithm casting.

The type casting splits[2] as SigningAlgorithm assumes the input is always a valid algorithm. Consider adding validation to ensure robustness.

 return {
     message: splits[1],
-    type: splits[2] as SigningAlgorithm,
+    type: splits[2] as SigningAlgorithm, // TODO: Validate algorithm
     signature: splits[3],
 }

Alternatively, add runtime validation:

const algorithm = splits[2] as SigningAlgorithm;
if (!Object.values(SigningAlgorithm).includes(algorithm)) {
    throw new Error(`Invalid signing algorithm: ${algorithm}`);
}
src/libs/abstraction/web2/github.ts (1)

91-94: Use class name instead of this in static context.

The static analysis correctly identifies that using this in a static context can be confusing. For better clarity, use the class name directly.

Apply this diff to improve code clarity:

 static async getInstance() {
     if (!this.instance) {
         this.instance = new this()
-        await this.instance.login()
+        await GithubProofParser.instance.login()
     }

Additionally, for consistency with the instantiation pattern:

 static async getInstance() {
-    if (!this.instance) {
-        this.instance = new this()
-        await this.instance.login()
+    if (!GithubProofParser.instance) {
+        GithubProofParser.instance = new GithubProofParser()
+        await GithubProofParser.instance.login()
     }
 
-    return this.instance
+    return GithubProofParser.instance
 }
🧰 Tools
🪛 Biome (1.9.4)

[error] 91-91: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 92-92: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 92-92: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 93-93: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

src/features/web2/handleWeb2.ts (1)

101-101: Address the TODO comment regarding attestation validation.

The comment indicates that web2ResultIsValid now returns a Promise, but the attestation validation logic appears to be incomplete with the TODO comment below.

Would you like me to help implement the attestation validation logic for non-original RPC requests? I can generate the missing implementation that properly validates attestations using the async web2ResultIsValid method.

src/libs/abstraction/index.ts (1)

1-1: Remove unused import.

The Cryptography import is no longer used after the migration to ucrypto.

-import Cryptography from "../crypto/cryptography"
 import { GithubProofParser } from "./web2/github"
src/libs/network/manageHelloPeer.ts (1)

8-8: Remove unused import.

The Cryptography import is no longer used after migrating to ucrypto.

 import * as forge from "node-forge"
-import Cryptography from "../crypto/cryptography"
 import { SyncData } from "../peer/Peer"
src/libs/consensus/v2/routines/manageProposeBlockHash.ts (1)

28-28: Avoid repeating getSharedState.publicKeyHex.

The same literal is assigned to response.response four times.
Stash it in a const ourKey = getSharedState.publicKeyHex; to reduce
property-lookups and keep the code DRY.

-        response.response = getSharedState.publicKeyHex
+        const ourKey = getSharedState.publicKeyHex
+        response.response = ourKey

Also applies to: 50-50, 60-60, 101-101

src/libs/consensus/v2/routines/createBlock.ts (1)

51-52: Optional: clarify validation_data typing.

The “! Define a decent type for validation_data” comment hints at tech
debt. Consider introducing an explicit interface instead of the loose
object literal.

src/libs/peer/PeerManager.ts (1)

100-101: 👍 Extra logging is harmless but remember to drop verbose console.log.

In production these console calls add noise; log.debug already exists.

src/libs/network/routines/transactions/handleIdentityRequest.ts (1)

31-36: Clarify the sender parameter usage for xm_identity_assign.

The comment mentions that sender can be either ed25519 or PQC address, but the code doesn't seem to use the sender parameter for xm_identity_assign. The verifyPayload method only takes the payload parameter.

Consider clarifying the comment or verify if the sender parameter should be passed:

         case "xm_identity_assign":
-            // NOTE: Sender here is the ed25519 address coming from the transaction body
-            // because the xm identity tx can be signed with both ed25519 and pqc.
-            // The sender address here will be the message to verify using the signature in the payload.
+            // NOTE: XM identity verification uses the signed data in the payload for verification
             return await IdentityManager.verifyPayload(
                 payload.payload as InferFromSignaturePayload,
             )
src/libs/blockchain/gcr/gcr_routines/identityManager.ts (2)

190-192: Fix static analysis warning: Replace 'this' with class name.

The static analysis tool correctly identifies that using this in a static context is confusing and should be replaced with the class name.

     static async getPQCIdentity(address: string) {
-        return await this.getIdentities(address, "pqc")
+        return await IdentityManager.getIdentities(address, "pqc")
     }
🧰 Tools
🪛 Biome (1.9.4)

[error] 191-191: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


128-156: Verify the PQC verification logic and error handling.

The PQC verification method uses Ed25519 for signature verification, which seems correct for the current implementation. However, consider these improvements:

  1. The message encoding uses payload.address directly - ensure this matches the signing process
  2. Error handling could be more descriptive about which specific payload failed

Consider enhancing error reporting:

             if (!verified) {
                 return {
                     success: false,
-                    message: `${payload.algorithm} payload could not be verified`,
+                    message: `${payload.algorithm} payload for address ${payload.address} could not be verified`,
                 }
             }
src/model/entities/types/IdentityTypes.ts (1)

17-28: Consider consolidating PQC identity interfaces.

The separation between SavedPqcIdentity and PqcIdentityEdit seems artificial since PqcIdentityEdit only adds the algorithm field. Consider if this separation is necessary or if a single interface with optional fields would be simpler.

Alternative approach:

-export interface SavedPqcIdentity {
-    address: string
-    signature: string
-    timestamp: number
-}
-
-/**
- * The PQC identity GCR edit operation data
- */
-export interface PqcIdentityEdit extends SavedPqcIdentity {
-    algorithm: string
-}
+export interface PqcIdentity {
+    address: string
+    signature: string
+    timestamp: number
+    algorithm?: string // Optional for stored identities, required for operations
+}
src/libs/blockchain/routines/validateTransaction.ts (4)

18-26: Remove dangling Cryptography import

Cryptography (line 18) is no longer referenced after the migration to ucrypto; keeping it will trigger linter/TS errors (no-unused-vars).

-import Cryptography from "src/libs/crypto/cryptography"

54-60: Avoid per-call identity fetch; cache the RPC public key

ucrypto.getIdentity() performs async I/O every time confirmTransaction runs.
If this routine is executed for every transaction, the extra await adds measurable latency.
Store the public key once at process start (or in getSharedState) and reuse it.


90-95: Unused confirmation variable

confirmation is destructured but never used – dead code and potential lint failure.
Simply omit it from the destructuring or use the value.

-const { confirmation, message, success: verified } =
-    await Transaction.confirmTx(tx, sender)
+const { message, success: verified } =
+    await Transaction.confirmTx(tx, sender)

133-136: privateKey parameter is now obsolete

defineGas no longer touches privateKey; keeping it misleads callers.

-async function defineGas(
-    tx: Transaction,
-    validityData: ValidityData,
-    privateKey: pki.PrivateKey,
+async function defineGas(
+    tx: Transaction,
+    validityData: ValidityData,
src/libs/peer/Peer.ts (2)

5-8: Prune unused Cryptography import

After the ucrypto migration, Cryptography isn’t referenced.

-import Cryptography from "../crypto/cryptography"

270-273: Skip empty auth headers when unauthenticated

When isAuthenticated === false, the current implementation still transmits identity: "" and signature: "". Many peers will treat this as malformed.
Set the headers conditionally instead.

src/libs/network/manageConsensusRoutines.ts (2)

15-15: Remove unused Cryptography import

No reference remains after header-level verification was off-loaded.

-import Cryptography from "../crypto/cryptography"

219-225: Shard-membership rejection is correct – but consider 403 instead of 401

401 implies “unauthenticated”; lack-of-membership is an authorization issue (403).
Minor but improves API semantics.

src/features/web2/Web2RequestManager.ts (1)

180-193: Busy-wait loop can hog the event loop

quorumIsReached uses a 100 ms polling loop with setTimeout, which can block the event loop under high concurrency. Prefer await Waiter.wait(...) or an event-driven promise.

src/libs/network/endpointHandlers.ts (1)

186-191: Avoid unnecessary async crypto call

ucrypto.getIdentity() hits WASM every time. You already expose the hex key via getSharedState.publicKeyHex; converting once with hexToUint8Array is faster and avoids an await.

src/libs/network/server_rpc.ts (1)

248-249: Stylistic rule violated (quotes)

ESLint complains because the string literal uses single quotes whereas the
project rule enforces double quotes. Align with the rule to keep CI green:

-server.get("/", () => new Response('{"message": "Hello, World!"}'))
+server.get("/", () => new Response("{\"message\": \"Hello, World!\"}"))
🧰 Tools
🪛 ESLint

[error] 248-248: Strings must use doublequote.

(quotes)

src/libs/blockchain/gcr/gcr_routines/GCRIdentityRoutines.ts (2)

294-329: Early return aborts batch processing after first duplicate

applyPqcIdentityAdd exits immediately when it finds an already–existing key.
This means that identities appearing after the duplicate are never checked
or added, surprising the caller.

Collect duplicates and process the rest, then return an aggregated result:

-            if (keyExists) {
-                return {
-                    success: false,
-                    message: `Identity already exists for algorithm ${algorithm}`,
-                }
-            }
+            if (keyExists) {
+                duplicates.push(`${algorithm}:${address}`)
+                continue
+            }

…and finally:

return duplicates.length
  ? { success: false, message: `Already exists: ${duplicates.join(", ")}` }
  : { success: true,  message: "PQC identities added" }

474-487: Use class name instead of this in static context

Biome flags this.applyPqcIdentityAdd / this.applyPqcIdentityRemove in a
static method. Replace with the explicit class name for clarity:

-            case "pqcadd":
-                result = await this.applyPqcIdentityAdd(
+            case "pqcadd":
+                result = await GCRIdentityRoutines.applyPqcIdentityAdd(

(Repeat for the remove path.)

🧰 Tools
🪛 Biome (1.9.4)

[error] 474-474: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 481-481: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

src/libs/blockchain/transaction.ts (2)

465-479: Storing signature as stringified JSON – brittle

Serialising nested structures into a single DB column makes querying and index
creation painful and can break on circular refs. Consider:

signature_type: varchar,
signature_data: text

or a JSONB column if the database supports it.
At minimum, keep the structure binary-safe (Base64 / hex) and avoid
JSON.stringify here.


321-323: Verbose console.log statements will flood production logs

confirmTx, validateSignature, etc. dump large objects on every call.
Replace with the existing log utility at an appropriate level or
remove before shipping.

🧰 Tools
🪛 Biome (1.9.4)

[error] 323-323: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 52b75ef and 97ad3aa.

📒 Files selected for processing (45)
  • .env.example (1 hunks)
  • .eslintrc.cjs (1 hunks)
  • package.json (1 hunks)
  • run (1 hunks)
  • src/features/incentive/PointSystem.ts (2 hunks)
  • src/features/web2/Web2RequestManager.ts (8 hunks)
  • src/features/web2/dahr/DAHR.ts (1 hunks)
  • src/features/web2/handleWeb2.ts (2 hunks)
  • src/index.ts (2 hunks)
  • src/libs/abstraction/index.ts (2 hunks)
  • src/libs/abstraction/web2/github.ts (3 hunks)
  • src/libs/abstraction/web2/parsers.ts (3 hunks)
  • src/libs/abstraction/web2/twitter.ts (2 hunks)
  • src/libs/blockchain/chain.ts (1 hunks)
  • src/libs/blockchain/gcr/gcr_routines/GCRIdentityRoutines.ts (10 hunks)
  • src/libs/blockchain/gcr/gcr_routines/identityManager.ts (4 hunks)
  • src/libs/blockchain/gcr/gcr_routines/index.ts (1 hunks)
  • src/libs/blockchain/mempool.ts (2 hunks)
  • src/libs/blockchain/routines/validateTransaction.ts (6 hunks)
  • src/libs/blockchain/transaction.ts (8 hunks)
  • src/libs/blockchain/types/confirmation.ts (1 hunks)
  • src/libs/consensus/v2/PoRBFT.ts (0 hunks)
  • src/libs/consensus/v2/routines/broadcastBlockHash.ts (4 hunks)
  • src/libs/consensus/v2/routines/createBlock.ts (2 hunks)
  • src/libs/consensus/v2/routines/manageProposeBlockHash.ts (5 hunks)
  • src/libs/consensus/v2/routines/secretary.ts (0 hunks)
  • src/libs/consensus/v2/types/secretaryManager.ts (4 hunks)
  • src/libs/identity/identity.ts (1 hunks)
  • src/libs/network/endpointHandlers.ts (12 hunks)
  • src/libs/network/manageConsensusRoutines.ts (6 hunks)
  • src/libs/network/manageExecution.ts (3 hunks)
  • src/libs/network/manageGCRRoutines.ts (1 hunks)
  • src/libs/network/manageHelloPeer.ts (4 hunks)
  • src/libs/network/manageNodeCall.ts (2 hunks)
  • src/libs/network/routines/nodecalls/getPeerlist.ts (2 hunks)
  • src/libs/network/routines/transactions/handleIdentityRequest.ts (2 hunks)
  • src/libs/network/server_rpc.ts (12 hunks)
  • src/libs/peer/Peer.ts (4 hunks)
  • src/libs/peer/PeerManager.ts (6 hunks)
  • src/libs/peer/routines/getPeerIdentity.ts (1 hunks)
  • src/libs/utils/demostdlib/deriveMempoolOperation.ts (3 hunks)
  • src/model/entities/Mempool.ts (2 hunks)
  • src/model/entities/Transactions.ts (2 hunks)
  • src/model/entities/types/IdentityTypes.ts (1 hunks)
  • src/utilities/sharedState.ts (3 hunks)
💤 Files with no reviewable changes (2)
  • src/libs/consensus/v2/PoRBFT.ts
  • src/libs/consensus/v2/routines/secretary.ts
🧰 Additional context used
🧬 Code Graph Analysis (14)
src/libs/network/manageGCRRoutines.ts (1)
src/libs/blockchain/gcr/gcr_routines/identityManager.ts (1)
  • IdentityManager (50-208)
src/libs/network/manageNodeCall.ts (1)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/index.ts (1)
src/utilities/sharedState.ts (2)
  • getSharedState (222-224)
  • publicKeyHex (95-101)
src/libs/blockchain/chain.ts (1)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/libs/utils/demostdlib/deriveMempoolOperation.ts (1)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/libs/network/routines/nodecalls/getPeerlist.ts (1)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/libs/consensus/v2/routines/manageProposeBlockHash.ts (1)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/features/web2/handleWeb2.ts (1)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/libs/consensus/v2/routines/createBlock.ts (1)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/libs/peer/PeerManager.ts (2)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/libs/network/manageHelloPeer.ts (1)
  • HelloPeerRequest (12-20)
src/libs/consensus/v2/routines/broadcastBlockHash.ts (1)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/libs/consensus/v2/types/secretaryManager.ts (1)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/libs/peer/Peer.ts (1)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/libs/blockchain/transaction.ts (4)
src/utilities/sharedState.ts (1)
  • getSharedState (222-224)
src/libs/blockchain/types/confirmation.ts (1)
  • Confirmation (14-31)
src/libs/blockchain/gcr/gcr_routines/identityManager.ts (1)
  • IdentityManager (50-208)
src/model/entities/types/IdentityTypes.ts (1)
  • SavedPqcIdentity (17-21)
🪛 Biome (1.9.4)
src/libs/abstraction/web2/github.ts

[error] 93-93: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

src/libs/blockchain/gcr/gcr_routines/identityManager.ts

[error] 191-191: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

src/libs/blockchain/transaction.ts

[error] 127-127: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 132-132: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 142-142: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

src/libs/blockchain/gcr/gcr_routines/GCRIdentityRoutines.ts

[error] 474-474: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 481-481: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

🪛 ESLint
src/libs/network/server_rpc.ts

[error] 248-248: Strings must use doublequote.

(quotes)

🔇 Additional comments (54)
.eslintrc.cjs (1)

42-43: LGTM: Naming convention update supports crypto refactor patterns.

The change to allow leading and trailing underscores for variable-like identifiers is appropriate for the crypto refactor that introduces new data structures. This maintains camelCase requirements while providing flexibility for cryptographic field naming.

src/utilities/sharedState.ts (3)

4-4: LGTM: Crypto imports support unified refactor.

The new imports for node-forge, SigningAlgorithm, and uint8ArrayToHex properly support the transition to unified cryptographic operations.

Also applies to: 12-13


24-24: LGTM: Explicit signing algorithm specification.

Setting the default signing algorithm to "ed25519" provides clear algorithm specification for the unified crypto system.


84-94: LGTM: Flexible keypair structure supports multiple crypto types.

The keypair object appropriately accommodates different key formats (Uint8Array, RSA, Ed25519) needed for the crypto refactor while maintaining type safety.

package.json (1)

51-51:

Details

❓ Verification inconclusive

Verify the twitter-scraper version for compatibility and security.

The version bump from ^0.16.6 to ^0.17.0 should be validated for breaking changes and security issues.


🏁 Script executed:

#!/bin/bash
# Description: Check twitter-scraper version and security advisories

# Check if version exists
curl -s https://registry.npmjs.org/@the-convocation/twitter-scraper | jq '.versions | has("0.17.0")'

# Check for any known vulnerabilities
npm audit --package-lock-only --json 2>/dev/null | jq '.vulnerabilities | to_entries[] | select(.key | contains("twitter-scraper"))'

Length of output: 280


Verify @the-convocation/twitter-scraper bump – no vulnerabilities found

  • Version 0.17.0 is published on npm.
  • npm audit --package-lock-only reports no known security issues for this package.
  • Action: Review the dependency’s CHANGELOG or release notes for any breaking changes before merging.

Location to review:

  • package.json, line 51:
    "@the-convocation/twitter-scraper": "^0.17.0"
src/libs/peer/routines/getPeerIdentity.ts (1)

29-29: LGTM! Removal aligns with the unified crypto refactor.

Removing the local identity retrieval and logging is consistent with the transition away from direct getSharedState.identity.ed25519 access to the new unified crypto module.

src/libs/network/manageGCRRoutines.ts (1)

31-31: LGTM! Parameter change improves API consistency.

Changing from sender to params[0] is correct based on the IdentityManager.getIdentities(address: string, key?: string) method signature. This allows querying identities for any address, not just the sender.

Also applies to: 36-36, 43-43

src/model/entities/Mempool.ts (2)

2-2: LGTM: Import statement simplified appropriately.

The single-line import for Transaction from the demosdk types package is clean and follows good import practices.


50-51: LGTM: Ed25519 signature column addition supports crypto refactor.

The new nullable ed25519_signature varchar column aligns well with the unified crypto refactor objectives. The nullable constraint ensures backward compatibility during the migration from the previous cryptographic implementation.

src/features/web2/dahr/DAHR.ts (1)

89-89: LGTM: Proper async handling for cryptographic operations.

The addition of await correctly handles the asynchronous nature of getAttestedResult following the migration to the unified async crypto API. This ensures attestedResult is fully resolved before being spread into the return object.

src/features/incentive/PointSystem.ts (1)

53-60: LGTM: Improved identity data structure handling.

The renaming from addresses to identities and the corresponding property access change to identity.address better reflects the enhanced identity data structure. This aligns well with the broader refactor to support richer identity objects containing additional cryptographic metadata.

src/libs/network/routines/nodecalls/getPeerlist.ts (2)

9-9: LGTM: Comment formatting improvement.

Trimming trailing whitespace improves code cleanliness.


19-19: LGTM: Simplified access to canonical public key hex.

The change from getSharedState.identity.ed25519.publicKey.toString("hex") to getSharedState.publicKeyHex simplifies the code by using the canonical hex-encoded public key property. This aligns well with the unified crypto refactor objectives and improves maintainability.

src/libs/identity/identity.ts (1)

92-95: Good optimization: Removed unnecessary await.

Since this.publicIP is already a resolved string value, the await operator was redundant. This change improves performance slightly while maintaining the same return behavior.

src/libs/network/manageExecution.ts (3)

44-47: Consistent parameter forwarding.

The sender parameter is properly forwarded to the validation handler.

🧰 Tools
🪛 Biome (1.9.4)

[error] 44-47: 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:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


71-74: Consistent parameter forwarding.

The sender parameter is properly forwarded to the execution handler.


13-16:

Details

✅ Verification successful

LGTM: Added sender parameter for identity-aware processing.

The addition of the sender parameter aligns with the broader cryptographic refactor to support identity-aware transaction processing.

Verify that the called handler methods accept the new sender parameter:


🏁 Script executed:

#!/bin/bash
# Description: Verify that handleValidateTransaction and handleExecuteTransaction accept sender parameter

# Search for the method signatures to confirm they accept the sender parameter
ast-grep --pattern 'handleValidateTransaction($_, $sender) {
  $$$
}'

ast-grep --pattern 'handleExecuteTransaction($_, $sender) {
  $$$
}'

Length of output: 142


To locate and inspect the handler signatures directly, let’s search the codebase for their definitions and check the parameter lists:


🏁 Script executed:

#!/bin/bash
# Locate and inspect handleValidateTransaction signature
rg -Hn "handleValidateTransaction\s*\(" --include '*.ts' -A 2

# Locate and inspect handleExecuteTransaction signature
rg -Hn "handleExecuteTransaction\s*\(" --include '*.ts' -A 2

Length of output: 1010


Let’s broaden the search patterns and include context to locate both handlers across all .ts files:


🏁 Script executed:

#!/bin/bash
# Search for any occurrence of the handlers and show surrounding lines

rg -n -g '*.ts' 'handleValidateTransaction' -C 3
rg -n -g '*.ts' 'function handleValidateTransaction' -C 3

rg -n -g '*.ts' 'handleExecuteTransaction' -C 3
rg -n -g '*.ts' 'function handleExecuteTransaction' -C 3

Length of output: 10394


Confirmed: Handler methods accept the new sender parameter

Both ServerHandlers.handleValidateTransaction and ServerHandlers.handleExecuteTransaction signatures include sender: string, matching the propagated argument:

  • src/libs/network/endpointHandlers.ts:
    • handleValidateTransaction(tx: Transaction, sender: string)
    • handleExecuteTransaction(validatedData: ValidityData, sender: string)

LGTM – the change consistently propagates identity through the pipeline.

src/libs/blockchain/types/confirmation.ts (2)

13-13: Good addition: Import for unified signature algorithm type.

The SigningAlgorithm import supports the transition to algorithm-aware signatures.


19-22:

Details

✅ Verification successful

Verify compatibility: Significant signature type change.

The signature property has been changed from a raw buffer to a structured object with algorithm metadata. This aligns with the unified cryptographic refactor but is a breaking change.

Verify that all usages of Confirmation.signature have been updated to handle the new structure:


🏁 Script executed:

#!/bin/bash
# Description: Find all usages of Confirmation signature property to ensure compatibility

# Search for references to Confirmation signature property
rg -A 3 -B 1 "\.signature" --type ts

# Search for Confirmation class instantiation and usage
ast-grep --pattern 'new Confirmation()'

# Search for signature assignments
rg -A 2 "signature\s*=" --type ts

Length of output: 32203


Confirmation.signature usage verified

All instantiations of Confirmation.signature have been updated to the new { type, data } shape:

  • src/libs/blockchain/transaction.ts (line 152):
    const confirmation = new Confirmation()
    confirmation.signature = {
        type: getSharedState.signingAlgorithm,
        data: uint8ArrayToHex(signature.signature),
    }

No other references to Confirmation.signature were found.

src/libs/blockchain/chain.ts (3)

536-538: Good refactor: Dynamic signing algorithm for transaction recipient.

Replacing the hardcoded "ed25519" with getSharedState.signingAlgorithm supports multiple cryptographic algorithms.


540-542: Good refactor: Dynamic signing algorithm for transaction sender.

Consistent use of dynamic signing algorithm from shared state.


544-547:

Details

✅ Verification successful

Verify initialization: Dynamic signature algorithm and format change.

The changes align with the unified cryptographic refactor:

  1. Dynamic signing algorithm from shared state
  2. Signature data format changed from Uint8Array to string "0x0"

Verify that getSharedState.signingAlgorithm is properly initialized before genesis block creation:


🏁 Script executed:

#!/bin/bash
# Description: Verify shared state initialization order and signature algorithm setup

# Search for signingAlgorithm initialization in shared state
rg -A 5 -B 5 "signingAlgorithm.*=" --type ts

# Search for genesis block generation calls to understand initialization order
rg -A 3 -B 3 "generateGenesisBlock" --type ts

# Check if there are any default values or initialization guards
ast-grep --pattern 'signingAlgorithm: $_'

Length of output: 2420


All good – signingAlgorithm has a default and is initialized before genesis creation.

  • In src/utilities/sharedState.ts, signingAlgorithm is assigned "ed25519" by default, so getSharedState.signingAlgorithm will always be defined when generateGenesisBlock runs.
src/libs/network/manageNodeCall.ts (1)

148-149: Blind cast may hide runtime type errors

keypair.publicKey should already be a Uint8Array; if future refactors turn it into a hex string, this as Uint8Array will compile yet explode at run-time.

-response.response = uint8ArrayToHex(getSharedState.keypair.publicKey as Uint8Array)
+const pk = getSharedState.keypair.publicKey
+response.response = ArrayBuffer.isView(pk)
+    ? uint8ArrayToHex(pk as Uint8Array)
+    : pk // assume already hex

Adds a tiny guard without cost.

src/libs/abstraction/web2/twitter.ts (2)

7-7: LGTM: Consistent import addition for unified crypto refactor.

The import of SigningAlgorithm aligns with the broader migration to algorithm-aware cryptographic operations.


139-139: LGTM: Proper return type update for unified signature handling.

The change from publicKey: string to type: SigningAlgorithm is consistent with the refactoring to use structured signature metadata instead of raw public keys.

src/libs/blockchain/mempool.ts (1)

23-23: LGTM: Proper imports for unified crypto refactor.

The addition of ISignature, SigningAlgorithm types and ucrypto module aligns with the migration to asynchronous cryptographic operations.

Also applies to: 28-28

src/libs/abstraction/web2/parsers.ts (2)

1-1: LGTM: Consistent import for algorithm-aware parsing.

The SigningAlgorithm import supports the transition to structured signature metadata.


57-57: LGTM: Abstract method signature updated consistently.

The return type change ensures all implementing classes follow the new algorithm-aware signature structure.

src/index.ts (3)

36-36: LGTM: Proper imports for unified crypto system.

The addition of crypto utilities from the demosdk supports the transition to the unified cryptographic API.


241-255: LGTM: Proper public key handling with algorithm-aware file naming.

The transition to hex-based public key handling and algorithm-prefixed file naming supports multi-algorithm cryptography effectively. The use of uint8ArrayToHex and inclusion of the signing algorithm in the filename is a good practice for the unified crypto system.


228-255:

Details

✅ Verification successful

Verify the unified crypto initialization sequence.

Ensure that the crypto initialization properly integrates with the existing identity system and that the shared state is correctly populated.

Run this script to verify the initialization dependencies:


🏁 Script executed:

#!/bin/bash
# Verify shared state and crypto initialization integration
echo "Checking shared state keypair usage..."
rg -A 5 -B 5 "getSharedState\.keypair"

echo "Checking signing algorithm configuration..."
rg -A 3 -B 3 "signingAlgorithm"

echo "Checking public key hex usage..."
rg -A 3 -B 3 "publicKeyHex"

Length of output: 35265


🏁 Script executed:

#!/bin/bash
# Display SharedState class definition to inspect identity & keypair properties
sed -n '1,200p' src/utilities/sharedState.ts

Length of output: 6538


🏁 Script executed:

#!/bin/bash
# Inspect the Identity class to verify its ed25519 properties and initialization
sed -n '1,200p' src/libs/identity.ts

Length of output: 100


🏁 Script executed:

#!/bin/bash
# Locate the Identity implementation to verify ed25519 fields
rg --files-with-matches "class Identity" -n .

Length of output: 137


🏁 Script executed:

#!/bin/bash
# Inspect the Identity class to verify ed25519 properties and initialization
sed -n '1,200p' src/libs/identity/identity.ts

Length of output: 3344


🏁 Script executed:

#!/bin/bash
# Show ucrypto import and context in src/index.ts
sed -n '1,100p' src/index.ts | sed -n '1,200p'
rg --context 3 "ucrypto" -n src/index.ts

Length of output: 4542


Unified crypto initialization sequence is correct

The call order in src/index.ts —

  1. getSharedState.identity.ensureIdentity() loads or generates the ed25519 key,
  2. ucrypto.generateAllIdentities(...) seeds the unified-crypto layer with that private key,
  3. getSharedState.keypair = await ucrypto.getIdentity(signingAlgorithm) populates the shared‐state keypair,
  4. subsequent calls to getSharedState.publicKeyHex return the expected value.

No gaps were found in how identity, keypair, signingAlgorithm and publicKeyHex are initialized or used across the codebase.

src/libs/abstraction/web2/github.ts (1)

40-42: Consistent return type for the unified crypto refactor.

The updated return type correctly replaces publicKey with type field, aligning with the broader migration to the unified crypto module's signature format.

src/features/web2/handleWeb2.ts (1)

80-93: Proper migration to async cryptographic signing.

The conversion to ucrypto.sign with explicit algorithm specification and hex encoding is correctly implemented, following the unified crypto module pattern.

src/libs/abstraction/index.ts (1)

37-61: Well-structured async signature verification with proper error handling.

The migration to ucrypto.verify is correctly implemented with:

  • Proper destructuring of the new signature format
  • Correct conversion of hex strings to Uint8Arrays
  • Nested try-catch for specific error handling of verification failures
  • Clear success/failure messages
src/libs/network/manageHelloPeer.ts (3)

15-18: Correct migration to structured signature format.

The signature field properly follows the new unified crypto format with explicit algorithm type specification.


37-37: Simplified and consistent identity comparison.

Good simplification using getSharedState.publicKeyHex directly, aligning with the pattern used in other modules.


55-62: Properly implemented async signature verification.

The migration to ucrypto.verify correctly:

  • Uses the algorithm type from the signature object
  • Converts all inputs to Uint8Arrays
  • Handles the async nature of the verification
src/libs/consensus/v2/routines/manageProposeBlockHash.ts (1)

8-8: Import looks OK – but double-check tree-shaking impact.

hexToUint8Array and ucrypto are correctly imported.
No action required unless bundle size matters.

src/libs/consensus/v2/routines/createBlock.ts (1)

41-44:

Details

❓ Verification inconclusive

Verify the ucrypto.sign call signature.

Other calls to ucrypto.verify use an object, but here sign is invoked
with positional parameters. Ensure this matches the actual API;
otherwise the returned value might be undefined or contain unexpected
fields.


🏁 Script executed:

#!/bin/bash
# Locate every ucrypto.sign invocation to confirm the call shape
rg --line-number "ucrypto\.sign" -A1 -B1

Length of output: 3710


🏁 Script executed:

#!/bin/bash
# Show import and nearby context of ucrypto usage in createBlock.ts
file="src/libs/consensus/v2/routines/createBlock.ts"
echo "---- Imports in $file ----"
sed -n '1,30p' "$file"
echo
echo "---- ucrypto.sign usage around line 41 ----"
sed -n '30,60p' "$file" | sed -n '1,30p'

Length of output: 2918


🏁 Script executed:

#!/bin/bash
# Fetch package.json from unpkg to find the types entry
echo "---- package.json types field ----"
curl -s https://unpkg.com/@kynesyslabs/demosdk/encryption/package.json | grep '"types"' -A1

# Extract the types file path
typesFile=$(curl -s https://unpkg.com/@kynesyslabs/demosdk/encryption/package.json \
  | grep '"types"' \
  | sed -E 's/.*"types": "([^"]+)".*/\1/')
echo "Types file located at: $typesFile"

# Fetch the TypeScript definitions and show the signature of ucrypto.sign
echo "---- ucrypto.sign signature ----"
curl -s https://unpkg.com/@kynesyslabs/demosdk/encryption/$typesFile \
  | sed -n '/sign\(/,/^}/p'

Length of output: 586


Confirm ucrypto.sign call signature

Please verify that ucrypto.sign actually accepts positional parameters—i.e. (algorithm, data)—rather than a single options object. All current calls (including in createBlock.ts:41) use the positional form, but if the published API expects something like ucrypto.sign({ algorithm, data }), these invocations will return undefined or an unexpected shape.

Files to inspect:

  • src/libs/consensus/v2/routines/createBlock.ts:41
  • src/features/web2/handleWeb2.ts:80
  • src/features/web2/Web2RequestManager.ts:86
  • src/libs/peer/Peer.ts:189, 238
  • src/libs/peer/PeerManager.ts:296
  • src/libs/utils/demostdlib/deriveMempoolOperation.ts:193
  • src/libs/blockchain/transaction.ts:89, 156
  • src/libs/network/endpointHandlers.ts:151
  • src/libs/blockchain/routines/validateTransaction.ts:118, 162, 188, 219

If the API signature is object‐based, update these calls accordingly to ensure the returned value includes the expected .signature property.

src/libs/peer/PeerManager.ts (2)

159-160: Use strict equality on hex strings is fine – just ensure canonical form.

Comparing identity with publicKeyHex presumes both are lowercase /
no 0x prefix. If not normalised, equality might fail.


310-314: Good move to structured signature object.

The request now carries { type, data }, which future-proofs multi-algo
support. Looks solid.

src/libs/consensus/v2/routines/broadcastBlockHash.ts (3)

7-7: LGTM: Import changes align with unified crypto refactor.

The import of ucrypto and hexToUint8Array from @kynesyslabs/demosdk/encryption is consistent with the unified cryptographic operations introduced across the codebase.


16-16: LGTM: Simplified public key access.

The change from getSharedState.identity.ed25519.publicKey.toString("hex") to getSharedState.publicKeyHex simplifies the public key access and aligns with the unified public key handling approach.


62-67:

Details

✅ Verification successful

Verify the message encoding consistency.

The signature verification now uses new TextEncoder().encode(block.hash) instead of the raw block hash string. Ensure this encoding is consistent with how signatures were originally created.


🏁 Script executed:

#!/bin/bash
# Description: Check how block hashes are signed in the codebase to ensure consistency

# Search for block hash signing patterns
rg -A 5 -B 5 "sign.*block\.hash|block\.hash.*sign" --type ts

Length of output: 62


I wasn’t able to locate any existing block-hash signing logic. Let’s search for where signatures are created to confirm the encoding used:


🏁 Script executed:

#!/bin/bash
# Find all ucrypto method usages
rg "ucrypto\." --type ts -n

# Find all .sign( calls
rg "\.sign\(" --type ts -n

# Find all signature fields in objects
rg "signature" --type ts -n -A3 -B3

Length of output: 70913


Let’s confirm how the block hash is signed in createBlock.ts and see the surrounding context in broadcastBlockHash.ts:

#!/bin/bash
# Show how the blockSignature is created
rg -n "const blockSignature" -A3 -B3 src/libs/consensus/v2/routines/createBlock.ts

# Show verify call context in broadcastBlockHash.ts
sed -n '1,100p' src/libs/consensus/v2/routines/broadcastBlockHash.ts

Let’s inspect how the block hash is signed in createBlock.ts and view the full verify context in broadcastBlockHash.ts:


🏁 Script executed:

#!/bin/bash
# Show how the blockSignature is created in createBlock.ts
rg -n "ucrypto\.sign" -A3 -B3 src/libs/consensus/v2/routines/createBlock.ts

# Show the surrounding context for verify in broadcastBlockHash.ts
sed -n '1,80p' src/libs/consensus/v2/routines/broadcastBlockHash.ts

Length of output: 3931


Encoding Consistency Verified

Both signing and verification use new TextEncoder().encode(block.hash):

  • In src/libs/consensus/v2/routines/createBlock.ts (lines 41–44), the block signature is created with:
    const blockSignature = await ucrypto.sign(
        getSharedState.signingAlgorithm,
        new TextEncoder().encode(block.hash),
    )
    
  • In src/libs/consensus/v2/routines/broadcastBlockHash.ts (lines 62–67), incoming signatures are verified with the same encoding:
    const isValid = await ucrypto.verify({
        algorithm: getSharedState.signingAlgorithm,
        message: new TextEncoder().encode(block.hash),
        signature: hexToUint8Array(signature),
        publicKey: hexToUint8Array(identity),
    })
    

No changes required.

src/libs/network/routines/transactions/handleIdentityRequest.ts (2)

37-42: LGTM: PQC identity support added correctly.

The new pqc_identity_assign case properly delegates to IdentityManager.verifyPqcPayload with the correct payload type and sender parameter. The comment clearly explains the sender parameter semantics.


24-27:

Details

✅ Verification successful

Breaking change: Verify all function callers are updated.

The function signature changed from accepting IdentityPayload directly to accepting a full Transaction object. This is a breaking change that requires all callers to be updated.


🏁 Script executed:

#!/bin/bash
# Description: Find all callers of handleIdentityRequest to ensure they're updated for the new signature

# Search for function calls to handleIdentityRequest
rg -A 3 -B 3 "handleIdentityRequest\(" --type ts

Length of output: 1228


No breaking change detected: all callers updated

A search for handleIdentityRequest( shows a single caller in src/libs/network/endpointHandlers.ts already passing (tx, sender). No other usages were found, so no action is needed.

src/libs/blockchain/gcr/gcr_routines/identityManager.ts (1)

133-138:

Details

❓ Verification inconclusive

Verify message encoding consistency for PQC signatures.

The verification uses new TextEncoder().encode(payload.address) as the message. Ensure this encoding is consistent with how PQC signatures are created elsewhere in the codebase.


🏁 Script executed:

#!/bin/bash
# Description: Check how PQC signatures are created to ensure message encoding consistency

# Search for PQC signing patterns
rg -A 5 -B 5 "pqc.*sign|sign.*pqc" --type ts

Length of output: 2875


🏁 Script executed:

#!/bin/bash
# Retrieve the verifyPqcPayload implementation to inspect how the message is encoded
rg -A20 -B5 "verifyPqcPayload" --type ts src/libs/blockchain/gcr/gcr_routines/identityManager.ts

Length of output: 1089


🏁 Script executed:

#!/bin/bash
# List GCR routine files to locate potential signing methods
ls -1 src/libs/blockchain/gcr/gcr_routines

# Search for any ucrypto.sign usages across the repo
rg -R "ucrypto\.sign" --type ts

# Locate the PqcIdentityAssignPayload type definition
rg -R "PqcIdentityAssignPayload" --type ts

Length of output: 1245


🏁 Script executed:

#!/bin/bash
# Correct search for ucrypto.sign usages
rg "ucrypto\.sign" --type ts

# Search for any general .sign( invocations in TS files
rg "\.sign\(" --type ts | grep -v "verify"

# Locate PqcIdentityAssignPayload definition
rg "type PqcIdentityAssignPayload" -A5 --type ts

Length of output: 3618


Ensure consistent message encoding for PQC identity‐assign signatures

Before merging, confirm that the way you encode payload.address when signing matches how you verify it. In verifyPqcPayload (src/libs/blockchain/gcr/gcr_routines/identityManager.ts lines 133–138), you currently do:

message: new TextEncoder().encode(payload.address)

If your PQC‐assign payloads were signed over the raw key bytes (e.g. via hexToUint8Array(payload.address)), this will fail at verify time. Please:

  • Verify how the client generates each payload.signature for PQC identity assign:
    • Are you signing the UTF-8 bytes of the hex string?
    • Or the raw public‐key bytes decoded from hex?
  • If it’s the latter, update the verifier to:
    message: hexToUint8Array(payload.address)
  • Otherwise, ensure your signing logic uses new TextEncoder().encode(payload.address).
src/model/entities/types/IdentityTypes.ts (1)

3-12: LGTM: Well-structured XM identity interface.

The SavedXmIdentity interface provides a comprehensive structure for XM identity data with clear comments explaining the signed message semantics. The note about not storing the message but deriving it from the transaction is particularly helpful.

src/libs/peer/Peer.ts (1)

40-44: Null-safe access to local public key

getSharedState.keypair may be undefined during early bootstrap or in test environments.
Guard to avoid Cannot read property 'publicKey' of undefined.

-return this.identity ===
-    uint8ArrayToHex(getSharedState.keypair.publicKey as Uint8Array)
+return (
+    getSharedState.keypair &&
+    this.identity ===
+        uint8ArrayToHex(getSharedState.keypair.publicKey as Uint8Array)
+)
src/libs/network/manageConsensusRoutines.ts (1)

76-78: Ensure publicKeyHex exists in shared state

If publicKeyHex is undefined the shard-membership test always fails, leading to false 400 responses.
Double-check initialization order or fall back to computing it from keypair.publicKey.

src/libs/consensus/v2/types/secretaryManager.ts (1)

538-539:

Details

✅ Verification successful

Double-check the updated RPC payload shape

releaseWaitingMembers now sends only [timestamp, phase].
Please confirm that every greenlight handler has been refactored accordingly; otherwise calls will break with 400 / 500 responses.


🏁 Script executed:

#!/bin/bash
# Find all greenlight handlers and list their parameter count
rg --context 2 $'function\\s+greenlight' | head -n 40

Length of output: 53


Let's broaden the search to locate any references to greenlight across the codebase:


🏁 Script executed:

#!/bin/bash
# Search for any occurrences of 'greenlight' to find handler definitions
rg --context 2 'greenlight' | head -n 60

Length of output: 4029


Let’s inspect the signatures and handler to ensure they match the new [timestamp, phase] payload:

#!/bin/bash
# Show releaseWaitingMembers definition
rg -A3 -B3 'releaseWaitingMembers' src/libs/consensus/v2/types/secretaryManager.ts

# Show receiveGreenLight signature
rg -A3 -B3 'receiveGreenLight' src/libs/consensus/v2/types/secretaryManager.ts

# Show the greenlight RPC handler
rg -A5 -B5 'case "greenlight":' src/libs/network/manageConsensusRoutines.ts

Let’s dump the relevant definitions and handler to verify their parameter shapes:


🏁 Script executed:

#!/bin/bash
# Show releaseWaitingMembers definition
rg -A3 -B3 'releaseWaitingMembers' src/libs/consensus/v2/types/secretaryManager.ts

# Show receiveGreenLight signature
rg -A3 -B3 'receiveGreenLight' src/libs/consensus/v2/types/secretaryManager.ts

# Show the greenlight RPC handler
rg -A5 -B5 'case "greenlight":' src/libs/network/manageConsensusRoutines.ts

Length of output: 1945


Greenlight RPC payload shape is correct

The greenlight handler in manageConsensusRoutines.ts unpacks exactly two params—[timestamp, validatorPhase]—and forwards them to SecretaryManager.receiveGreenLight(timestamp, validatorPhase), whose signature matches. No other greenlight handlers exist, so no further refactoring is needed.

src/libs/blockchain/gcr/gcr_routines/GCRIdentityRoutines.ts (1)

48-68: SavedXmIdentity extended object – but publicKey may be undefined

publicKey is pushed with editOperation.data.publicKey || "".
If the caller forgets publicKey, the empty string is persisted and later
signature verification will inevitably fail.

Either make the field mandatory in the validation above, or omit it when not
provided to avoid writing meaningless data.

-    !signature ||
-    !timestamp ||
-    !signedData
+    !signature ||
+    !timestamp ||
+    !signedData ||
+    !publicKey

or

 publicKey: editOperation.data.publicKey || "",

-> remove the line and adjust the type.
Choose one consistent path.

src/libs/blockchain/transaction.ts (2)

152-163: Type mismatch when building Confirmation

Confirmation.data.validator expects a forge.pki.ed25519.BinaryBuffer but an
Uint8Array is assigned. Down-stream code that serialises / deserialises the
confirmation may break.

Convert the key:

-confirmation.data.validator = getSharedState.keypair.publicKey as Uint8Array
+confirmation.data.validator = forge.util.binary.raw.encode(
+    Buffer.from(getSharedState.keypair.publicKey)
+)

(or update the type definition if the project is switching away from Forge).


256-262: Double hashing risk – message format not fixed

The main signature is verified on TextEncoder().encode(tx.hash).
If the original signer instead signed the raw content (pre-hash) this
verification will always fail. Ensure signing and verification agree on:

  • raw JSON
  • canonicalised JSON
  • or the hash string

Document the convention and enforce it in sign().

@cwilvx cwilvx merged commit c80e90a into testnet Jun 9, 2025
1 check passed
@cwilvx cwilvx deleted the ucrypto branch June 9, 2025 13:21
@coderabbitai coderabbitai bot mentioned this pull request Aug 4, 2025
@coderabbitai coderabbitai bot mentioned this pull request Oct 21, 2025
This was referenced Nov 4, 2025
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