Skip to content
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

test: introduce basic unit tests for instantsend #6606

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

Conversation

PastaPastaPasta
Copy link
Member

What was done?

Introduce unit tests for some instantsend logic

How Has This Been Tested?

Running tests

Breaking Changes

Checklist:

Go over all the following points, and put an x in all the boxes that apply.

  • 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 (for repository code-owners and collaborators only)

@PastaPastaPasta PastaPastaPasta added this to the 23 milestone Mar 2, 2025
Copy link

coderabbitai bot commented Mar 2, 2025

Walkthrough

The changes introduce a new test file, test/evo_islock_tests.cpp, into the test suite by adding it to the BITCOIN_TESTS variable in src/Makefile.test.include. This file contains a test suite for InstantSend functionality, which includes two test cases. The first test case, getrequestid, creates an instance of llmq::CInstantSendLock, computes hash values for both empty and populated inputs vectors, and verifies that the computed request ID matches the expected hash values. The second test case, deserialize_instantlock_from_realdata2, validates the deserialization of an InstantSend lock from a hex string, extracting expected values from various fields (such as txid, cycleHash, and signature) and checking for consistency with the computed values. The tests utilize the Boost Test framework for assertions and ensure that the lock’s serialization and hash computations function as expected.

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

// Now add two dummy inputs to the lock
islock.inputs.clear();
// Construct two dummy outpoints (using uint256S for a dummy hash)
COutPoint op1(uint256S("0x0000000000000000000000000000000000000000000000000000000000000001"), 0);
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: coule use uint256::ONE and uint256::TWO here

Comment on lines 41 to 44
CHashWriter hw(SER_GETHASH, 0);
hw << std::string_view("islock");
hw << islock.inputs;
const uint256 expected = hw.GetHash();
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: refactor it to a function so far as it is used twice (see below)

BOOST_CHECK_EQUAL(input.n, expectedInputN);

// Compute the expected request ID: it is the hash of the constant prefix "islock" followed by the inputs.
CHashWriter hw(SER_GETHASH, 0);
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: refactor it to a function so far as it is used twice

ss >> islock;

// Verify the calculated signHash
auto signHash = llmq::BuildSignHash(Consensus::LLMQType::LLMQ_60_75, uint256S(quorumHash), islock.GetRequestId(), islock.txid);
Copy link
Collaborator

Choose a reason for hiding this comment

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

let's add one more unit test with other quorum type to be sure that this argument is used?

I think a check such as BOOST_CHECK(signHash.ToString() != expectedSignHash) is enough.

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.

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/test/evo_islock_tests.cpp (3)

69-69: Document the BLS scheme setting

Setting bls::bls_legacy_scheme.store(false) is critical for the test to work, but the reasoning behind this choice could be better documented. Consider adding a more detailed comment explaining why this setting is necessary and what would happen if it were set to true.


58-59: Define quorumHash consistently with other variables

While most string variables use std::string_view, quorumHash is defined as std::string. For consistency, consider using std::string_view for all string constants or provide a comment explaining why this particular variable needs to be a std::string.


1-104: Overall test coverage is comprehensive but could be expanded

The implementation provides good basic coverage of the InstantSend functionality, with tests for request ID calculation and deserialization from real data. To further improve coverage, consider:

  1. Adding tests with different quorum types as previously suggested
  2. Testing the serialization process (not just deserialization)
  3. Adding tests for edge cases or error conditions

These tests provide a solid foundation but expanding them would further enhance the robustness of the codebase.

🧰 Tools
🪛 Cppcheck (2.10-2)

[error] 13-13: There is an unknown macro here somewhere. Configuration is required. If BOOST_AUTO_TEST_SUITE is a macro then please configure it.

(unknownMacro)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 674d541 and 53799cd.

📒 Files selected for processing (1)
  • src/test/evo_islock_tests.cpp (1 hunks)
🧰 Additional context used
🪛 Cppcheck (2.10-2)
src/test/evo_islock_tests.cpp

[error] 13-13: There is an unknown macro here somewhere. Configuration is required. If BOOST_AUTO_TEST_SUITE is a macro then please configure it.

(unknownMacro)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: arm-linux-build / Build source
  • GitHub Check: x86_64-w64-mingw32 / Build depends
  • GitHub Check: x86_64-pc-linux-gnu / Build depends
  • GitHub Check: x86_64-pc-linux-gnu_nowallet / Build depends
  • GitHub Check: x86_64-pc-linux-gnu_multiprocess / Build depends
🔇 Additional comments (6)
src/test/evo_islock_tests.cpp (6)

15-21: Helper function well implemented

The CalculateRequestId function is cleanly implemented to mirror the internal functionality of CInstantSendLock::GetRequestId(). This is good practice for unit tests as it provides an independent verification mechanism.


23-48: Test case covers empty and non-empty inputs correctly

The getrequestid test case appropriately verifies the request ID calculation for both an empty inputs vector and one with dummy inputs. Good use of uint256::ONE and uint256::TWO for creating test outpoints.


40-42: Dummy outpoints correctly constructed

Good use of the predefined constants uint256::ONE and uint256::TWO for creating test outpoints rather than manually constructing arbitrary values.


50-102: Consider adding a test with different quorum types

The deserialization test is thorough, verifying multiple aspects of the deserialized data including hashes, transaction ID, cycle hash, inputs, and signature. However, as previously suggested, it would be beneficial to add a test with a different quorum type to ensure that parameter is properly handled.

You could add a variation of the current test where you use a different quorum type and verify that the signature hash changes, with something like:

// Test with a different quorum type
auto signHashAlt = llmq::BuildSignHash(Consensus::LLMQType::LLMQ_400_60, uint256S(quorumHash), islock.GetRequestId(), islock.txid);
BOOST_CHECK(signHashAlt != signHash);

77-80: Add test for different quorum types

This section tests only one quorum type (LLMQ_60_75). As previously suggested, it would be valuable to add a test case with a different quorum type to verify that the BuildSignHash function properly handles different quorum types.


97-98: Good verification of request ID calculation

The test correctly verifies that the calculated request ID matches the expected value derived from the inputs. This ensures consistency between the internal implementation and the test's expectations.

knst
knst previously approved these changes Mar 10, 2025
Copy link
Collaborator

@knst knst left a comment

Choose a reason for hiding this comment

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

utACK 53799cd

@UdjinM6
Copy link

UdjinM6 commented Mar 10, 2025

pls consider 98b20c8

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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/test/evo_islock_tests.cpp (1)

67-67: Consider restoring the BLS legacy scheme setting.

The test changes the BLS legacy scheme setting but doesn't restore it afterward. This could potentially affect other tests that rely on a different setting.

+ bool original_legacy_scheme = bls::bls_legacy_scheme.load();
  bls::bls_legacy_scheme.store(false);
+ // Scope cleanup or defer
+ struct BLSLegacySchemeGuard {
+     bool original_value;
+     BLSLegacySchemeGuard(bool val) : original_value(val) {}
+     ~BLSLegacySchemeGuard() { bls::bls_legacy_scheme.store(original_value); }
+ } guard(original_legacy_scheme);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 53799cd and 6faf34d.

📒 Files selected for processing (1)
  • src/test/evo_islock_tests.cpp (1 hunks)
🧰 Additional context used
🪛 Cppcheck (2.10-2)
src/test/evo_islock_tests.cpp

[error] 12-12: There is an unknown macro here somewhere. Configuration is required. If BOOST_AUTO_TEST_SUITE is a macro then please configure it.

(unknownMacro)

🔇 Additional comments (6)
src/test/evo_islock_tests.cpp (6)

14-20: Good implementation of the helper function.

Nice work creating a clean helper function for calculating the request ID. This function is reused across multiple test cases, which promotes code reuse and maintainability.


39-40: Good use of predefined constants.

You've implemented the previous review suggestion by using uint256::ONE and uint256::TWO instead of manually creating these values.


22-47: Well-structured test for GetRequestId functionality.

The test case properly validates the GetRequestId method with both empty and populated inputs vectors. This ensures the hash calculation works correctly in both scenarios.


49-100: Comprehensive deserialization test with real-world data.

Excellent test case that uses real-world data to verify the deserialization of an InstantSend lock. The test covers all important fields and validates the relationship between the inputs and the request ID.


1-102: Good implementation of the InstantSend test suite.

Overall, this is a well-written test suite that covers important functionality of the InstantSend feature. The tests are detailed, use real-world data where appropriate, and ensure that critical functionality works as expected.

🧰 Tools
🪛 Cppcheck (2.10-2)

[error] 12-12: There is an unknown macro here somewhere. Configuration is required. If BOOST_AUTO_TEST_SUITE is a macro then please configure it.

(unknownMacro)


76-78:

❓ Verification inconclusive

Consider adding a test with a different quorum type.

A previous review suggested adding a test with a different quorum type to verify that the quorum type argument is properly used. This would ensure that BuildSignHash handles different quorum types correctly.


🏁 Script executed:

#!/bin/bash
# Check if there are other tests for different quorum types
ast-grep --pattern $'BuildSignHash\(Consensus::LLMQType::$_, $_' 

Length of output: 231


Action: Expand test coverage for BuildSignHash quorum types

The current test in src/test/evo_islock_tests.cpp uses Consensus::LLMQType::LLMQ_60_75 exclusively. Our initial search (filtered to avoid non-UTF-8 files) did not reveal any tests that use an alternative quorum type. To ensure that the quorum type argument is correctly handled by BuildSignHash, please add a test case using a different quorum type.

Verify manually that no such additional tests exist in your codebase, and once added, confirm that the function behaves as expected with multiple quorum types.

UdjinM6
UdjinM6 previously approved these changes Mar 13, 2025
Copy link

@UdjinM6 UdjinM6 left a comment

Choose a reason for hiding this comment

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

utACK 6faf34d, one nit

Co-authored-by: UdjinM6 <[email protected]>
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.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/test/evo_islock_tests.cpp (2)

36-43: Consider removing redundant clear() call

Line 37 calls islock.inputs.clear() immediately after creating an empty InstantSendLock object, which already has an empty inputs vector.

    // Now add two dummy inputs to the lock
-   islock.inputs.clear();
    // Construct two dummy outpoints (using uint256S for a dummy hash)
    COutPoint op1(uint256::ONE, 0);
    COutPoint op2(uint256::TWO, 1);
    islock.inputs.push_back(op1);
    islock.inputs.push_back(op2);

68-68: Restore global state after modifying bls_legacy_scheme

This line changes a global state that could potentially affect other tests. Consider restoring it to its original value at the end of the test.

    // This islock was created with non-legacy. Using legacy will result in the signature being all zeros.
    bls::bls_legacy_scheme.store(false);
+   // Save original value to restore later
+   const bool original_bls_legacy_scheme = bls::bls_legacy_scheme.load();
+   bls::bls_legacy_scheme.store(false);
+   
+   // ... rest of the test ...
+   
+   // Restore original value
+   bls::bls_legacy_scheme.store(original_bls_legacy_scheme);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e812ca3 and 4f00407.

📒 Files selected for processing (1)
  • src/test/evo_islock_tests.cpp (1 hunks)
🧰 Additional context used
🪛 Cppcheck (2.10-2)
src/test/evo_islock_tests.cpp

[error] 12-12: There is an unknown macro here somewhere. Configuration is required. If BOOST_AUTO_TEST_SUITE is a macro then please configure it.

(unknownMacro)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: x86_64-w64-mingw32 / Build depends
  • GitHub Check: x86_64-apple-darwin / Build depends
  • GitHub Check: x86_64-pc-linux-gnu_nowallet / Build depends
  • GitHub Check: x86_64-pc-linux-gnu / Build depends
  • GitHub Check: x86_64-pc-linux-gnu_multiprocess / Build depends
  • GitHub Check: arm-linux-gnueabihf / Build depends
🔇 Additional comments (5)
src/test/evo_islock_tests.cpp (5)

1-11: Well-structured includes with clear organization

The includes are appropriately selected for the testing requirements, with a helpful comment explaining the purpose of util/strencodings.h for constructing dummy outpoints.


14-20: Good extraction of common logic into a helper function

This helper function cleanly encapsulates the hash calculation logic that's used in multiple test cases. It follows the same logic as the implementation being tested while keeping the test code DRY.


77-79: Add test with a different quorum type

As mentioned in a previous review, it would be beneficial to verify that the quorum type argument is correctly used in the BuildSignHash function by adding a test with a different quorum type.

    // Verify the calculated signHash
    auto signHash = llmq::BuildSignHash(Consensus::LLMQType::LLMQ_60_75, uint256S(quorumHashStr), islock.GetRequestId(),
                                      islock.txid);
    BOOST_CHECK_EQUAL(signHash.ToString(), expectedSignHashStr);
+
+   // Verify that a different quorum type produces a different signHash
+   auto differentSignHash = llmq::BuildSignHash(Consensus::LLMQType::LLMQ_400_60, uint256S(quorumHashStr), islock.GetRequestId(),
+                                           islock.txid);
+   BOOST_CHECK(signHash != differentSignHash);

96-97: Consider reusing the CalculateRequestId helper function in both test cases

This is a good example of code reuse between test cases. The helper function ensures consistency in how the expected request ID is calculated.


49-101: Comprehensive test for InstantSend lock deserialization

This test provides thorough validation of the deserialization process using real-world data. It verifies multiple aspects of the deserialized lock (signHash, txid, cycleHash, inputs, requestId, signature) which is excellent for ensuring the code works correctly with actual network data.

Copy link

@UdjinM6 UdjinM6 left a comment

Choose a reason for hiding this comment

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

utACK 4f00407

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