Skip to content

perf: using asynchronous worker to validate BLS signatures in quorum commitments #6692

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 6 commits into
base: develop
Choose a base branch
from

Conversation

knst
Copy link
Collaborator

@knst knst commented May 28, 2025

Issue being fixed or feature implemented

During blocks validation, quorum commitments are processed in single thread.
While some blocks have up to 32 commitments (blocks which have rotation quorums commitment), each quorum commitment have hundreds public keys to validate and 2 signature (quorum signature and public key signature). It takes up to 30% in total indexing time and up to 1 second for heavy blocks.

What was done?

CCheckQueue which is used for validation ECDSA signatures is used now for validation of BLS signatures in quorum commitments.
Quorum signature and members signatures are validated simultaneously now which makes performance improvement even for blocks which has only 1 commitment.

How Has This Been Tested?

Invalidated + reconsidered 15k blocks (~1 months worth)
This PR makes validation of Quorum Commitment 3.5x times faster; overall indexing 25% faster on my 12 cores environment.

PR:
image

2025-05-28T10:17:56Z [bench]         - m_qblockman: 0.03ms [28.90s]
2025-05-28T10:17:56Z [bench]   - Connect total: 9.01ms [184.16s (11.86ms/blk)]
2025-05-28T10:17:56Z [bench] - Connect block: 9.21ms [190.33s (12.25ms/blk)]

develop:
image

2025-05-22T18:39:44Z [bench]         - m_qblockman: 0.03ms [96.90s]
2025-05-22T18:39:44Z [bench]   - Connect total: 9.31ms [252.80s (16.28ms/blk)]
2025-05-22T18:39:44Z [bench] - Connect block: 9.50ms [258.90s (16.67ms/blk)]

Breaking Changes

N/A

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation
  • I have assigned this pull request to a milestone

@knst knst force-pushed the perf-bls-parallel branch from ec3a9d4 to 8b6414d Compare May 28, 2025 11:53
Copy link

coderabbitai bot commented May 28, 2025

Walkthrough

The changes add asynchronous BLS signature verification to quorum commitment processing by introducing a BlsCheck struct that encapsulates signature verification tasks. A parallelized check queue (m_bls_queue) is integrated into the CQuorumBlockProcessor class to handle these tasks concurrently, with worker threads managed in the constructor and destructor. The signature verification logic is refactored into a new method, VerifySignatureAsync, in the CFinalCommitment class, which supports both synchronous and asynchronous verification. These modifications offload signature verification from commitment processing and centralize the verification logic.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ec3a9d4 and 8b6414d.

📒 Files selected for processing (6)
  • src/llmq/blockprocessor.cpp (3 hunks)
  • src/llmq/blockprocessor.h (4 hunks)
  • src/llmq/commitment.cpp (3 hunks)
  • src/llmq/commitment.h (2 hunks)
  • src/llmq/utils.cpp (1 hunks)
  • src/llmq/utils.h (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/llmq/blockprocessor.h
  • src/llmq/utils.cpp
  • src/llmq/blockprocessor.cpp
  • src/llmq/commitment.cpp
  • src/llmq/utils.h
  • src/llmq/commitment.h
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: arm-linux-build / Build source
  • GitHub Check: linux64_nowallet-build / Build source
  • GitHub Check: win64-build / Build source
  • GitHub Check: linux64_fuzz-build / Build source
  • GitHub Check: linux64-build / Build source
  • GitHub Check: linux64_sqlite-build / Build source
  • GitHub Check: linux64_ubsan-build / Build source
  • GitHub Check: mac-build / Build source
  • GitHub Check: linux64_tsan-build / Build source
  • GitHub Check: linux64_multiprocess-build / Build source
✨ Finishing Touches
  • 📝 Generate Docstrings

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

Copy link

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/llmq/blockprocessor.cpp (1)

208-220: Consider adding error logging when signature verification fails.

The asynchronous signature verification implementation is correct and follows proper patterns. However, when queue_control.Wait() returns false, it would be helpful to log which commitment(s) failed verification for debugging purposes.

Consider adding a log message before returning false:

 if (!queue_control.Wait()) {
     // at least one check failed
+    LogPrintf("[ProcessBlock] BLS signature verification failed for block at height %d\n", pindex->nHeight);
     return false;
 }
src/llmq/commitment.cpp (1)

31-95: Consider refactoring for improved modularity.

The implementation correctly handles both synchronous and asynchronous BLS signature verification. However, the method is quite long (64 lines) and handles multiple responsibilities.

Consider extracting helper methods to improve readability and maintainability:

bool CFinalCommitment::VerifySignatureAsync(CDeterministicMNManager& dmnman, CQuorumSnapshotManager& qsnapman,
                                           gsl::not_null<const CBlockIndex*> pQuorumBaseBlockIndex,
                                           CCheckQueueControl<utils::BlsCheck>* queue_control) const
{
    auto members = utils::GetAllQuorumMembers(llmqType, dmnman, qsnapman, pQuorumBaseBlockIndex);
    const auto& llmq_params_opt = Params().GetLLMQ(llmqType);
    if (!llmq_params_opt.has_value()) {
        LogPrint(BCLog::LLMQ, "CFinalCommitment -- q[%s] invalid llmqType=%d\n", quorumHash.ToString(),
                 ToUnderlying(llmqType));
        return false;
    }
    const auto& llmq_params = llmq_params_opt.value();

    uint256 commitmentHash = BuildCommitmentHash(llmq_params.type, quorumHash, validMembers, quorumPublicKey,
                                                 quorumVvecHash);
    LogMemberDetails(members, commitmentHash);

    if (!VerifyMemberSignatures(llmq_params, members, commitmentHash, queue_control)) {
        return false;
    }

    if (!VerifyQuorumSignature(commitmentHash, queue_control)) {
        return false;
    }

    return true;
}

private:
bool CFinalCommitment::VerifyMemberSignatures(const Consensus::LLMQParams& llmq_params,
                                             const std::vector<CDeterministicMNCPtr>& members,
                                             const uint256& commitmentHash,
                                             CCheckQueueControl<utils::BlsCheck>* queue_control) const
{
    // Implementation for member signature verification
}

bool CFinalCommitment::VerifyQuorumSignature(const uint256& commitmentHash,
                                            CCheckQueueControl<utils::BlsCheck>* queue_control) const
{
    // Implementation for quorum signature verification
}
🛑 Comments failed to post (1)
src/llmq/commitment.h (1)

34-37: ⚠️ Potential issue

Fix namespace formatting issue identified by pipeline.

The nested namespace declaration needs proper formatting according to clang-format requirements.

Apply this diff to fix the formatting:

-namespace utils
-{
-struct BlsCheck;
-} // namespace utils
+namespace utils {
+struct BlsCheck;
+} // namespace utils
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

namespace utils {
struct BlsCheck;
} // namespace utils
🤖 Prompt for AI Agents
In src/llmq/commitment.h around lines 34 to 37, the nested namespace declaration
for utils is not properly formatted according to clang-format standards. Adjust
the namespace declaration to use the correct syntax and indentation style,
ensuring the opening and closing braces align properly and the comment
indicating the namespace closure is correctly placed.

@knst
Copy link
Collaborator Author

knst commented May 28, 2025

just to be sure that CCheckQueue works at all (and not just return true) I modified code a bit and it failed as expected:

diff --git a/src/llmq/commitment.cpp b/src/llmq/commitment.cpp
index c2cbe9b35c..b242b4c988 100644
--- a/src/llmq/commitment.cpp
+++ b/src/llmq/commitment.cpp
@@ -69,7 +69,12 @@ bool CFinalCommitment::VerifySignatureAsync(CDeterministicMNManager& dmnman, CQu
             strprintf("CFinalCommitment -- q[%s] invalid aggregated members signature", quorumHash.ToString())};
         if (queue_control) {
             std::vector<utils::BlsCheck> vChecks;
-            vChecks.emplace_back(membersSig, memberPubKeys, commitmentHash, members_id_string);
+            static int counter{0};
+            if (++counter == 42) {
+                vChecks.emplace_back(quorumSig, memberPubKeys, commitmentHash, members_id_string);
+            } else {
+                vChecks.emplace_back(membersSig, memberPubKeys, commitmentHash, members_id_string);
+            }
             queue_control->Add(vChecks);
         } else {
             if (!membersSig.VerifySecureAggregated(memberPubKeys, commitmentHash)) {

error:

2025-05-28T08:25:41Z [ProcessBlock] h[2270346] numCommitmentsRequired[32] numCommitmentsInNewBlock[32]
2025-05-28T08:25:41Z CDeterministicMNList::PoSePunish -- punished MN a5a25d4c35bce6be47a5b0bf8c82b44944eda4aefbac048172217d10187ec7ba, penalty 2039->3122 (max=3122)
2025-05-28T08:25:41Z CDeterministicMNList::PoSePunish -- banned MN a5a25d4c35bce6be47a5b0bf8c82b44944eda4aefbac048172217d10187ec7ba at height 2270346
2025-05-28T08:23:57Z ERROR: ConnectBlock(DASH): ProcessSpecialTxsInBlock for block 00000000000000253bbf25fe6552038e2358378103b9d3075015228a4455462b failed with Valid
2025-05-28T08:23:57Z ERROR: ConnectTip: ConnectBlock 00000000000000253bbf25fe6552038e2358378103b9d3075015228a4455462b failed, Valid

state is expected to don't be set, same issue on develop, because:

    if (!qc.Verify(m_dmnman, m_qsnapman, pQuorumBaseBlockIndex, /*checkSigs=*/fBLSChecks)) {        
        LogPrint(BCLog::LLMQ, "CQuorumBlockProcessor::%s height=%d, type=%d, quorumIndex=%d, quorumHash=%s, signers=%s, validMembers=%d, quorumPublicKey=%s qc verify failed.\n", __func__,                                                                                        
                 nHeight, ToUnderlying(qc.llmqType), qc.quorumIndex, quorumHash.ToString(), qc.CountSigners(), qc.CountValidMembers(), qc.quorumPublicKey.ToString());
        return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-qc-invalid");
    }

@knst knst added this to the 23 milestone May 28, 2025
@@ -52,8 +53,18 @@ CQuorumBlockProcessor::CQuorumBlockProcessor(CChainState& chainstate, CDetermini
m_qsnapman(qsnapman)
{
utils::InitQuorumsCache(mapHasMinedCommitmentCache);

int qc_threads = gArgs.GetIntArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
Copy link

Choose a reason for hiding this comment

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

Probably want a separate arg for this

// -par=-n means "leave n cores free" (number of cores - n - 1 validator threads)
qc_threads += GetNumCores();
}
m_bls_queue.StartWorkerThreads(qc_threads);
Copy link

Choose a reason for hiding this comment

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

The original script check logic has some additional limits

    // Subtract 1 because the main thread counts towards the par threads
    script_threads = std::max(script_threads - 1, 0);

    // Number of script-checking threads <= MAX_SCRIPTCHECK_THREADS
    script_threads = std::min(script_threads, MAX_SCRIPTCHECK_THREADS);

Shouldn't we have smth like that here too?

@knst knst marked this pull request as draft June 1, 2025 10:28
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