Skip to content

Commit 0620957

Browse files
author
MarcoFalke
committed
Merge bitcoin/bitcoin#23832: Refactor: Changes time variables from int to chrono
fe86eb5 Refactor: Uses c++ init convention for time variables (Shashwat) 6111b0d Refactor: Changes remaining time variable type from int to chrono (Shashwat) Pull request description: This PR is a follow-up to #23801. This PR aims to make the following changes to all the time variables in **net_processing.cpp** wherever possible. - Convert all time variables to `std::chrono.` - Use `chorno::literals` wherever possible. - Use `auto` keywords wherever possible. - Use `var{val}` convention of initialization. This PR also minimizes the number of times, serialization of time `count_seconds(..)` occurs. ACKs for top commit: MarcoFalke: re-ACK fe86eb5 🏕 Tree-SHA512: c8684c0c60a11140027e36b6e9706a45ecdeae6b5ba0bf267e50655835daee5e5410e34096a8c4eca005f327caae1ac258cc7b8ba663eab58abf131f6d2f4d42
2 parents 799fd7a + fe86eb5 commit 0620957

File tree

1 file changed

+40
-40
lines changed

1 file changed

+40
-40
lines changed

src/net_processing.cpp

Lines changed: 40 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,14 @@ static constexpr auto HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1ms;
5757
* behind headers chain.
5858
*/
5959
static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4;
60-
/** Timeout for (unprotected) outbound peers to sync to our chainwork, in seconds */
61-
static constexpr int64_t CHAIN_SYNC_TIMEOUT = 20 * 60; // 20 minutes
60+
/** Timeout for (unprotected) outbound peers to sync to our chainwork */
61+
static constexpr auto CHAIN_SYNC_TIMEOUT{20min};
6262
/** How frequently to check for stale tips */
6363
static constexpr auto STALE_CHECK_INTERVAL{10min};
6464
/** How frequently to check for extra outbound peers and disconnect */
6565
static constexpr auto EXTRA_PEER_CHECK_INTERVAL{45s};
6666
/** Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict */
67-
static constexpr std::chrono::seconds MINIMUM_CONNECT_TIME{30};
67+
static constexpr auto MINIMUM_CONNECT_TIME{30s};
6868
/** SHA256("main address relay")[0:8] */
6969
static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL;
7070
/// Age after which a stale block will no longer be served if requested as
@@ -74,7 +74,7 @@ static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60;
7474
/// limiting block relay. Set to one week, denominated in seconds.
7575
static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60;
7676
/** Time between pings automatically sent out for latency probing and keepalive */
77-
static constexpr std::chrono::minutes PING_INTERVAL{2};
77+
static constexpr auto PING_INTERVAL{2min};
7878
/** The maximum number of entries in a locator */
7979
static const unsigned int MAX_LOCATOR_SZ = 101;
8080
/** The maximum number of entries in an 'inv' protocol message */
@@ -88,19 +88,19 @@ static constexpr int32_t MAX_PEER_TX_REQUEST_IN_FLIGHT = 100;
8888
* the actual transaction (from any peer) in response to requests for them. */
8989
static constexpr int32_t MAX_PEER_TX_ANNOUNCEMENTS = 5000;
9090
/** How long to delay requesting transactions via txids, if we have wtxid-relaying peers */
91-
static constexpr auto TXID_RELAY_DELAY = std::chrono::seconds{2};
91+
static constexpr auto TXID_RELAY_DELAY{2s};
9292
/** How long to delay requesting transactions from non-preferred peers */
93-
static constexpr auto NONPREF_PEER_TX_DELAY = std::chrono::seconds{2};
93+
static constexpr auto NONPREF_PEER_TX_DELAY{2s};
9494
/** How long to delay requesting transactions from overloaded peers (see MAX_PEER_TX_REQUEST_IN_FLIGHT). */
95-
static constexpr auto OVERLOADED_PEER_TX_DELAY = std::chrono::seconds{2};
96-
/** How long to wait (in microseconds) before downloading a transaction from an additional peer */
97-
static constexpr std::chrono::microseconds GETDATA_TX_INTERVAL{std::chrono::seconds{60}};
95+
static constexpr auto OVERLOADED_PEER_TX_DELAY{2s};
96+
/** How long to wait before downloading a transaction from an additional peer */
97+
static constexpr auto GETDATA_TX_INTERVAL{60s};
9898
/** Limit to avoid sending big packets. Not used in processing incoming GETDATA for compatibility */
9999
static const unsigned int MAX_GETDATA_SZ = 1000;
100100
/** Number of blocks that can be requested at any given time from a single peer. */
101101
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
102102
/** Time during which a peer must stall block download progress before being disconnected. */
103-
static constexpr auto BLOCK_STALLING_TIMEOUT = 2s;
103+
static constexpr auto BLOCK_STALLING_TIMEOUT{2s};
104104
/** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
105105
* less than this number, we reached its tip. Changing this value is a protocol upgrade. */
106106
static const unsigned int MAX_HEADERS_RESULTS = 2000;
@@ -125,16 +125,16 @@ static const int MAX_UNCONNECTING_HEADERS = 10;
125125
/** Minimum blocks required to signal NODE_NETWORK_LIMITED */
126126
static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288;
127127
/** Average delay between local address broadcasts */
128-
static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL = 24h;
128+
static constexpr auto AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL{24h};
129129
/** Average delay between peer address broadcasts */
130-
static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL = 30s;
130+
static constexpr auto AVG_ADDRESS_BROADCAST_INTERVAL{30s};
131131
/** Average delay between trickled inventory transmissions for inbound peers.
132132
* Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */
133-
static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL = 5s;
133+
static constexpr auto INBOUND_INVENTORY_BROADCAST_INTERVAL{5s};
134134
/** Average delay between trickled inventory transmissions for outbound peers.
135135
* Use a smaller delay as there is less privacy concern for them.
136136
* Blocks and peers with NetPermissionFlags::NoBan permission bypass this. */
137-
static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL = 2s;
137+
static constexpr auto OUTBOUND_INVENTORY_BROADCAST_INTERVAL{2s};
138138
/** Maximum rate of inventory items to send per second.
139139
* Limits the impact of low-fee transaction floods. */
140140
static constexpr unsigned int INVENTORY_BROADCAST_PER_SECOND = 7;
@@ -148,9 +148,9 @@ static constexpr unsigned int INVENTORY_MAX_RECENT_RELAY = 3500;
148148
* peers, and random variations in the broadcast mechanism. */
149149
static_assert(INVENTORY_MAX_RECENT_RELAY >= INVENTORY_BROADCAST_PER_SECOND * UNCONDITIONAL_RELAY_DELAY / std::chrono::seconds{1}, "INVENTORY_RELAY_MAX too low");
150150
/** Average delay between feefilter broadcasts in seconds. */
151-
static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL = 10min;
151+
static constexpr auto AVG_FEEFILTER_BROADCAST_INTERVAL{10min};
152152
/** Maximum feefilter broadcast delay after significant change. */
153-
static constexpr auto MAX_FEEFILTER_CHANGE_DELAY = 5min;
153+
static constexpr auto MAX_FEEFILTER_CHANGE_DELAY{5min};
154154
/** Maximum number of compact filters that may be requested with one getcfilters. See BIP 157. */
155155
static constexpr uint32_t MAX_GETCFILTERS_SIZE = 1000;
156156
/** Maximum number of cf hashes that may be requested with one getcfheaders. See BIP 157. */
@@ -329,7 +329,7 @@ class PeerManagerImpl final : public PeerManager
329329
EXCLUSIVE_LOCKS_REQUIRED(cs_main);
330330

331331
/** Consider evicting an outbound peer based on the amount of time they've been behind our tip */
332-
void ConsiderEviction(CNode& pto, int64_t time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
332+
void ConsiderEviction(CNode& pto, std::chrono::seconds time_in_seconds) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
333333

334334
/** If we have extra outbound peers, try to disconnect the one with the oldest block announcement */
335335
void EvictExtraOutboundPeers(std::chrono::seconds now) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
@@ -727,7 +727,7 @@ struct CNodeState {
727727
* - its chain tip has at least as much work as ours
728728
*
729729
* CHAIN_SYNC_TIMEOUT: if a peer's best known block has less work than our tip,
730-
* set a timeout CHAIN_SYNC_TIMEOUT seconds in the future:
730+
* set a timeout CHAIN_SYNC_TIMEOUT in the future:
731731
* - If at timeout their best known block now has more work than our tip
732732
* when the timeout was set, then either reset the timeout or clear it
733733
* (after comparing against our current tip's work)
@@ -742,7 +742,7 @@ struct CNodeState {
742742
*/
743743
struct ChainSyncTimeoutState {
744744
//! A timeout used for checking whether our peer has sufficiently synced
745-
int64_t m_timeout{0};
745+
std::chrono::seconds m_timeout{0s};
746746
//! A header with the work we require on our peer's chain
747747
const CBlockIndex* m_work_header{nullptr};
748748
//! After timeout is reached, set to true after sending getheaders
@@ -949,10 +949,10 @@ bool PeerManagerImpl::TipMayBeStale()
949949
{
950950
AssertLockHeld(cs_main);
951951
const Consensus::Params& consensusParams = m_chainparams.GetConsensus();
952-
if (count_seconds(m_last_tip_update) == 0) {
952+
if (m_last_tip_update.load() == 0s) {
953953
m_last_tip_update = GetTime<std::chrono::seconds>();
954954
}
955-
return count_seconds(m_last_tip_update) < GetTime() - consensusParams.nPowTargetSpacing * 3 && mapBlocksInFlight.empty();
955+
return m_last_tip_update.load() < GetTime<std::chrono::seconds>() - std::chrono::seconds{consensusParams.nPowTargetSpacing * 3} && mapBlocksInFlight.empty();
956956
}
957957

958958
bool PeerManagerImpl::CanDirectFetch()
@@ -1137,7 +1137,7 @@ void PeerManagerImpl::AddTxAnnouncement(const CNode& node, const GenTxid& gtxid,
11371137
// - TXID_RELAY_DELAY for txid announcements while wtxid peers are available
11381138
// - OVERLOADED_PEER_TX_DELAY for announcements from peers which have at least
11391139
// MAX_PEER_TX_REQUEST_IN_FLIGHT requests in flight (and don't have NetPermissionFlags::Relay).
1140-
auto delay = std::chrono::microseconds{0};
1140+
auto delay{0us};
11411141
const bool preferred = state->fPreferredDownload;
11421142
if (!preferred) delay += NONPREF_PEER_TX_DELAY;
11431143
if (!gtxid.IsWtxid() && m_wtxid_relay_peers > 0) delay += TXID_RELAY_DELAY;
@@ -1191,7 +1191,7 @@ void PeerManagerImpl::ReattemptInitialBroadcast(CScheduler& scheduler)
11911191

11921192
// Schedule next run for 10-15 minutes in the future.
11931193
// We add randomness on every cycle to avoid the possibility of P2P fingerprinting.
1194-
const std::chrono::milliseconds delta = std::chrono::minutes{10} + GetRandMillis(std::chrono::minutes{5});
1194+
const std::chrono::milliseconds delta = 10min + GetRandMillis(5min);
11951195
scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
11961196
}
11971197

@@ -1296,7 +1296,7 @@ bool PeerManagerImpl::GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) c
12961296
// since pingtime does not update until the ping is complete, which might take a while.
12971297
// So, if a ping is taking an unusually long time in flight,
12981298
// the caller can immediately detect that this is happening.
1299-
std::chrono::microseconds ping_wait{0};
1299+
auto ping_wait{0us};
13001300
if ((0 != peer->m_ping_nonce_sent) && (0 != peer->m_ping_start.load().count())) {
13011301
ping_wait = GetTime<std::chrono::microseconds>() - peer->m_ping_start.load();
13021302
}
@@ -1496,7 +1496,7 @@ void PeerManagerImpl::StartScheduledTasks(CScheduler& scheduler)
14961496
scheduler.scheduleEvery([this] { this->CheckForStaleTipAndEvictPeers(); }, std::chrono::seconds{EXTRA_PEER_CHECK_INTERVAL});
14971497

14981498
// schedule next run for 10-15 minutes in the future
1499-
const std::chrono::milliseconds delta = std::chrono::minutes{10} + GetRandMillis(std::chrono::minutes{5});
1499+
const std::chrono::milliseconds delta = 10min + GetRandMillis(5min);
15001500
scheduler.scheduleFromNow([&] { ReattemptInitialBroadcast(scheduler); }, delta);
15011501
}
15021502

@@ -1963,10 +1963,9 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic
19631963
std::vector<CInv> vNotFound;
19641964
const CNetMsgMaker msgMaker(pfrom.GetCommonVersion());
19651965

1966-
const std::chrono::seconds now = GetTime<std::chrono::seconds>();
1966+
const auto now{GetTime<std::chrono::seconds>()};
19671967
// Get last mempool request time
1968-
const std::chrono::seconds mempool_req = pfrom.m_tx_relay != nullptr ? pfrom.m_tx_relay->m_last_mempool_req.load()
1969-
: std::chrono::seconds::min();
1968+
const auto mempool_req = pfrom.m_tx_relay != nullptr ? pfrom.m_tx_relay->m_last_mempool_req.load() : std::chrono::seconds::min();
19701969

19711970
// Process as many TX items from the front of the getdata queue as
19721971
// possible, since they're common and it's efficient to batch process
@@ -2890,7 +2889,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
28902889
int64_t nSince = nNow - 10 * 60;
28912890

28922891
// Update/increment addr rate limiting bucket.
2893-
const auto current_time = GetTime<std::chrono::microseconds>();
2892+
const auto current_time{GetTime<std::chrono::microseconds>()};
28942893
if (peer->m_addr_token_bucket < MAX_ADDR_PROCESSING_TOKEN_BUCKET) {
28952894
// Don't increment bucket if it's already full
28962895
const auto time_diff = std::max(current_time - peer->m_addr_token_timestamp, 0us);
@@ -2976,7 +2975,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
29762975

29772976
LOCK(cs_main);
29782977

2979-
const auto current_time = GetTime<std::chrono::microseconds>();
2978+
const auto current_time{GetTime<std::chrono::microseconds>()};
29802979
uint256* best_block{nullptr};
29812980

29822981
for (CInv& inv : vInv) {
@@ -3354,7 +3353,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type,
33543353
}
33553354
}
33563355
if (!fRejectedParents) {
3357-
const auto current_time = GetTime<std::chrono::microseconds>();
3356+
const auto current_time{GetTime<std::chrono::microseconds>()};
33583357

33593358
for (const uint256& parent_txid : unique_parents) {
33603359
// Here, we only have the txid (and not wtxid) of the
@@ -4180,7 +4179,7 @@ bool PeerManagerImpl::ProcessMessages(CNode* pfrom, std::atomic<bool>& interrupt
41804179
return fMoreWork;
41814180
}
41824181

4183-
void PeerManagerImpl::ConsiderEviction(CNode& pto, int64_t time_in_seconds)
4182+
void PeerManagerImpl::ConsiderEviction(CNode& pto, std::chrono::seconds time_in_seconds)
41844183
{
41854184
AssertLockHeld(cs_main);
41864185

@@ -4195,20 +4194,20 @@ void PeerManagerImpl::ConsiderEviction(CNode& pto, int64_t time_in_seconds)
41954194
// unless it's invalid, in which case we should find that out and
41964195
// disconnect from them elsewhere).
41974196
if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork) {
4198-
if (state.m_chain_sync.m_timeout != 0) {
4199-
state.m_chain_sync.m_timeout = 0;
4197+
if (state.m_chain_sync.m_timeout != 0s) {
4198+
state.m_chain_sync.m_timeout = 0s;
42004199
state.m_chain_sync.m_work_header = nullptr;
42014200
state.m_chain_sync.m_sent_getheaders = false;
42024201
}
4203-
} else if (state.m_chain_sync.m_timeout == 0 || (state.m_chain_sync.m_work_header != nullptr && state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork)) {
4202+
} else if (state.m_chain_sync.m_timeout == 0s || (state.m_chain_sync.m_work_header != nullptr && state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork)) {
42044203
// Our best block known by this peer is behind our tip, and we're either noticing
42054204
// that for the first time, OR this peer was able to catch up to some earlier point
42064205
// where we checked against our tip.
42074206
// Either way, set a new timeout based on current tip.
42084207
state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT;
42094208
state.m_chain_sync.m_work_header = m_chainman.ActiveChain().Tip();
42104209
state.m_chain_sync.m_sent_getheaders = false;
4211-
} else if (state.m_chain_sync.m_timeout > 0 && time_in_seconds > state.m_chain_sync.m_timeout) {
4210+
} else if (state.m_chain_sync.m_timeout > 0s && time_in_seconds > state.m_chain_sync.m_timeout) {
42124211
// No evidence yet that our peer has synced to a chain with work equal to that
42134212
// of our tip, when we first detected it was behind. Send a single getheaders
42144213
// message to give the peer a chance to update us.
@@ -4221,7 +4220,7 @@ void PeerManagerImpl::ConsiderEviction(CNode& pto, int64_t time_in_seconds)
42214220
LogPrint(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", state.m_chain_sync.m_work_header->GetBlockHash().ToString());
42224221
m_connman.PushMessage(&pto, msgMaker.Make(NetMsgType::GETHEADERS, m_chainman.ActiveChain().GetLocator(state.m_chain_sync.m_work_header->pprev), uint256()));
42234222
state.m_chain_sync.m_sent_getheaders = true;
4224-
constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes
4223+
constexpr auto HEADERS_RESPONSE_TIME{2min};
42254224
// Bump the timeout to allow a response, which could clear the timeout
42264225
// (if the response shows the peer has synced), reset the timeout (if
42274226
// the peer syncs to the required work but not to our tip), or result
@@ -4348,7 +4347,8 @@ void PeerManagerImpl::CheckForStaleTipAndEvictPeers()
43484347
// Check whether our tip is stale, and if so, allow using an extra
43494348
// outbound peer
43504349
if (!fImporting && !fReindex && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) {
4351-
LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", count_seconds(now) - count_seconds(m_last_tip_update));
4350+
LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n",
4351+
count_seconds(now - m_last_tip_update.load()));
43524352
m_connman.SetTryNewOutboundPeer(true);
43534353
} else if (m_connman.GetTryNewOutboundPeer()) {
43544354
m_connman.SetTryNewOutboundPeer(false);
@@ -4570,7 +4570,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
45704570
// If we get here, the outgoing message serialization version is set and can't change.
45714571
const CNetMsgMaker msgMaker(pto->GetCommonVersion());
45724572

4573-
const auto current_time = GetTime<std::chrono::microseconds>();
4573+
const auto current_time{GetTime<std::chrono::microseconds>()};
45744574

45754575
if (pto->IsAddrFetchConn() && current_time - pto->m_connected > 10 * AVG_ADDRESS_BROADCAST_INTERVAL) {
45764576
LogPrint(BCLog::NET, "addrfetch connection timeout; disconnecting peer=%d\n", pto->GetId());
@@ -4969,7 +4969,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
49694969

49704970
// Check that outbound peers have reasonable chains
49714971
// GetTime() is used by this anti-DoS logic so we can test this using mocktime
4972-
ConsiderEviction(*pto, GetTime());
4972+
ConsiderEviction(*pto, GetTime<std::chrono::seconds>());
49734973

49744974
//
49754975
// Message: getdata (blocks)

0 commit comments

Comments
 (0)