-
Notifications
You must be signed in to change notification settings - Fork 1.2k
refactor: reduce PeerManager
usage in InstantSend worker functions
#6821
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
Conversation
✅ No Merge Conflicts DetectedThis PR currently has no conflicts with other open PRs. |
…geProcessingResult`, drop `PeerMsgRet` 491ae50 revert: new util class `expected` for return errors by more convenient way (Kittywhiskers Van Gogh) 2020757 trivial: remove `PeerMsgRet` handling logic (Kittywhiskers Van Gogh) 5d1222e chore: drop govobj/govobjvote counts, use `ret.m_inventory.size()` (UdjinM6) 4822b93 refactor: allow submitting multiple `CInv`s to `MessageProcessingResult` (Kittywhiskers Van Gogh) 0517aff refactor: mark `RelayInv{,Filtered}`'s `CInv` argument as const (Kittywhiskers Van Gogh) 9084530 refactor: migrate `CGovernanceManager::ProcessMessage()` and friends (Kittywhiskers Van Gogh) 8b9bf7c refactor: migrate `CCoinJoinServer::ProcessMessage()` (Kittywhiskers Van Gogh) 1d50a1a refactor: migrate `CCoinJoinClientQueueManager::ProcessMessage()` (Kittywhiskers Van Gogh) 6352baf refactor: migrate `CMNAuth::ProcessMessage()` (Kittywhiskers Van Gogh) 9f85bd0 refactor: migrate `CInstantSendManager::ProcessMessage()` (Kittywhiskers Van Gogh) ef4a0bb refactor: migrate `CDKGSessionManager::ProcessMessage()` and friends (Kittywhiskers Van Gogh) 93d68b8 refactor: migrate `CQuorumManager::ProcessMessage()` (Kittywhiskers Van Gogh) 1bbcb95 refactor: migrate `CSporkManager::ProcessMessage()` and friends (Kittywhiskers Van Gogh) e7b23a2 refactor: migrate `CSigningManager::ProcessMessage()` (Kittywhiskers Van Gogh) f3b98ce chore: add redefinition of `NodeId` to avoid repetitive redefinition (Kittywhiskers Van Gogh) f341ef5 chore: add `nodiscard` attrib to `MessageProcessingResult` ret functions (Kittywhiskers Van Gogh) Pull request description: ## Additional Information * Dependency for #6821 * To avoid having to redeclare `NodeId` repeatedly to avoid circular dependencies from including `net.h` ([source](https://github.com/dashpay/dash/blob/fb87a5a937dd232d4f2ae60b5b8c5c29d49cb92f/src/net.h#L121)), a redeclaration is made in the relatively lightweight `net_types.h` that as of `develop` (fb87a5a), doesn't have includes outside the standard library ([source](https://github.com/dashpay/dash/blob/fb87a5a937dd232d4f2ae60b5b8c5c29d49cb92f/src/net_types.h#L8-L10)). Redeclarations were flagged during review (see [comment](#6820 (comment)), [comment](#6820 (comment))). * As `tl::expected` was introduced alongside `PeerMsgRet` in [dash#5782](#5782) and has not been used elsewhere, we can safely remove it as we've finished migrating all usage to `MessageProcessingResult`. ## Breaking Changes None expected. ## Checklist - [x] I have performed a self-review of my own code - [x] I have commented my code, particularly in hard-to-understand areas **(note: N/A)** - [x] I have added or updated relevant unit/integration/functional/e2e tests - [x] I have made corresponding changes to the documentation **(note: N/A)** - [x] I have assigned this pull request to a milestone _(for repository code-owners and collaborators only)_ ACKs for top commit: knst: utACK 491ae50 UdjinM6: utACK 491ae50 Tree-SHA512: c37fe6370555f1c33877fa5a335356e2febf25c2d0d954fa44623f49994647ea2a10aec5ceb9e788bb6fa9315dc00b3e54ca8e0da96c7899fb31c30b888eb732
This pull request has conflicts, please rebase. |
…ons, ChainLock and InstantSend refactoring 34a90e6 chore: remove unused `IsInvInFilter` from `PeerManager` interface (Kittywhiskers Van Gogh) f3224ae refactor: consolidate `INPUTLOCK_REQUESTID_PREFIX` usage to `lock.cpp` (Kittywhiskers Van Gogh) 7b4ee6b trivial: document transaction confirmation safety threshold (Kittywhiskers Van Gogh) 25f05c1 refactor: make unknown block clsig flow easier to follow (Kittywhiskers Van Gogh) 9578146 refactor: document `pindex` assumptions in chainlocks code (Kittywhiskers Van Gogh) 4a744c7 refactor: use `std::chrono` for time variables, reduce resolution (Kittywhiskers Van Gogh) b051c22 refactor: consolidate `CLSIG_REQUESTID_PREFIX` usage to `clsig.cpp` (Kittywhiskers Van Gogh) 024b466 chore: move lock annotations in `chainlock.h` to the next line (Kittywhiskers Van Gogh) c6e99fb chore: apply most `clang-format` suggestions (Kittywhiskers Van Gogh) Pull request description: ## Additional Information * Depends on #6761 * Dependency for #6821 * Assumptions surrounding `pindex` usage have been documented in response to reviewer comments in [dash#6761](#6761) ([comment](#6761 (comment)), [comment](#6761 (comment))). * The internal structures of `CChainLocksHandler` (`txFirstSeenTime`, `seenChainLocks`, `lastCleanupTime`) have their time resolution reduced from milliseconds to seconds while migrating to `std::chrono`. * `CInstantSendManager::AskNodesForLockedTx()` was moved as `PeerManagerImpl::AskPeersForTransaction()` in [dash#6425](#6425) and with that, the sole external usage of `PeerManagerImpl::IsInvInFilter()` was moved internally, we can therefore safely remove it from the `PeerManager` interface. ## Breaking Changes None expected. ## Checklist - [x] I have performed a self-review of my own code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have added or updated relevant unit/integration/functional/e2e tests **(note: N/A)** - [x] I have made corresponding changes to the documentation **(note: N/A)** - [x] I have assigned this pull request to a milestone _(for repository code-owners and collaborators only)_ ACKs for top commit: UdjinM6: utACK 34a90e6 Tree-SHA512: 28b532cb5b8b5e6d7c1331c7c6c0ecd4d45b186922c279db6d2d3e8974d422ec8b67d75aeadce77986d409a8ed071e85359ee08609e0c2dde657e4520c546817
PeerManagerImpl already knows if we're a masternode or not, we don't need to accept it as an argument.
WalkthroughRefactors InstantSend to decouple verification from network I/O. CInstantSendManager::ProcessPendingInstantSendLocks() now returns instantsend::PendingState containing a pending-work flag and a per-peer list of MessageProcessingResult actions. ProcessInstantSendLock returns MessageProcessingResult instead of performing peer I/O. WorkThreadMain consumes PendingState and posts per-peer actions via PeerManager. PeerManager public API removes AskPeersForTransaction, RelayInvFiltered overloads, EraseObjectRequest, and RequestObject variants; helpers are moved private in PeerManagerImpl and RequestObject drops the is_masternode parameter. MessageProcessingResult gains m_inv_filter and m_request_tx to drive filtered relays and tx requests. Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes ✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/instantsend/instantsend.cpp (1)
24-25
: Missing include for std::same_as in requires-clauseThis TU uses std::same_as in a requires-clause (Line 39) but does not include . Some toolchains won’t transitively pull it in, causing a build error.
Apply:
#include <cxxtimer.hpp> +#include <concepts>
🧹 Nitpick comments (10)
src/protocol.h (2)
19-19
: Include set is incomplete for using std::optional directly in this headerGood call adding . This header also uses std::optional in MessageProcessingResult but doesn't include itself, relying on transitive includes. Make the header self-contained.
Apply this diff near the other standard headers:
#include <limits> #include <string> +#include <optional> #include <variant>
603-608
: Shape of m_inv_filter is terse; consider a named struct for readability and future extensionThe optional pair<inv, variant<txref, txid>> works, but it's opaque at call sites and in PostProcessMessage. A small named type improves clarity and avoids nested templates in signatures.
For example:
+struct FilteredInvAction { + CInv inv; + std::variant<CTransactionRef, uint256> related; // tx or just txid +}; ... - std::optional<std::pair<CInv, std::variant<CTransactionRef, uint256>>> m_inv_filter; + std::optional<FilteredInvAction> m_inv_filter;Follow-ups in users: ret.m_inv_filter = FilteredInvAction{inv, tx}; or {inv, islock->txid}.
src/instantsend/instantsend.h (1)
38-44
: Give names to per-peer actions and make PendingState a bit more self-documentingThe vector<pair<NodeId, MessageProcessingResult>> type repeats and is hard to scan. A small alias (or struct) clarifies intent and reduces template noise.
Apply:
namespace instantsend { -struct PendingState { +using PeerAction = std::pair<NodeId, MessageProcessingResult>; + +struct PendingState { bool m_pending_work{false}; - std::vector<std::pair<NodeId, MessageProcessingResult>> m_peer_activity{}; + std::vector<PeerAction> m_peer_activity{}; }; } // namespace instantsendOptionally mark PendingState-returning helpers [[nodiscard]] to discourage accidental result drops.
src/instantsend/instantsend.cpp (4)
172-208
: Micro-optimizations and a typo in batching pending locks
- The for-loop iterates with const auto&… then std::move on a const ref, which defeats moving. Use non-const ref if you want to move from the map’s value. Shared_ptr copies are cheap, but this is easy to make correct.
- Reserve buckets in pend to avoid rehashing.
- Typo: “temporaily” -> “temporarily”.
Apply:
instantsend::PendingState CInstantSendManager::ProcessPendingInstantSendLocks() { decltype(pendingInstantSendLocks) pend; instantsend::PendingState ret; @@ - // The keys of the removed values are temporaily stored here to avoid invalidating an iterator + // The keys of the removed values are temporarily stored here to avoid invalidating an iterator std::vector<uint256> removed; removed.reserve(maxCount); + pend.reserve(maxCount); - for (const auto& [islockHash, nodeid_islptr_pair] : pendingInstantSendLocks) { + for (auto& [islockHash, nodeid_islptr_pair] : pendingInstantSendLocks) { // Check if we've reached max count if (pend.size() >= maxCount) { ret.m_pending_work = true; break; } pend.emplace(islockHash, std::move(nodeid_islptr_pair)); removed.emplace_back(islockHash); }
238-347
: Pre-size peer_activity to reduce reallocations during batch processingYou append once per pending lock and once per bad source. Reserving amortizes vector growth, especially under high load.
Add just before the ban handling:
std::unordered_set<uint256, StaticSaltedHasher> badISLocks; +// Reserve space for per-peer work results to avoid reallocations +peer_activity.reserve(peer_activity.size() + pend.size() + batchVerifier.badSources.size()); + if (ban && !batchVerifier.badSources.empty()) {
349-429
: Returning MessageProcessingResult with filtered INV and optional tx request — LGTMThe split between “announce with tx-aware filtering” vs “announce with txid and request tx” is clear and keeps I/O outside the worker.
Minor nits:
- Consider making inv const: const CInv inv(MSG_ISDLOCK, hash);
- Comments: “we don’t have the TX yet, so we only filter based on txid” — perfect context, keep this style in future touch-ups.
923-931
: Avoid copying m_peer_activity with structured binding; move from the returned state insteadStructured binding from the prvalue PendingState will copy the vector into peer_activity before you move individual elements. Bind the whole struct and move from its member.
Apply:
- auto [more_work, peer_activity] = ProcessPendingInstantSendLocks(); - for (auto& [node_id, mpr] : peer_activity) { + auto st = ProcessPendingInstantSendLocks(); + for (auto& [node_id, mpr] : st.m_peer_activity) { peerman.PostProcessMessage(std::move(mpr), node_id); } - if (!m_signer) return more_work; + if (!m_signer) return st.m_pending_work;src/net_processing.cpp (3)
1579-1611
: RequestObject: scheduling logic is correct; fix unsafe logging format and consider small clarity nits
- Using m_mn_activeman != nullptr as the “this node is MN” signal passed into CalculateObjectGetDataTime preserves the previous behavior without threading a flag through APIs. Looks good.
- The LogPrint format uses %d for microseconds (int) but count() returns a 64-bit integer. That’s undefined behavior on LLP64/LP64. Cast or use a 64-bit specifier.
Apply this logging fix:
- LogPrint(BCLog::NET, "%s -- inv=(%s), current_time=%d, process_time=%d, delta=%d\n", __func__, inv.ToString(), current_time.count(), process_time.count(), (process_time - current_time).count()); + LogPrint(BCLog::NET, "%s -- inv=(%s), current_time=%lld, process_time=%lld, delta=%lld\n", + __func__, inv.ToString(), + static_cast<long long>(current_time.count()), + static_cast<long long>(process_time.count()), + static_cast<long long>((process_time - current_time).count()));Optional clarity: assign a local const bool is_masternode = (m_mn_activeman != nullptr) before calling CalculateObjectGetDataTime to make intent explicit.
2296-2323
: AskPeersForTransaction: add fairness (randomization) when selecting up to 4 peersCurrent code picks the first 4 peers from m_peer_map with a positive filter hit, which can bias requests toward stable insertion order. Use reservoir sampling (or shuffle candidates) to fairly choose up to 4 peers.
Proposed change using reservoir sampling and preserving existing locks:
void PeerManagerImpl::AskPeersForTransaction(const uint256& txid) { - std::vector<PeerRef> peersToAsk; - peersToAsk.reserve(4); + std::vector<PeerRef> peersToAsk; + peersToAsk.reserve(4); { LOCK(m_peer_mutex); - // TODO consider prioritizing MNs again, once that flag is moved into Peer - for (const auto& [_, peer] : m_peer_map) { - if (peersToAsk.size() >= 4) { - break; - } - if (IsInvInFilter(*peer, txid)) { - peersToAsk.emplace_back(peer); - } - } + // TODO consider prioritizing MNs again, once that flag is moved into Peer + size_t seen = 0; + for (const auto& [_, peer] : m_peer_map) { + if (!IsInvInFilter(*peer, txid)) continue; + ++seen; + if (peersToAsk.size() < 4) { + peersToAsk.emplace_back(peer); + } else { + // Replace existing with decreasing probability + const size_t j = static_cast<size_t>(GetRand(seen)); + if (j < 4) peersToAsk[j] = peer; + } + } } { CInv inv(MSG_TX, txid); LOCK(cs_main); for (PeerRef& peer : peersToAsk) { LogPrintf("PeerManagerImpl::%s -- txid=%s: asking other peer %d for correct TX\n", __func__, txid.ToString(), peer->m_id); - RequestObject(peer->m_id, inv, GetTime<std::chrono::microseconds>(), /*fForce=*/true); + RequestObject(peer->m_id, inv, GetTime<std::chrono::microseconds>(), /*fForce=*/true); } } }
646-663
: All RequestObject and RelayInvFiltered call sites updated to new signaturesVerified via a repository-wide search that there are no remaining uses of the old RequestObject(is_masternode) overload or RelayInvFiltered/AskPeersForTransaction variants—every invocation now uses the 4-argument RequestObject (with
fForce
defaulted where omitted), and both RelayInvFiltered overloads are called with the appropriateminProtoVersion
.
- No calls to an old RequestObject signature were found outside
net_processing.cpp
; allRequestObject(
usages accept(NodeId, const CInv&, microseconds, bool)
only.- All
RelayInvFiltered(
andAskPeersForTransaction(
invocations pass the correct parameters and versions.Next steps:
- Add a brief comment adjacent to these private declarations in
src/net_processing.cpp
(lines 646–663) noting that PostProcessMessage leveragesISDLOCK_PROTO_VERSION
as the relay gate whenm_inv_filter
is set, and that this is intentional for InstantSend behavior.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
-
src/instantsend/instantsend.cpp
(12 hunks) -
src/instantsend/instantsend.h
(2 hunks) -
src/net_processing.cpp
(8 hunks) -
src/net_processing.h
(0 hunks) -
src/protocol.h
(2 hunks)
💤 Files with no reviewable changes (1)
- src/net_processing.h
🧰 Additional context used
📓 Path-based instructions (1)
src/**/*.{cpp,h,cc,cxx,hpp}
📄 CodeRabbit inference engine (CLAUDE.md)
src/**/*.{cpp,h,cc,cxx,hpp}
: Dash Core C++ codebase must be written in C++20 and require at least Clang 16 or GCC 11.1
Dash uses unordered_lru_cache for efficient caching with LRU eviction
Files:
src/protocol.h
src/instantsend/instantsend.h
src/net_processing.cpp
src/instantsend/instantsend.cpp
🧠 Learnings (1)
📚 Learning: 2025-01-02T21:50:00.967Z
Learnt from: kwvg
PR: dashpay/dash#6504
File: src/llmq/context.cpp:42-43
Timestamp: 2025-01-02T21:50:00.967Z
Learning: LLMQContext manages concurrency for the `CInstantSendManager`. Previously, this was handled globally; now it's handled as a class member in `LLMQContext`, but the concurrency control remains consistent.
Applied to files:
src/instantsend/instantsend.h
🧬 Code graph analysis (2)
src/instantsend/instantsend.h (1)
src/instantsend/instantsend.cpp (6)
ProcessPendingInstantSendLocks
(172-235)ProcessPendingInstantSendLocks
(172-172)ProcessPendingInstantSendLocks
(237-347)ProcessPendingInstantSendLocks
(237-240)ProcessInstantSendLock
(349-429)ProcessInstantSendLock
(349-350)
src/instantsend/instantsend.cpp (1)
src/net_processing.cpp (7)
ret
(664-664)inv
(630-630)inv
(631-631)inv
(650-650)inv
(656-656)inv
(938-938)inv
(2314-2314)
🪛 GitHub Actions: Clang Diff Format Check
src/instantsend/instantsend.cpp
[error] 215-221: Clang-format differences detected in src/instantsend/instantsend.cpp (call to ProcessPendingInstantSendLocks reformatted). Run clang-format to fix formatting. Command failed: git diff -U0 origin/develop --
🔇 Additional comments (5)
src/instantsend/instantsend.h (1)
105-116
: Verification complete: net_processing handles InstantSendMessageProcessing results correctlyI’ve confirmed that the new
MessageProcessingResult
fields are fully consumed innet_processing.cpp
:
PostProcessMessage applies both filters:
- Checks and relays via
m_inv_filter
(src/net_processing.cpp:3506–3507)- Schedules tx requests via
m_request_tx
(src/net_processing.cpp:3514–3515)RelayInvFiltered enforces the
ISDLOCK_PROTO_VERSION
gating as intended:
- PeerManagerImpl’s
RelayInvFiltered
methods (src/net_processing.cpp:2393–2426) and the call sites in PostProcessMessage (lines 3509–3511) all guard onpnode->nVersion < minProtoVersion
before relaying.No further issues found.
src/instantsend/instantsend.cpp (1)
215-221
: Install clang-format and rerun formatting checkThe clang-format-diff script ran without error but didn’t report any differences because the
clang-format
binary wasn’t found in the environment. Please ensure you have clang-format installed, then rerun:git diff -U0 origin/develop -- src/instantsend/instantsend.cpp > changes.diff contrib/devtools/clang-format-diff.py -p1 < changes.diffIf any differences are reported, apply them via
git clang-format
or by patching accordingly.src/net_processing.cpp (3)
4157-4157
: INV handler: call-site updated to new RequestObject signatureCalling RequestObject(pfrom.GetId(), inv, current_time) under cs_main is correct and keeps the request scheduling centralized. LGTM.
4544-4549
: Missing-inputs flow: parent re-requests look correct
- Good use of AddKnownInv before RequestObject to avoid redundant announcements.
- Scheduling both MSG_TX and MSG_DSTX parent requests covers both paths without adding special-case logic.
No changes requested.
3506-3516
: Ensure<variant>
Is Included and Document ISDLOCK Version AssumptionPlease add the
<variant>
header to src/net_processing.cpp and annotate the hard-coded protocol version. After this change, no further adjustments are needed.• In
src/net_processing.cpp
, among the other headers:#include <optional> +#include <variant> // needed for std::holds_alternative and std::get in PostProcessMessage (m_inv_filter)
• At the call site, annotate why we’re using
ISDLOCK_PROTO_VERSION
:if (std::holds_alternative<CTransactionRef>(filter)) { // Note: using ISDLOCK_PROTO_VERSION here for IS-lock relay per PR scope; do not alter without compatibility checks. RelayInvFiltered(inv, *std::get<CTransactionRef>(filter), ISDLOCK_PROTO_VERSION); } else { // Note: using ISDLOCK_PROTO_VERSION here for IS-lock relay per PR scope; do not alter without compatibility checks. RelayInvFiltered(inv, std::get<uint256>(filter), ISDLOCK_PROTO_VERSION); }With these additions, compilation will succeed, and the version-hardcoding intent is clearly documented.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM overall
So far we cannot stop using `PeerManager` entirely the triggers are internal (i.e. not coming from P2P interactions) but we can extend and embrace MessageProcessingResult, to at least isolate its usage as best we can. Co-Authored-By: Konstantin Akimov <knstqq@gmail.com>
With their usage being brokered by `MessageProcessingResult`, we can remove them from the interface and keep them as implementation details.
RequestObject is not used outside PeerManagerImpl and EraseObjectRequest is now brokered by `MessageProcessingResult`, so we can remove both from the interface and keep them as implementation details.
There was a problem hiding this 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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/instantsend/instantsend.cpp (1)
172-235
: Fix: avoid dropping pending ISLOCKs when quorum selection failsIf
ProcessPendingInstantSendLocks(llmq_params, ...)
returns early due to!quorum
, the outer function has already erased entries frompendingInstantSendLocks
and never re-queues them. This silently loses work. Re-queue the batch when no peer activity was produced, and markm_pending_work = true
so the worker loops immediately.@@ - // First check against the current active set and don't ban - auto badISLocks = ProcessPendingInstantSendLocks(llmq_params, /*signOffset=*/0, /*ban=*/false, pend, ret.m_peer_activity); + // First check against the current active set and don't ban + const auto pre_peer_activity = ret.m_peer_activity.size(); + auto badISLocks = ProcessPendingInstantSendLocks(llmq_params, /*signOffset=*/0, /*ban=*/false, pend, ret.m_peer_activity); + // If quorum selection failed in the helper and nothing was processed, re-queue and retry later + if (badISLocks.empty() && ret.m_peer_activity.size() == pre_peer_activity && !pend.empty()) { + LOCK(cs_pendingLocks); + for (auto& kv : pend) { + pendingInstantSendLocks.emplace(kv.first, std::move(kv.second)); + } + ret.m_pending_work = true; + return ret; + } @@ - // Now check against the previous active set and perform banning if this fails - ProcessPendingInstantSendLocks(llmq_params, dkgInterval, /*ban=*/true, pend, ret.m_peer_activity); + // Now check against the previous active set and perform banning if this fails + ProcessPendingInstantSendLocks(llmq_params, dkgInterval, /*ban=*/true, pend, ret.m_peer_activity);
♻️ Duplicate comments (1)
src/net_processing.cpp (1)
3506-3518
: Variant handling for m_inv_filter: nit addressed.The explicit holds_alternative branches with a defensive assert cover all variant cases cleanly.
🧹 Nitpick comments (7)
src/instantsend/instantsend.cpp (4)
186-188
: Spelling nit: “temporaily” → “temporarily”Minor doc polish.
- // The keys of the removed values are temporaily stored here to avoid invalidating an iterator + // The keys of the removed values are temporarily stored here to avoid invalidating an iterator
218-218
: Fix clang-format diff failure on wrapped callCI reports clang-format differences for the call sites. Reflow the arguments to match the project style.
-auto badISLocks = ProcessPendingInstantSendLocks(llmq_params, /*signOffset=*/0, /*ban=*/false, pend, ret.m_peer_activity); +auto badISLocks = ProcessPendingInstantSendLocks( + llmq_params, /*signOffset=*/0, /*ban=*/false, pend, ret.m_peer_activity); @@ -ProcessPendingInstantSendLocks(llmq_params, dkgInterval, /*ban=*/true, pend, ret.m_peer_activity); +ProcessPendingInstantSendLocks( + llmq_params, dkgInterval, /*ban=*/true, pend, ret.m_peer_activity);Also applies to: 231-231
311-318
: Remove unnecessary cs_main lock in ban path
peer_activity.emplace_back(nodeId, MisbehavingError{20});
doesn’t touch chainstate; taking::cs_main
here adds contention without need.- if (ban && !batchVerifier.badSources.empty()) { - LOCK(::cs_main); - for (const auto& nodeId : batchVerifier.badSources) { + if (ban && !batchVerifier.badSources.empty()) { + for (const auto& nodeId : batchVerifier.badSources) { // Let's not be too harsh, as the peer might simply be unlucky and might have sent us an old lock which // does not validate anymore due to changed quorums peer_activity.emplace_back(nodeId, MisbehavingError{20}); } }
923-932
: Avoid copying peer_activity with structured bindings
auto [more_work, peer_activity] = ...;
copies the vector. Move out of the returned struct to avoid an extra allocation/copy.- auto [more_work, peer_activity] = ProcessPendingInstantSendLocks(); - for (auto& [node_id, mpr] : peer_activity) { - peerman.PostProcessMessage(std::move(mpr), node_id); - } + auto pending = ProcessPendingInstantSendLocks(); + const bool more_work = pending.m_pending_work; + for (auto& [node_id, mpr] : pending.m_peer_activity) { + peerman.PostProcessMessage(std::move(mpr), node_id); + }src/net_processing.cpp (3)
649-657
: RelayInvFiltered helpers moved private: OK; minProtoVersion assumption is acceptable here.Given current usage (InstantSend), ISDLOCK_PROTO_VERSION as a floor is fine. If future callers want broader relays, consider threading minProtoVersion through MessageProcessingResult.
1579-1611
: RequestObject rewrite: semantics and timing look correct.
- Inferring masternode role via m_mn_activeman in CalculateObjectGetDataTime matches prior intent (skip inbound delay for MNs).
- Capacity/dup guards on m_object_announced/process_time are preserved.
Minor: the LogPrint uses %d for microsecond counts; prefer 64-bit formatting to avoid truncation.
- LogPrint(BCLog::NET, "%s -- inv=(%s), current_time=%d, process_time=%d, delta=%d\n", __func__, inv.ToString(), current_time.count(), process_time.count(), (process_time - current_time).count()); + LogPrint(BCLog::NET, "%s -- inv=(%s), current_time=%lld, process_time=%lld, delta=%lld\n", + __func__, inv.ToString(), + (long long)current_time.count(), + (long long)process_time.count(), + (long long)(process_time - current_time).count());
2296-2321
: Avoid deterministic peer bias when asking for TX.We always pick the first 4 peers in m_peer_map. Randomize the choice to spread load and reduce adversarial influence.
- std::vector<PeerRef> peersToAsk; - peersToAsk.reserve(4); - { - LOCK(m_peer_mutex); - // TODO consider prioritizing MNs again, once that flag is moved into Peer - for (const auto& [_, peer] : m_peer_map) { - if (peersToAsk.size() >= 4) { - break; - } - if (IsInvInFilter(*peer, txid)) { - peersToAsk.emplace_back(peer); - } - } - } + std::vector<PeerRef> candidates; + { + LOCK(m_peer_mutex); + for (const auto& [_, peer] : m_peer_map) { + if (IsInvInFilter(*peer, txid)) candidates.emplace_back(peer); + } + } + // Shuffle and take up to 4 + Shuffle(candidates.begin(), candidates.end(), FastRandomContext()); + std::vector<PeerRef> peersToAsk; + peersToAsk.reserve(std::min<size_t>(4, candidates.size())); + for (size_t i = 0; i < std::min<size_t>(4, candidates.size()); ++i) { + peersToAsk.emplace_back(candidates[i]); + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
src/instantsend/instantsend.cpp
(12 hunks)src/instantsend/instantsend.h
(2 hunks)src/net_processing.cpp
(8 hunks)src/net_processing.h
(0 hunks)src/protocol.h
(2 hunks)
💤 Files with no reviewable changes (1)
- src/net_processing.h
🚧 Files skipped from review as they are similar to previous changes (2)
- src/instantsend/instantsend.h
- src/protocol.h
🧰 Additional context used
📓 Path-based instructions (1)
src/**/*.{cpp,h,cc,cxx,hpp}
📄 CodeRabbit inference engine (CLAUDE.md)
src/**/*.{cpp,h,cc,cxx,hpp}
: Dash Core C++ codebase must be written in C++20 and require at least Clang 16 or GCC 11.1
Dash uses unordered_lru_cache for efficient caching with LRU eviction
Files:
src/net_processing.cpp
src/instantsend/instantsend.cpp
🧬 Code graph analysis (1)
src/instantsend/instantsend.cpp (1)
src/net_processing.cpp (7)
ret
(664-664)inv
(630-630)inv
(631-631)inv
(650-650)inv
(656-656)inv
(938-938)inv
(2314-2314)
🪛 GitHub Actions: Clang Diff Format Check
src/instantsend/instantsend.cpp
[error] 215-216: Clang-format differences detected by clang-format-diff.py. The ProcessPendingInstantSendLocks call in src/instantsend/instantsend.cpp has its arguments wrapped onto a new line.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
- GitHub Check: x86_64-w64-mingw32 / Build depends
- GitHub Check: Lint / Run linters
- GitHub Check: arm-linux-gnueabihf / 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-apple-darwin / Build depends
- GitHub Check: x86_64-pc-linux-gnu_multiprocess / Build depends
🔇 Additional comments (7)
src/instantsend/instantsend.cpp (3)
238-241
: Signature change looks good; batch peer-activity via out-param is cleanThe helper’s new signature that fills
peer_activity
in-place aligns with the post-processing flow.
331-331
: LGTM: defers peer I/O by returning MessageProcessingResultGood decoupling—pushes ISLOCK processing results to the worker via
peer_activity
.
349-365
: No changes needed:m_inv_filter
correctly uses CTransactionRef
Them_inv_filter
member is defined asstd::variant<CTransactionRef, uint256>
in protocol.h, andPostProcessMessage
handles theCTransactionRef
alternative by dereferencing it (*std::get<CTransactionRef>(filter)
) before callingRelayInvFiltered
, so passing theCTransactionRef
directly is correct.src/net_processing.cpp (4)
646-648
: Private AskPeersForTransaction: good locking and scope.Collects PeerRef under m_peer_mutex, requests under cs_main. Looks correct and re-entrant-safe.
658-662
: EraseObjectRequest/RequestObject privatization: OK.Signatures and annotations look consistent with call sites and locking.
4159-4160
: INV path updated to new RequestObject signature: looks good.Inbound-delay logic now derives inside RequestObject; no functional regressions expected.
4547-4551
: Missing-inputs re-request path updated: OK.Dual request (MSG_TX/DSTX) maintained; new RequestObject call fits the refactor.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
utACK a02e843
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
utACK a02e843
Additional Information
Depends on refactor: follow-up dash#6761, implement review suggestions, ChainLock and InstantSend refactoring #6815
Depends on refactor: migrate
ProcessMessage
definitions toMessageProcessingResult
, dropPeerMsgRet
#6820While this pull request doesn't entirely decouple
PeerManager
fromCInstantSendManager
as the worker thread isn't reactive (i.e. triggered byProcessMessage()
), we can reduce its usage by folding all expected network activity into aMessageProcessingResult
batch that can be consumed byPostProcessMessage
.To achieve this,
MessageProcessingResult
has been extended to allowm_request_tx
)m_inv_filter
)This has the additional effect of removing external uses of
RelayInvFiltered()
andAskPeersForTransaction()
, which can now be safely removed from thePeerManager
interface as it is now brokered throughMessageProcessingResult
.Note that while the old
RelayInvFiltered()
allowed specifying any minimum protocol version,PostProcessMessage()
will assume thatminProtoVersion
isISDLOCK_PROTO_VERSION
. This is acceptable asRelayInvFiltered()
isn't used anywhere else and deterministic InstantSend locks were introduced in v0.18 (see dash#4381).If there is any foreseeable use needing to relay messages to even older versions of Dash Core,
m_inv_filter
can be modified to accommodate that.Breaking Changes
None expected.
Checklist