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

backport: merge bitcoin#21845, #22732, #23542, #24468, #25119, #25176, #25421, #26248, #26199, #27036, #27270, partial bitcoin#27106 (networking backports: part 10) #6532

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

Conversation

kwvg
Copy link
Collaborator

@kwvg kwvg commented Jan 13, 2025

Additional Information

  • Due to changes introduced in bitcoin#21845, a LOCK(cs_main) had to be added to PeerManagerImpl::ReattemptInitialBroadcast() (source). This addition is in line with upstream (source).

  • While nodes have been allowed to connect to non-default ports since dash#2168, bitcoin#23542 also adds a list of ports considered "bad" that while not outright prohibited, are heavily discouraged from use as they are considered de facto prohibited.

    In combination with port restrictions for masternodes (connections only permitted if matching listening port), port validation logic was better served by implementing it in a lambda block that's immediately executed (see is_prohibited_port for more information, source).

  • In bitcoin#25176, is_block_relay is renamed to is_tx_relay as the block relay-only = not transaction-relay assumption no longer holds true (see dash#6365 for more information). One use of is_block_relay which relied on this now-obsolete assumption is incrementing m_block_relay_peers_count. It has been replaced with checking for a block-relay-only conn_type, matching upstream (source).

Breaking Changes

None expected.

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

@kwvg kwvg added this to the 22.1 milestone Jan 13, 2025
@kwvg kwvg marked this pull request as ready for review January 14, 2025 08:54
Copy link

coderabbitai bot commented Jan 14, 2025

Walkthrough

This pull request introduces a comprehensive set of changes across multiple files in the Dash Core codebase, focusing on network connectivity, socket handling, transaction relay, and documentation. The modifications include adding a new documentation file about P2P bad ports, refactoring socket and peer management functions, updating transaction relay logic, and enhancing testing frameworks.

Key areas of change include the introduction of methods to handle "bad" ports, modifications to how peers are classified and connected, updates to socket selectability and non-blocking operations, and improvements in transaction relay mechanisms. The changes aim to improve network security, connection management, and overall code structure by centralizing certain functionalities and providing more precise control over network interactions.

The pull request also includes updates to test frameworks and functional tests to support and validate these new network-related features, ensuring robust implementation of the proposed changes.

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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. (Beta)
  • @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.

Actionable comments posted: 3

🧹 Nitpick comments (11)
src/net.cpp (5)

3145-3145: Remove redundant 'net:' prefix in log message

The logging category BCLog::NET already indicates that this log message is related to the network. Including 'net:' in the message is redundant.

Apply this diff to remove the redundant prefix:

-    LogPrint(BCLog::NET, "net: enabling extra block-relay-only peers\n");
+    LogPrint(BCLog::NET, "enabling extra block-relay-only peers\n");

3552-3552: Fix typo in comment

The word 'arbitary' is misspelled. It should be 'arbitrary' in the comment.

Apply this diff to correct the typo:

-// from using a non-default port while others allow any arbitary port so long
+// from using a non-default port while others allow any arbitrary port so long

3553-3553: Improve clarity in comment

Consider adding 'as' after 'so long' to enhance the clarity of the comment.

Apply this diff to improve the comment:

-// it isn't a bad port (and in the case of masternodes, it matches its listen
+// as it isn't a bad port (and in the case of masternodes, it matches its listen

4250-4251: Ensure consistent use of bilingual_str in ThreadSafeMessageBox

The ThreadSafeMessageBox function may expect a bilingual_str for proper localization support. Ensure that strError is a bilingual_str and that unnecessary conversions are avoided.

If strError is already a bilingual_str, pass it directly:

-                m_client_interface->ThreadSafeMessageBox(strError, "", CClientUIInterface::MSG_ERROR);
+                m_client_interface->ThreadSafeMessageBox(strError, /*caption=*/"", CClientUIInterface::MSG_ERROR);

If strError is a std::string, consider changing it to a bilingual_str.


4302-4302: Pass bilingual_str to ThreadSafeMessageBox

Similar to the previous comment, ensure that you're passing a bilingual_str to ThreadSafeMessageBox to support localization.

If the message is translatable, wrap it with _() to create a bilingual_str:

-            m_client_interface->ThreadSafeMessageBox(
-                _("Cannot provide specific connections and have addrman find outgoing connections at the same time."),
+            m_client_interface->ThreadSafeMessageBox(
+                _("Cannot provide specific connections and have addrman find outgoing connections at the same time."),
                 "", CClientUIInterface::MSG_ERROR);
src/netbase.cpp (1)

708-795: Consider adding more commonly exploited ports

The implementation provides a good baseline of prohibited ports, but consider adding these commonly exploited ports:

  • Port 445 (Microsoft-DS)
  • Port 3389 (RDP)
  • Port 5900 (VNC)
 case 6697:  // IRC + TLS
 case 10080: // Amanda
+case 445:   // Microsoft-DS
+case 3389:  // RDP
+case 5900:  // VNC
     return true;
src/test/netbase_tests.cpp (1)

437-455: Enhance test coverage for edge cases

While the test provides good basic coverage, consider adding:

  1. Edge case tests for port numbers 0 and 65535
  2. Tests for sequential port ranges (e.g., IRC ports 6665-6669)
  3. Tests for related services (e.g., if SMTP port 25 is bad, test SMTPS port 465)
 BOOST_AUTO_TEST_CASE(isbadport)
 {
     BOOST_CHECK(IsBadPort(1));
     BOOST_CHECK(IsBadPort(22));
     BOOST_CHECK(IsBadPort(6000));
+    BOOST_CHECK(!IsBadPort(0));
+    BOOST_CHECK(!IsBadPort(65535));
 
     BOOST_CHECK(!IsBadPort(80));
     BOOST_CHECK(!IsBadPort(443));
     BOOST_CHECK(!IsBadPort(8333));
 
+    // Test sequential IRC ports
+    BOOST_CHECK(IsBadPort(6665));
+    BOOST_CHECK(IsBadPort(6666));
+    BOOST_CHECK(IsBadPort(6667));
+    BOOST_CHECK(IsBadPort(6668));
+    BOOST_CHECK(IsBadPort(6669));
+
+    // Test related services
+    BOOST_CHECK(IsBadPort(25));   // SMTP
+    BOOST_CHECK(IsBadPort(465));  // SMTPS
+    BOOST_CHECK(IsBadPort(587));  // SMTP Submission
+
     // Check all ports, there must be 80 bad ports in total.
doc/p2p-bad-ports.md (1)

104-114: Improve document formatting for better readability.

Consider the following formatting improvements:

  1. Add a blank line before "For further information see:"
  2. Format references as a bullet list for better readability

Here's the suggested format:

+
 For further information see:

-[pull/23306](https://github.com/bitcoin/bitcoin/pull/23306#issuecomment-947516736)
-
-[pull/23542](https://github.com/bitcoin/bitcoin/pull/23542)
-
-[fetch.spec.whatwg.org](https://fetch.spec.whatwg.org/#port-blocking)
-
-[chromium.googlesource.com](https://chromium.googlesource.com/chromium/src.git/+/refs/heads/main/net/base/port_util.cc)
-
-[hg.mozilla.org](https://hg.mozilla.org/mozilla-central/file/tip/netwerk/base/nsIOService.cpp)
+* [Bitcoin PR #23306](https://github.com/bitcoin/bitcoin/pull/23306#issuecomment-947516736)
+* [Bitcoin PR #23542](https://github.com/bitcoin/bitcoin/pull/23542)
+* [WHATWG Fetch Spec - Port Blocking](https://fetch.spec.whatwg.org/#port-blocking)
+* [Chromium Port Util Implementation](https://chromium.googlesource.com/chromium/src.git/+/refs/heads/main/net/base/port_util.cc)
+* [Mozilla Port Blocking Implementation](https://hg.mozilla.org/mozilla-central/file/tip/netwerk/base/nsIOService.cpp)
🧰 Tools
🪛 LanguageTool

[uncategorized] ~104-~104: Possible missing comma found.
Context: ...RC + TLS 10080: Amanda For further information see: [pull/23306](https://github.com/b...

(AI_HYDRA_LEO_MISSING_COMMA)

src/net_processing.cpp (2)

32-32: Consider reordering includes for consistency

The addition of #include <sync.h> appears between #include <streams.h> and #include <timedata.h>, which may not follow the include ordering conventions. It's recommended to group includes by category and sort them alphabetically within each group to maintain consistency.


648-649: Rename _RelayTransaction for naming consistency

The method _RelayTransaction uses a leading underscore, which may not align with the project's naming conventions. Consider renaming it to RelayTransactionImpl or similar to maintain consistency and avoid reserved identifier usage.

Apply this diff to rename the method:

-void _RelayTransaction(const uint256& txid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
+void RelayTransactionImpl(const uint256& txid) EXCLUSIVE_LOCKS_REQUIRED(cs_main);

Similarly, update all references to _RelayTransaction to RelayTransactionImpl.

src/init.cpp (1)

569-570: Remove TODO comment after changes are widely deployed.

This comment should be removed once the changes from Bitcoin PR bitcoin#23542 regarding non-default ports are widespread.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4e39489 and 01975fb.

📒 Files selected for processing (26)
  • doc/README.md (1 hunks)
  • doc/p2p-bad-ports.md (1 hunks)
  • src/bitcoin-cli.cpp (4 hunks)
  • src/compat/compat.h (0 hunks)
  • src/init.cpp (3 hunks)
  • src/masternode/node.cpp (1 hunks)
  • src/net.cpp (10 hunks)
  • src/net.h (3 hunks)
  • src/net_processing.cpp (15 hunks)
  • src/net_processing.h (1 hunks)
  • src/netaddress.cpp (0 hunks)
  • src/netaddress.h (2 hunks)
  • src/netbase.cpp (4 hunks)
  • src/netbase.h (1 hunks)
  • src/node/transaction.cpp (0 hunks)
  • src/test/dbwrapper_tests.cpp (2 hunks)
  • src/test/fuzz/netaddress.cpp (1 hunks)
  • src/test/fuzz/util.cpp (2 hunks)
  • src/test/fuzz/util.h (2 hunks)
  • src/test/netbase_tests.cpp (1 hunks)
  • src/test/util/net.h (1 hunks)
  • src/util/sock.cpp (2 hunks)
  • src/util/sock.h (1 hunks)
  • test/functional/p2p_blocksonly.py (1 hunks)
  • test/functional/test_framework/p2p.py (1 hunks)
  • test/lint/lint-locale-dependence.py (0 hunks)
💤 Files with no reviewable changes (4)
  • src/compat/compat.h
  • src/node/transaction.cpp
  • test/lint/lint-locale-dependence.py
  • src/netaddress.cpp
🧰 Additional context used
🪛 LanguageTool
doc/p2p-bad-ports.md

[uncategorized] ~104-~104: Possible missing comma found.
Context: ...RC + TLS 10080: Amanda For further information see: [pull/23306](https://github.com/b...

(AI_HYDRA_LEO_MISSING_COMMA)

🔇 Additional comments (31)
src/net.cpp (1)

3563-3563: Verify masternode port restriction

The condition addr.GetPort() != GetListenPort() restricts connections to masternodes only if they are using the same port as our node's listening port. Please verify if this restriction is necessary. Masternodes might operate on different ports, and enforcing this could limit connectivity.

src/net_processing.h (1)

114-114: Verify thread safety after lock annotation removal.

The removal of EXCLUSIVE_LOCKS_REQUIRED(cs_main) from RelayTransaction suggests that locking is now handled internally. Please ensure that all call sites are properly synchronized.

✅ Verification successful

Thread safety is properly maintained after lock annotation removal

The implementation ensures thread safety by acquiring cs_main lock internally in RelayTransaction before calling _RelayTransaction. The change simplifies the interface while maintaining proper synchronization.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct calls to RelayTransaction to verify proper synchronization
ast-grep --pattern 'RelayTransaction($hash)'

Length of output: 212


Script:

#!/bin/bash
# Find interface declarations and implementations
ast-grep --pattern 'RelayTransaction($_) $_'

# Find direct method calls
rg "RelayTransaction\(" -A 2

# Check for any locking mechanisms around the implementation
rg "cs_main" -A 3 -B 3

Length of output: 69911

test/functional/p2p_blocksonly.py (1)

60-60: LGTM! Enhanced test coverage for relay permissions.

The added assertion properly verifies that the peer has the expected relay permission when restarted with relay permission and blocksonly mode.

src/netbase.h (1)

249-256: LGTM! Consider adding comprehensive unit tests.

The IsBadPort function is well-documented and provides a clear interface for validating ports. This is important for security as it helps prevent connections to potentially dangerous ports.

src/util/sock.h (1)

193-204: LGTM! Excellent use of modern C++ practices.

The new methods demonstrate good practices:

  • Use of [[nodiscard]] to prevent ignoring critical return values
  • Virtual methods enabling proper polymorphic behavior
  • Clear documentation explaining the purpose of each method
src/masternode/node.cpp (1)

165-165: LGTM: Socket selectability check refactored correctly.

The change moves the socket selectability check into the Sock class, improving encapsulation and maintainability.

src/util/sock.cpp (3)

128-145: LGTM: Well-implemented platform-specific non-blocking socket configuration.

The implementation correctly handles both Windows and POSIX systems, with proper error handling and status reporting.


147-154: LGTM: Platform-aware socket selectability check.

The implementation correctly handles platform differences:

  • Always returns true for systems using poll or Windows
  • Checks against FD_SETSIZE for other platforms

185-185: LGTM: Updated Wait method to use new IsSelectable check.

Consistent with the socket handling refactoring.

src/test/dbwrapper_tests.cpp (3)

8-8: LGTM: Added required header for string utilities.


341-343: LGTM: Improved deserialization robustness.

The new implementation using stream eof check is more reliable for handling serialized data.


352-368: LGTM: Enhanced key generation with better type safety.

Replacing string formatting with ToString improves type safety and readability.

src/test/fuzz/util.cpp (3)

17-17: LGTM: Proper initialization of selectability state.

Constructor correctly initializes the new m_selectable member with fuzzed data.


260-271: LGTM: Well-implemented fuzz testing for non-blocking socket operations.

The implementation correctly simulates possible error conditions with appropriate errno values.


273-276: LGTM: Simple and effective selectability check for fuzz testing.

Returns the fuzzed boolean value, providing good test coverage for socket selectability handling.

src/test/fuzz/util.h (1)

56-61: Well-structured socket selectability implementation!

Good practices observed:

  • Clear documentation of the m_selectable member variable
  • Use of const for thread safety
  • Proper use of override keyword for virtual methods

Also applies to: 90-92

src/netaddress.h (1)

564-570: Secure implementation of service hashing!

Good security practices:

  • Using cryptographically secure random number generation for salt initialization
  • Proper const-correctness for salt values
  • Parameterized constructor enables testing while keeping default constructor secure

Also applies to: 582-583

src/netbase.cpp (2)

291-291: LGTM: Updated documentation reflects API changes

The comment accurately reflects the socket non-blocking functionality changes.


703-705: LGTM: Clean implementation of interrupt mechanism

Simple and effective implementation using atomic flag.

test/functional/test_framework/p2p.py (1)

613-613: LGTM: Added relay attribute from version message

The addition of self.relay attribute properly captures the relay capability from the version message.

src/net.h (1)

1466-1466: LGTM: Method declaration for starting extra block relay peers

Clean method declaration for managing extra block relay peers.

doc/README.md (1)

79-79: LGTM!

The new documentation link is well-placed and follows the existing format.

doc/p2p-bad-ports.md (1)

1-22: LGTM! Clear and comprehensive documentation.

The document provides an excellent explanation of P2P bad ports, their implications, and the rationale behind avoiding them. The content is technically accurate and valuable for both developers and users.

src/net_processing.cpp (4)

1459-1460: Ensure correct transaction relay flag in version message

The tx_relay flag is correctly set based on the RejectIncomingTxs(pnode) function, ensuring that the VERSION message reflects whether the peer should relay transactions.


1634-1635: Add missing lock before calling _RelayTransaction

The LOCK(cs_main); statement is added before calling _RelayTransaction(txid); to ensure thread safety, complying with the EXCLUSIVE_LOCKS_REQUIRED(cs_main) annotation on _RelayTransaction.


2434-2438: Consistent naming for private relay transaction method

The public method RelayTransaction calls the private method _RelayTransaction. To maintain naming consistency and avoid leading underscores, consider renaming _RelayTransaction as suggested earlier.


5739-5741: Properly reject incoming transactions from feeler connections

The addition of if (peer.IsFeelerConn()) return true; ensures that transactions from feeler connections are rejected, adhering to the expected behavior for such temporary connections.

src/test/util/net.h (1)

206-206: Verify method signature for IsSelectable

Ensure that the IsSelectable() method signature, including the const qualifier, matches the base class method. If the base class method is non-const, adjust accordingly to avoid overriding issues.

src/bitcoin-cli.cpp (1)

437-437: LGTM! Improved naming and logic for transaction relay handling.

The changes correctly rename is_block_relay to is_tx_relay and update the associated logic to better reflect the actual functionality. The implementation aligns with Bitcoin PR bitcoin#25176.

Also applies to: 501-501, 507-507, 530-530, 564-564

src/init.cpp (2)

2275-2281: LGTM! Well-designed reusable warning message function.

The BadPortWarning lambda is well-structured and provides consistent warning messages for bad ports, with proper documentation references.


2290-2292: LGTM! Comprehensive port validation with user-friendly warnings.

The implementation adds proper validation for potentially problematic ports in both -bind and -port arguments, with clear warning messages directing users to documentation.

Also applies to: 2320-2327

@@ -4303,7 +4325,9 @@ bool CConnman::Start(CDeterministicMNManager& dmnman, CMasternodeMetaMan& mn_met
LogPrintf("%i block-relay-only anchors will be tried for connections.\n", m_anchors.size());
}

uiInterface.InitMessage(_("Starting network threads…").translated);
if (m_client_interface) {
m_client_interface->InitMessage(_("Starting network threads…").translated);
Copy link

@coderabbitai coderabbitai bot Jan 14, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid unnecessary .translated when passing bilingual_str

The InitMessage function expects a bilingual_str parameter. Using .translated converts it to a std::string, which may not be intended. Pass the bilingual_str directly without calling .translated.

Apply this diff to fix the issue:

-            m_client_interface->InitMessage(_("Starting network threads…").translated);
+            m_client_interface->InitMessage(_("Starting network threads…"));
📝 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.

Suggested change
m_client_interface->InitMessage(_("Starting network threads…").translated);
m_client_interface->InitMessage(_("Starting network threads…"));

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

The commit that introduces that change only does the switchover from uiInterface to m_client_interface, anything other than that is out-of-scope for that commit.

Copy link

Choose a reason for hiding this comment

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

@kwvg You're absolutely right - I apologize for suggesting a change outside the scope of this commit. The commit should stay focused on just the uiInterface to m_client_interface switchover. Thank you for the feedback.


✏️ Learnings added
Learnt from: kwvg
PR: dashpay/dash#6532
File: src/net.cpp:4329-4329
Timestamp: 2025-01-14T09:07:12.264Z
Learning: Keep suggestions focused on the scope of the current commit/PR. Avoid suggesting unrelated improvements that should be handled in separate PRs, even if technically valid.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment on lines +83 to +84
(void)CServiceHash()(service);
(void)CServiceHash(0, 0)(service);
Copy link

@coderabbitai coderabbitai bot Jan 14, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Verify the usage of CServiceHash function object

The calls to CServiceHash()(service); and CServiceHash(0, 0)(service); should be verified to ensure that the CServiceHash class supports such constructors and that these calls are valid. The constructor CServiceHash(0, 0) may not exist or may not be intended for use in this way.

Apply this diff to correct the usage:

-        (void)CServiceHash()(service);
-        (void)CServiceHash(0, 0)(service);
+        (void)CServiceHash(service);

Alternatively, ensure that the correct constructor and method are used according to the CServiceHash implementation.

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

But both constructors exist and the code cited is from the fuzzer harness, where both variants are tested

dash/src/netaddress.h

Lines 564 to 570 in 01975fb

CServiceHash()
: m_salt_k0{GetRand(std::numeric_limits<uint64_t>::max())},
m_salt_k1{GetRand(std::numeric_limits<uint64_t>::max())}
{
}
CServiceHash(uint64_t salt_k0, uint64_t salt_k1) : m_salt_k0{salt_k0}, m_salt_k1{salt_k1} {}

Copy link

Choose a reason for hiding this comment

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

@kwvg You are absolutely right. I apologize for the incorrect warning. Both constructors exist in CServiceHash and the fuzzer is correctly testing both variants. Thank you for the clarification.


✏️ Learnings added
Learnt from: kwvg
PR: dashpay/dash#6532
File: src/test/fuzz/netaddress.cpp:83-84
Timestamp: 2025-01-14T09:06:18.984Z
Learning: In fuzzer harness tests, CServiceHash can be used with both default constructor (CServiceHash()) and parameterized constructor (CServiceHash(salt_k0, salt_k1)) to test different variants. The usage pattern CServiceHash()(service) and CServiceHash(0, 0)(service) is valid and intentional in such tests.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

@@ -201,6 +201,10 @@ class StaticContentsSock : public Sock
return 0;
}

bool SetNonBlocking() const override { return true; }
Copy link

@coderabbitai coderabbitai bot Jan 14, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct constness of SetNonBlocking() method

The SetNonBlocking() method in StaticContentsSock is marked const, but it overrides a base class method that is likely non-const. Marking it const may lead to incorrect overriding and compiler warnings or errors. Consider removing the const qualifier.

Apply this diff to correct the constness:

-    bool SetNonBlocking() const override { return true; }
+    bool SetNonBlocking() override { return true; }

Ensure that the method signature matches the base class to prevent overriding errors.

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

Suggested change
bool SetNonBlocking() const override { return true; }
bool SetNonBlocking() override { return true; }

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

But they're const everywhere

bool SetNonBlocking() const override;

bool SetNonBlocking() const override { return true; }

dash/src/util/sock.h

Lines 193 to 197 in 01975fb

/**
* Set the non-blocking option on the socket.
* @return true if set successfully
*/
[[nodiscard]] virtual bool SetNonBlocking() const;

Copy link

Choose a reason for hiding this comment

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

@kwvg You are absolutely correct. I apologize for my earlier review. The const qualifier on SetNonBlocking() is correct as it matches the base class Sock's virtual method declaration and is consistently used across all implementations. Thank you for pointing this out.


✏️ Learnings added
Learnt from: kwvg
PR: dashpay/dash#6532
File: src/test/util/net.h:204-204
Timestamp: 2025-01-14T09:05:11.844Z
Learning: The SetNonBlocking() method in Sock and its derived classes is correctly marked const as it doesn't modify the socket's internal state, only its blocking mode configuration.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

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.

1 participant