Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
fad1bbb to
fa2a20c
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
fa2a20c to
fa8b05f
Compare
fa8b05f to
fa14855
Compare
|
Concept ACK |
sedited
left a comment
There was a problem hiding this comment.
ACK fa14855ff1bd527cbbd56080eb2cfdcd74d780da
seduless
left a comment
There was a problem hiding this comment.
Tested ACK fa14855ff1bd527cbbd56080eb2cfdcd74d780da
In commit fa1a22927adac877c46645b586ecda8ae1592002, peerman_tests still has a few straightforward migrations left. Non-blocking, happy to send a follow-up if you'd rather not fold it in here.
|
Yeah, the goal here is mostly to fix net_processing fully. Not sure what the ideal size of a pull request is, but 7 commits and ~150 lines explicitly touched (and a few more implicitly) seems ok-ish. Edit: I think the next pull should just remove it fully, in all remaining places? |
Perhaps it's useful for the next follow-up to avoid clashing with the scoped clock proposed for the kernel in #35557? |
ryanofsky
left a comment
There was a problem hiding this comment.
Code review ACK fa14855ff1bd527cbbd56080eb2cfdcd74d780da. But approach +0.5. NodeClock::time_point is an improvement over using integer or duration types to represent time points. But I don't think it's a good thing to be hardcoding NodeClock::epoch everywhere, especially for things like block times which don't come from the node/system clock. If default-initializing time variables, it seems better to do it the standard way by calling default constructors, instead of inviting inconsistency and preferring to use bitcoin-specific NodeClock::epoch constant. Also, if choosing sentinel time values, it seems better to use min or max values than to treat the epoch time as being special unnecessarily.
I am also not sure it's good hardcode NodeClock::time_point types everywhere. It seems like a lost opportunity to choose to hardcode a platform-dependent clock type that doesn't have a standard precision or representation, when we could use application-specific type aliases like using MempoolTime = NodeClock::time_point;, using NetworkTime = NodeClock::time_point;, using BlockTime = NodeSeconds; to not be tied to the system clock and be able to intentionally chose which precision and representations to use in different areas of the code. For example, it would be nice to define standard ways of serializing each of these types without requiring them all to be serialized the same way.
I left more detailed code review comments below, but I guess my main feedback is I would be happier to see most NodeClock::epoch uses dropped. And I also think it could be a good idea to replace most NodeClock::time_point references here with a networking specific NetworkTime alias.
Not sure. Those types are direct aliases, so they are tied to the (mockable) system clock (aka node clock). Also, given that they are type aliases, so anyone can use them interchangeably, which seems confusing. While I like my approach, I don't think it matters much and I am happy to switch to whatever reviewers prefer. |
ryanofsky
left a comment
There was a problem hiding this comment.
Thanks for the replies. I still think expanded uses of NodeClock::epoch in this PR are bad, and haven't seen a positive case being made for them. So would like to see that addressed by dropping them, improving them, or explaining benefits with some rationale.
re: #35315 (comment)
Those types are direct aliases, so they are tied to the (mockable) system clock (aka node clock). Also, given that they are type aliases, so anyone can use them interchangeably, which seems confusing.
Not sure what is confusing. Type aliases are meant to be interchangeable. They exist to express developer intent and make code more readable and maintainable. Using them would make time variables declarations more self-documenting, allow changing time types without causing churn, and allow adding more type constraints or features like serialization support in the future. I don't have a strong opinion on this. I just think it is a good idea without any downsides that I can see.
I mostly think this invites bike-shedding, because it is less clear where to draw the line without knowing any of the imaginary future plans. E.g. should network time be the same alias like p2p time, and mempool time, and validation time, or should even different fields in p2p have different named time aliases, ...? [Meta note: Generally it is best to provide each review topic in a new review thread, and not in the global thread. Otherwise, it is harder to follow the global thread, because it mixes different sub-threads] |
I agree with @maflcko, and see similar things with other aliases that were introduced in the codebase. I think they are a poor tool for being the impetus for more in depth code changes. Sometimes they can help documenting intent, but for the reasons named here I don't think they really make it easier. |
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
|
Approach ACK for improved type safety in time handling, this makes the code easier to read and harder to make mistakes. I think the meta-nit: I think the current commit structure is reasonable, but I would have preferred having separate commits for refactoring changes (i.e. changing the type) and for behaviour changes (i.e. changing the default, using min/max etc). Not a blocker, it's doable as-is, but it would speed the (re-)review cycle up for me. meta-nit: faba25132928b8bdce526957d3b311fca3e75faf should not have |
fa714df to
fa146ff
Compare
|
Thanks for the approach review! I've:
|
ryanofsky
left a comment
There was a problem hiding this comment.
Code review ACK fa146ff. Nice improvement using the time point type to represent times, instead of duration types or integers.
Unfortunately, it looks like uses of the epoch constant are still increasing from 10 to 26 in this pull, but this is better than the 44 uses in previous versions.
I left some new suggestions, but as always feel free to ignore them. Thanks for all the updates!
| /// Code may reference this constant and treat it as special, if an unset | ||
| /// variable should be represented as zero. For example, when the time |
There was a problem hiding this comment.
In commit "refactor: Allow NodeClock::epoch to be used in NodeSeconds context" (fa3ed0c)
This seems like bad advice and the previous comment in fa815059fc1a4eabbd81d586b8e515315eba5ec3 was better. The problem is:
if an unset variable should be represented as zero
An unset variable should not be represented as zero. That is a footgun and a cause of bugs. If you think there are cases where this is appropriate I'd like to know what they are, and this comment should be specific about what they are.
Log messages and RPCs should not be using this constant if they want to display or return zero when literal zeroes would be clearer. Also they are probably better off writing "unset" or null than using zeroes at all. C++ code is better off using std::optional, or min/max times when the goal is to represent the last time something happened, or the next time it should happen.
I still believe that epoch is a non-standard, error-prone constant should be removed entirely. Zeroes are not a good way represent unset times. In cases where they can't be avoided, literal zeros can be used and would preferable for transparency, and to make intent clear because the internal clock epoch time should not be relevant to application logic. Alternately, if there is some reason we don't want to write zeroes literally, we could introduce a constant like NODE_UNSET_TIME which would also express intent more clearly and also make bad code stand out.
Suggestion would be to drop this commit (preferred) or to improve the comment. I think earlier suggested comment could fit well here.
/// Default value assigned to a NodeSeconds time point variable if no explicit
/// value is set. Since C++20, this is guaranteed to be the unix epoch time,
/// 1970-01-01T00:00:00Z.
/// Bitcoin Core code should generally avoid referencing this constant or
/// treating this time point as special. If a time variable is unset it is
/// usually preferable to initialize it with time_point::max or time_point::min
/// values for more natural comparisons, or to use std::optional.There was a problem hiding this comment.
I think all other reviewers prefer the constant, so I won't be dropping it. I can add the words Old code ... and New code ..., or some other wording, if I have to re-touch.
About the RPC/logs: Yes it is possible to change
TicksSinceEpoch<seconds>(field_with_zero_default)to
field_with_min_default == NodeClock::min() ? 0 : TicksSinceEpoch<seconds>(field_with_min_default)or to
TicksSinceEpoch<seconds>(opt_field.value_or(NodeClock::epoch)), but this would have to be separate commit and this pull is already too large to include that here.
Also, breaking behavior changes like switching 0 to null or "unset" in RPC are not allowed in this refactor-only PR.
I am happy to review a later pull, if someone creates one.
There was a problem hiding this comment.
to improve the comment
Thx, minimally improved docstring.
| CNodeState &state = *State(pnode->GetId()); | ||
| if (now - pnode->m_connected > MINIMUM_CONNECT_TIME && state.vBlocksInFlight.empty()) { | ||
| LogDebug(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement); | ||
| LogDebug(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)", |
There was a problem hiding this comment.
In commit "p2p: Use NodeClock::time_point for m_last_block_announcement" (fa6f2e9)
Not important, but this is also dropping \n, and I think it's good for commit messages to note when they make unrelated changes, so it's clear they are intentional. There is also another \n kept immediately below.
There was a problem hiding this comment.
The \n is not needed by the logger. May adjust the commit message if I have to re-touch.
| uint32_t GetFetchFlags(const Peer& peer) const; | ||
|
|
||
| std::map<uint64_t, std::chrono::microseconds> m_next_inv_to_inbounds_per_network_key GUARDED_BY(g_msgproc_mutex); | ||
| std::map<uint64_t, NodeClock::time_point> m_next_inv_to_inbounds_per_network_key GUARDED_BY(g_msgproc_mutex); |
There was a problem hiding this comment.
In commit "refactor: Use NodeClock::time_point instead of std::chrono::microseconds in net_processing" (cccc523)
Could mention this field in commit message
There was a problem hiding this comment.
May adjust the commit message if I have to re-touch.
| @@ -790,7 +790,7 @@ class PeerManagerImpl final : public PeerManager | |||
| /** The height of the best chain */ | |||
| std::atomic<int> m_best_height{-1}; | |||
| /** The time of the best chain tip block */ | |||
| std::atomic<std::chrono::seconds> m_best_block_time{0s}; | |||
| std::atomic<NodeSeconds> m_best_block_time{}; | |||
There was a problem hiding this comment.
re: #35315 (comment)
Why are you surprised that I literally addressed your review feedback?
Yes I was surprised you took the suggestion here and nowhere else.
It is not allowed to call
ApproximateBestBlockDepthwhen the value is not set. Also, there is no code path where it is not set. I don't think it makes sense to bubble up errors that can never happen. In any case, I am not changing any behavior in this commit, so changingApproximateBestBlockDepthseems out of scope.
Thanks, I didn't realize there was no code path where m_best_block_time could be read before it is set. When I made my comment I was assuming that is was intended for ApproximateBestBlockDepth to return a really large value in this case so NETWORK_LIMITED would not be used.
Suggestion: The fact that m_best_block_time does always get set to a different value is not obvious, and I think there should at least be a comment here like "// default value is never used" to be clear that it's a bug if this value does get used.
I also think it could be safer to make this field std::optional and assert that it is set before it's used, but absent that, just having a comment would be helpful for making this not look like it is trying to return garbage.
stickies-v
left a comment
There was a problem hiding this comment.
Reviewed fa146ff
Code LGTM but want to give it another review round to double check potential behaviour change. Left a few comments, but no blockers.
| int64_t PeerManagerImpl::ApproximateBestBlockDepth() const | ||
| { | ||
| return (GetTime<std::chrono::seconds>() - m_best_block_time.load()).count() / m_chainparams.GetConsensus().nPowTargetSpacing; | ||
| return (Now<NodeSeconds>() - m_best_block_time.load()).count() / m_chainparams.GetConsensus().nPowTargetSpacing; |
There was a problem hiding this comment.
in fa3c6ba:
orthogonal, but while touching, would be good to use TicksSeconds here to guard against errors when m_best_block_time changes its duration type?
git diff on fa3c6ba
diff --git a/src/net_processing.cpp b/src/net_processing.cpp
index bc7f807ea5..9efe02fa69 100644
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -1352,7 +1352,7 @@ bool PeerManagerImpl::TipMayBeStale()
int64_t PeerManagerImpl::ApproximateBestBlockDepth() const
{
- return (Now<NodeSeconds>() - m_best_block_time.load()).count() / m_chainparams.GetConsensus().nPowTargetSpacing;
+ return TicksSeconds(Now<NodeSeconds>() - m_best_block_time.load()) / m_chainparams.GetConsensus().nPowTargetSpacing;
}
bool PeerManagerImpl::CanDirectFetch()
There was a problem hiding this comment.
Thx, done, but with a different patch
There was a problem hiding this comment.
nit: "maintain" would now require nanoseconds. No practical implications either way, but might be slightly less confusion to not have a different duration here?
| // Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to nanoseconds before scaling | |
| // to maintain precision | |
| std::chrono::nanoseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} * |
There was a problem hiding this comment.
I mean this is pretty pointless, the base timeout is 15 minutes and the per-header timeout-diff is 1ms, so even with a 1 week-old best header, we are bike-shedding about 15min1.008sec vs 15min1.007sec.
My preference would be to just remove this useless "precision" code, or use SecondsDouble for "precision".
edit: Miners can (and do?) "wiggle" the time here by more than one pow-target-spacing anyway, so implying a greater precision here seems confusing?
There was a problem hiding this comment.
My preference would be to just remove this useless "precision" code
I agree, it seems unnecessary and confusing.
| //! Since when we're stalling block download progress (in microseconds), or 0. | ||
| std::chrono::microseconds m_stalling_since{0us}; | ||
| /// When this peer started stalling block download progress, or unset. | ||
| std::optional<NodeClock::time_point> m_stalling_since{}; |
There was a problem hiding this comment.
Seems like logic for most of these variables would be simplified using min/max constants instead of optional.
I find relying on sentinels (if (State(staller)->m_stalling_since == NodeClock::time_point::max())) to be an antipattern, and would have found it more clear if this were a std::optional.
git diff on fa146ff
diff --git a/src/net_processing.cpp b/src/net_processing.cpp
index 78c6002ede..b4e6909ab2 100644
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -445,8 +445,8 @@ struct CNodeState {
const CBlockIndex* pindexBestHeaderSent{nullptr};
//! Whether we've started headers synchronization with this peer.
bool fSyncStarted{false};
- /// When this peer started stalling block download progress, or max() if not stalling.
- NodeClock::time_point m_stalling_since{NodeClock::time_point::max()};
+ /// When this peer started stalling block download progress.
+ std::optional<NodeClock::time_point> m_stalling_since{};
std::list<QueuedBlock> vBlocksInFlight;
//! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
NodeClock::time_point m_downloading_since{NodeClock::time_point::min()};
@@ -1239,7 +1239,7 @@ void PeerManagerImpl::RemoveBlockRequest(const uint256& hash, std::optional<Node
// Last validated block on the queue for this peer was received.
m_peers_downloading_from--;
}
- state.m_stalling_since = NodeClock::time_point::max();
+ state.m_stalling_since.reset();
range.first = mapBlocksInFlight.erase(range.first);
}
@@ -6205,7 +6205,7 @@ bool PeerManagerImpl::SendMessages(CNode& node)
// Detect whether we're stalling
auto stalling_timeout = m_block_stalling_timeout.load();
- if (state.m_stalling_since < now - stalling_timeout) {
+ if (state.m_stalling_since && *state.m_stalling_since < now - stalling_timeout) {
// Stalling only triggers when the block download window cannot move. During normal steady state,
// the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
// should only happen during initial block download.
@@ -6302,7 +6302,7 @@ bool PeerManagerImpl::SendMessages(CNode& node)
pindex->nHeight, node.GetId());
}
if (state.vBlocksInFlight.empty() && staller != -1) {
- if (State(staller)->m_stalling_since == NodeClock::time_point::max()) {
+ if (!State(staller)->m_stalling_since) {
State(staller)->m_stalling_since = now;
LogDebug(BCLog::NET, "Stall started peer=%d\n", staller);
}
Generally, I think ::min() and ::max() are natural choices when we can use them without relying on them as sentinel values. Once that no longer holds, I think std::optional is more clear.
git diff on fa146ff
diff --git a/src/net_processing.cpp b/src/net_processing.cpp
index 78c6002ede..0c5214c2b0 100644
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -309,8 +309,8 @@ struct Peer {
* NODE_BLOOM. See BIP35. */
bool m_send_mempool GUARDED_BY(m_tx_inventory_mutex){false};
/** The next time after which we will send an `inv` message containing
- * transaction announcements to this peer. */
- NodeClock::time_point m_next_inv_send_time GUARDED_BY(m_tx_inventory_mutex){NodeClock::time_point::min()};
+ * transaction announcements to this peer. Unset until version handshake completes. */
+ std::optional<NodeClock::time_point> m_next_inv_send_time GUARDED_BY(m_tx_inventory_mutex){};
/** The mempool sequence num at which we sent the last `inv` message to this peer.
* Can relay txs with lower sequence numbers than this (see CTxMempool::info_for_relay). */
uint64_t m_last_inv_sequence GUARDED_BY(m_tx_inventory_mutex){1};
@@ -366,8 +366,8 @@ struct Peer {
mutable Mutex m_addr_send_times_mutex;
/** Time point to send the next ADDR message to this peer. */
NodeClock::time_point m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){NodeClock::time_point::min()};
- /** Time point to possibly re-announce our local address to this peer. */
- NodeClock::time_point m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){NodeClock::time_point::min()};
+ /** Time point to possibly re-announce our local address to this peer. Unset before first announcement. */
+ std::optional<NodeClock::time_point> m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){};
/** Whether the peer has signaled support for receiving ADDRv2 (BIP155)
* messages, indicating a preference to receive ADDRv2 instead of ADDR ones. */
std::atomic_bool m_wants_addrv2{false};
@@ -445,11 +445,11 @@ struct CNodeState {
const CBlockIndex* pindexBestHeaderSent{nullptr};
//! Whether we've started headers synchronization with this peer.
bool fSyncStarted{false};
- /// When this peer started stalling block download progress, or max() if not stalling.
- NodeClock::time_point m_stalling_since{NodeClock::time_point::max()};
+ /// When this peer started stalling block download progress.
+ std::optional<NodeClock::time_point> m_stalling_since{};
std::list<QueuedBlock> vBlocksInFlight;
//! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
- NodeClock::time_point m_downloading_since{NodeClock::time_point::min()};
+ std::optional<NodeClock::time_point> m_downloading_since{};
//! Whether we consider this a preferred download peer.
bool fPreferredDownload{false};
/** Whether this peer wants invs or cmpctblocks (when possible) for block announcements. */
@@ -1231,7 +1231,7 @@ void PeerManagerImpl::RemoveBlockRequest(const uint256& hash, std::optional<Node
if (state.vBlocksInFlight.begin() == list_it) {
// First block on the queue was received, update the start download time for the next one
- state.m_downloading_since = std::max(state.m_downloading_since, NodeClock::now());
+ state.m_downloading_since = std::max(Assert(state.m_downloading_since).value(), NodeClock::now());
}
state.vBlocksInFlight.erase(list_it);
@@ -1239,7 +1239,7 @@ void PeerManagerImpl::RemoveBlockRequest(const uint256& hash, std::optional<Node
// Last validated block on the queue for this peer was received.
m_peers_downloading_from--;
}
- state.m_stalling_since = NodeClock::time_point::max();
+ state.m_stalling_since.reset();
range.first = mapBlocksInFlight.erase(range.first);
}
@@ -2286,7 +2286,7 @@ void PeerManagerImpl::InitiateTxBroadcastToAll(const Txid& txid, const Wtxid& wt
// otherwise at risk of leaking to a spy, if the spy is able to
// distinguish transactions received during the handshake from the rest
// in the announcement.
- if (tx_relay->m_next_inv_send_time == NodeClock::time_point::min()) continue;
+ if (!tx_relay->m_next_inv_send_time) continue;
const uint256& hash{peer.m_wtxid_relay ? wtxid.ToUint256() : txid.ToUint256()};
if (!tx_relay->m_tx_inventory_known_filter.contains(hash)) {
@@ -3892,7 +3892,7 @@ void PeerManagerImpl::ProcessMessage(Peer& peer, CNode& pfrom, const std::string
Assume(WITH_LOCK(
tx_relay->m_tx_inventory_mutex,
return tx_relay->m_tx_inventory_to_send.empty() &&
- tx_relay->m_next_inv_send_time == NodeClock::time_point::min()));
+ !tx_relay->m_next_inv_send_time));
}
if (pfrom.IsPrivateBroadcastConn()) {
@@ -5500,19 +5500,19 @@ void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, NodeClock::time_poi
LOCK(peer.m_addr_send_times_mutex);
// Periodically advertise our local address to the peer.
if (fListen && !m_chainman.IsInitialBlockDownload() &&
- peer.m_next_local_addr_send < current_time) {
+ (!peer.m_next_local_addr_send || *peer.m_next_local_addr_send < current_time)) {
// If we've sent before, clear the bloom filter for the peer, so that our
// self-announcement will actually go out.
// This might be unnecessary if the bloom filter has already rolled
// over since our last self-announcement, but there is only a small
// bandwidth cost that we can incur by doing this (which happens
// once a day on average).
- if (peer.m_next_local_addr_send != NodeClock::time_point::min()) {
+ if (peer.m_next_local_addr_send) {
peer.m_addr_known->reset();
}
if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) {
CAddress local_addr{*local_service, peer.m_our_services, Now<NodeSeconds>()};
- if (peer.m_next_local_addr_send == NodeClock::time_point::min()) {
+ if (!peer.m_next_local_addr_send) {
// Send the initial self-announcement in its own message. This makes sure
// rate-limiting with limited start-tokens doesn't ignore it if the first
// message ends up containing multiple addresses.
@@ -6091,7 +6091,7 @@ bool PeerManagerImpl::SendMessages(CNode& node)
LOCK(tx_relay->m_tx_inventory_mutex);
// Check whether periodic sends should happen
bool fSendTrickle = node.HasPermission(NetPermissionFlags::NoBan);
- if (tx_relay->m_next_inv_send_time < now) {
+ if (!tx_relay->m_next_inv_send_time || *tx_relay->m_next_inv_send_time < now) {
fSendTrickle = true;
if (node.IsInboundConn()) {
tx_relay->m_next_inv_send_time = NextInvToInbounds(now, INBOUND_INVENTORY_BROADCAST_INTERVAL, node.m_network_key);
@@ -6205,7 +6205,7 @@ bool PeerManagerImpl::SendMessages(CNode& node)
// Detect whether we're stalling
auto stalling_timeout = m_block_stalling_timeout.load();
- if (state.m_stalling_since < now - stalling_timeout) {
+ if (state.m_stalling_since && *state.m_stalling_since < now - stalling_timeout) {
// Stalling only triggers when the block download window cannot move. During normal steady state,
// the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
// should only happen during initial block download.
@@ -6227,7 +6227,7 @@ bool PeerManagerImpl::SendMessages(CNode& node)
if (state.vBlocksInFlight.size() > 0) {
QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
int nOtherPeersWithValidatedDownloads = m_peers_downloading_from - 1;
- if (now > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
+ if (now > Assert(state.m_downloading_since).value() + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
LogInfo("Timeout downloading block %s, %s", queuedBlock.pindex->GetBlockHash().ToString(), node.DisconnectMsg());
node.fDisconnect = true;
return true;
@@ -6302,7 +6302,7 @@ bool PeerManagerImpl::SendMessages(CNode& node)
pindex->nHeight, node.GetId());
}
if (state.vBlocksInFlight.empty() && staller != -1) {
- if (State(staller)->m_stalling_since == NodeClock::time_point::max()) {
+ if (!State(staller)->m_stalling_since) {
State(staller)->m_stalling_since = now;
LogDebug(BCLog::NET, "Stall started peer=%d\n", staller);
}
Not a blocker, I don't want these style preferences to get in the way of the real improvements.
Some contexts have only second precision by definition, and it should be allowed to use NodeClock::epoch as an alias for zero. Also, add a docstring.
Previously, it was using a duration type.
Previously, a raw i64 was used, which also required a cast to seconds. Externally, this is a refactor. Internally, this is a minimal behavior improvement: The value tracks the last *new* block announcement. It should be rare for more than one new block to be announced in the same second. Even if several new blocks were announced in the same second, the value is only used in EvictExtraOutboundPeers. Changing the time points to be more precise may change the sorting of the worst peers when they all announced a block in the same second. In this case it should be fine and preferable, to use the more accurate sorting from the exact block announce time for the worst peers, than to fall back to peer with the highest id. Nit note: The removed \n char in the log is not needed (refactor).
This may minimally increase the precision from µs to ns, but the behavior does not change in this refactor.
fa146ff to
fa1f6e7
Compare
…e stats and eviction Externally, this is a refactor, because stats reported by RPC do not change. Internally, this is a minimal behavior improvement: With the precision increase from seconds to nanoseconds, SelectNodeToEvict will be more precise picking the protected peers with CompareNodeBlockTime and CompareNodeTXTime.
The base timeout is 15 minutes, so trying to imply that a rounding error of 1ms is relevant seems confusing. Fix the confusion by using the integer division truncation to round down to the next ms.
…nds in net_processing for fields: * m_headers_sync_timeout * m_downloading_since * m_next_send_feefilter * m_next_addr_send * m_next_local_addr_send * m_next_inv_send_time * m_next_inv_to_inbounds_per_network_key * m_stalling_since This patch may minimally increase the precision from µs to ns, but the behavior does not change in this refactor.
This refactor does not change any behavior. It uses a single natural special in-band sentinel values instead of two different ones: epoch-zero and time_point::max(). Review help: fSyncStarted gates all uses of the field, so the zero-epoch default is irrelevant. time_point::max() used below is the meaningful sentinel here, representing a disabled timeout after sync has started, so use that value consistently.
This refactor does not change any behavior. It uses a more natural special in-band sentinel values instead of epoch-zero. Fields with time_point::min() as new sentinel value: * m_downloading_since * m_next_send_feefilter * m_next_addr_send * m_next_inv_send_time * m_next_local_addr_send Fields with time_point::max() as new sentinel value: * m_stalling_since
fa1f6e7 to
fab4bd7
Compare
| /** The next time after which we will send an `inv` message containing | ||
| * transaction announcements to this peer. */ | ||
| std::chrono::microseconds m_next_inv_send_time GUARDED_BY(m_tx_inventory_mutex){0}; | ||
| NodeClock::time_point m_next_inv_send_time GUARDED_BY(m_tx_inventory_mutex){NodeClock::time_point::min()}; |
There was a problem hiding this comment.
Would be useful to document all sentinels:
git diff on fab4bd7
diff --git a/src/net_processing.cpp b/src/net_processing.cpp
index d1564766fb..903f6dadda 100644
--- a/src/net_processing.cpp
+++ b/src/net_processing.cpp
@@ -309,7 +309,8 @@ struct Peer {
* NODE_BLOOM. See BIP35. */
bool m_send_mempool GUARDED_BY(m_tx_inventory_mutex){false};
/** The next time after which we will send an `inv` message containing
- * transaction announcements to this peer. */
+ * transaction announcements to this peer, or time_point::min() when
+ * the version handshake is not yet completed. */
NodeClock::time_point m_next_inv_send_time GUARDED_BY(m_tx_inventory_mutex){NodeClock::time_point::min()};
/** The mempool sequence num at which we sent the last `inv` message to this peer.
* Can relay txs with lower sequence numbers than this (see CTxMempool::info_for_relay). */
@@ -366,7 +367,8 @@ struct Peer {
mutable Mutex m_addr_send_times_mutex;
/** Time point to send the next ADDR message to this peer. */
NodeClock::time_point m_next_addr_send GUARDED_BY(m_addr_send_times_mutex){NodeClock::time_point::min()};
- /** Time point to possibly re-announce our local address to this peer. */
+ /** Time point to possibly re-announce our local address to this peer, or
+ * time_point::min() if no self-announcement was sent to this peer yet. */
NodeClock::time_point m_next_local_addr_send GUARDED_BY(m_addr_send_times_mutex){NodeClock::time_point::min()};
/** Whether the peer has signaled support for receiving ADDRv2 (BIP155)
* messages, indicating a preference to receive ADDRv2 instead of ADDR ones. */
@@ -403,7 +405,8 @@ struct Peer {
/** Whether we've sent our peer a sendheaders message. **/
std::atomic<bool> m_sent_sendheaders{false};
- /** When to potentially disconnect peer for stalling headers download */
+ /** When to potentially disconnect peer for stalling headers download, or
+ * time_point::max() if this peer is exempt from the timeout. */
NodeClock::time_point m_headers_sync_timeout GUARDED_BY(NetEventsInterface::g_msgproc_mutex){NodeClock::time_point::max()};
/** Whether this peer wants invs or headers (when possible) for block announcements */
@@ -482,7 +485,8 @@ struct CNodeState {
* drop the outbound one that least recently announced us a new block.
*/
struct ChainSyncTimeoutState {
- //! A timeout used for checking whether our peer has sufficiently synced
+ //! A timeout used for checking whether our peer has sufficiently synced,
+ //! or NodeClock::epoch when unset
NodeClock::time_point m_timeout{NodeClock::epoch};
//! A header with the work we require on our peer's chain
const CBlockIndex* m_work_header{nullptr};
@@ -959,7 +963,7 @@ private:
typedef std::multimap<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator>> BlockDownloadMap;
BlockDownloadMap mapBlocksInFlight GUARDED_BY(cs_main);
- /** When our tip was last updated. */
+ /** When our tip was last updated, or NodeClock::epoch for no update. */
std::atomic<NodeClock::time_point> m_last_tip_update{NodeClock::epoch};
/** Determine whether or not a peer can request a transaction, and return it (or nullptr if not found or not allowed). */
| int64_t PeerManagerImpl::ApproximateBestBlockDepth() const | ||
| { | ||
| return (GetTime<std::chrono::seconds>() - m_best_block_time.load()).count() / m_chainparams.GetConsensus().nPowTargetSpacing; | ||
| return (Now<NodeSeconds>() - m_best_block_time.load()) / m_chainparams.GetConsensus().PowTargetSpacing(); |
There was a problem hiding this comment.
nit: any reason we use Node<NodeSeconds>() here instead of NodeClock::now()?
|
🐙 This pull request conflicts with the target branch and needs rebase. |
ryanofsky
left a comment
There was a problem hiding this comment.
Code review ACK fab4bd7. Changes since last review: tweaking epoch comment and commit message as suggested, replacing nPowTargetSpacing with PowTargetSpacing a few places, simplifying HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER calculation making it slightly less precise but off by 1ms at most
jeanpablojp
left a comment
There was a problem hiding this comment.
tACK fab4bd7
Built and ran the unit suites and the p2p functional tests.
Left 3 nits (feel free to ignore)
| // Check that outbound peers have reasonable chains | ||
| // GetTime() is used by this anti-DoS logic so we can test this using mocktime | ||
| ConsiderEviction(node, peer, GetTime<std::chrono::seconds>()); | ||
| ConsiderEviction(node, peer, NodeClock::now()); |
There was a problem hiding this comment.
nit: MaybeSendAddr, GetRequestsToSend and MaybeSendFeefilter all end up taking the now from the top of SendMessages, and ConsiderEviction is the one that still takes its own read. Worth passing now here too?
| ConsiderEviction(node, peer, NodeClock::now()); | |
| ConsiderEviction(node, peer, now); |
| QueuedBlock &queuedBlock = state.vBlocksInFlight.front(); | ||
| int nOtherPeersWithValidatedDownloads = m_peers_downloading_from - 1; | ||
| if (current_time > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) { | ||
| if (now > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) { |
There was a problem hiding this comment.
nit: the rest of the file moved to consensusParams.PowTargetSpacing(), and this is the last duration still built by hand from nPowTargetSpacing.
| if (now > state.m_downloading_since + std::chrono::seconds{consensusParams.nPowTargetSpacing} * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) { | |
| if (now > state.m_downloading_since + consensusParams.PowTargetSpacing() * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) { |
| BOOST_CHECK(!IsEvicted( | ||
| number_of_nodes, [number_of_nodes](NodeEvictionCandidate& candidate) { | ||
| candidate.m_last_tx_time = std::chrono::seconds{number_of_nodes - candidate.id}; | ||
| candidate.m_last_tx_time = NodeSeconds{std::chrono::seconds{number_of_nodes - candidate.id}}; |
There was a problem hiding this comment.
nit: the eviction commit says the precision makes SelectNodeToEvict more precise through CompareNodeBlockTime and CompareNodeTXTime, and this fixture still hands it whole seconds. Casting both times back to seconds inside SelectNodeToEvict leaves peer_eviction_test green, and with these initialisations in milliseconds it fails. The other five in this test take the same change.
The announcement comparison in EvictExtraOutboundPeers has the same gap, worth one there too?
| candidate.m_last_tx_time = NodeSeconds{std::chrono::seconds{number_of_nodes - candidate.id}}; | |
| candidate.m_last_tx_time = NodeClock::time_point{std::chrono::milliseconds{number_of_nodes - candidate.id}}; |
|
Ping for rebase @maflcko |

It is a bit confusing to have some code use the deprecated
GetTime, which returns a duration and not a time point, and other code to useNodeClocktime points.Fix all places in
net_processing.cppto properly use time_point types.