Skip to content

Commit 9dd4de2

Browse files
author
MarcoFalke
committed
Merge #20027: Use mockable time everywhere in net_processing
b6834e3 Avoid 'timing mishap' warnings when mocking (Pieter Wuille) ec3916f Use mockable time everywhere in net_processing (Pieter Wuille) Pull request description: The fact that net_processing uses a mix of mockable tand non-mockable time functions made it hard to write functional tests for #19988. I'm opening this as a separate PR as I believe it's independently useful. In some ways this doesn't go quite as far as it could, as there are now several data structures that could be converted to `std::chrono` types as well now. I haven't done that here, but I'm happy to reconsider that. ACKs for top commit: MarcoFalke: ACK b6834e3 🌶 jnewbery: utACK b6834e3 naumenkogs: utACK b6834e3 Tree-SHA512: 6528a167c57926ca12894e0c476826411baf5de2f7b01c2125b97e5f710e620f427bbb13f72bdfc3de59072e56a9c1447bce832f41c725e00e81fea019518f0e
2 parents 283a73d + b6834e3 commit 9dd4de2

File tree

3 files changed

+34
-39
lines changed

3 files changed

+34
-39
lines changed

src/net_processing.cpp

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,7 @@ static bool MarkBlockAsReceived(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs
582582
}
583583
if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
584584
// First block on the queue was received, update the start download time for the next one
585-
state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
585+
state->nDownloadingSince = std::max(state->nDownloadingSince, count_microseconds(GetTime<std::chrono::microseconds>()));
586586
}
587587
state->vBlocksInFlight.erase(itInFlight->second.second);
588588
state->nBlocksInFlight--;
@@ -617,7 +617,7 @@ static bool MarkBlockAsInFlight(CTxMemPool& mempool, NodeId nodeid, const uint25
617617
state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
618618
if (state->nBlocksInFlight == 1) {
619619
// We're starting a block download (batch) from this peer.
620-
state->nDownloadingSince = GetTimeMicros();
620+
state->nDownloadingSince = GetTime<std::chrono::microseconds>().count();
621621
}
622622
if (state->nBlocksInFlightValidHeaders == 1 && pindex != nullptr) {
623623
nPeersWithValidatedDownloads++;
@@ -3637,7 +3637,7 @@ void PeerManager::ProcessMessage(CNode& pfrom, const std::string& msg_type, CDat
36373637
// Matching pong received, this ping is no longer outstanding
36383638
bPingFinished = true;
36393639
const auto ping_time = ping_end - pfrom.m_ping_start.load();
3640-
if (ping_time.count() > 0) {
3640+
if (ping_time.count() >= 0) {
36413641
// Successful ping time measurement, replace previous
36423642
pfrom.nPingUsecTime = count_microseconds(ping_time);
36433643
pfrom.nMinPingUsecTime = std::min(pfrom.nMinPingUsecTime.load(), count_microseconds(ping_time));
@@ -4102,7 +4102,6 @@ bool PeerManager::SendMessages(CNode* pto)
41024102
CNodeState &state = *State(pto->GetId());
41034103

41044104
// Address refresh broadcast
4105-
int64_t nNow = GetTimeMicros();
41064105
auto current_time = GetTime<std::chrono::microseconds>();
41074106

41084107
if (pto->RelayAddrsWithConn() && !::ChainstateActive().IsInitialBlockDownload() && pto->m_next_local_addr_send < current_time) {
@@ -4148,7 +4147,7 @@ bool PeerManager::SendMessages(CNode* pto)
41484147
// Only actively request headers from a single peer, unless we're close to today.
41494148
if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
41504149
state.fSyncStarted = true;
4151-
state.nHeadersSyncTimeout = GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(consensusParams.nPowTargetSpacing);
4150+
state.nHeadersSyncTimeout = count_microseconds(current_time) + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(consensusParams.nPowTargetSpacing);
41524151
nSyncStarted++;
41534152
const CBlockIndex *pindexStart = pindexBestHeader;
41544153
/* If possible, start at the block preceding the currently
@@ -4329,7 +4328,7 @@ bool PeerManager::SendMessages(CNode* pto)
43294328
if (pto->m_tx_relay->nNextInvSend < current_time) {
43304329
fSendTrickle = true;
43314330
if (pto->IsInboundConn()) {
4332-
pto->m_tx_relay->nNextInvSend = std::chrono::microseconds{m_connman.PoissonNextSendInbound(nNow, INVENTORY_BROADCAST_INTERVAL)};
4331+
pto->m_tx_relay->nNextInvSend = std::chrono::microseconds{m_connman.PoissonNextSendInbound(count_microseconds(current_time), INVENTORY_BROADCAST_INTERVAL)};
43334332
} else {
43344333
// Use half the delay for outbound peers, as there is less privacy concern for them.
43354334
pto->m_tx_relay->nNextInvSend = PoissonNextSend(current_time, std::chrono::seconds{INVENTORY_BROADCAST_INTERVAL >> 1});
@@ -4428,20 +4427,20 @@ bool PeerManager::SendMessages(CNode* pto)
44284427
nRelayedTransactions++;
44294428
{
44304429
// Expire old relay messages
4431-
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow)
4430+
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < count_microseconds(current_time))
44324431
{
44334432
mapRelay.erase(vRelayExpiration.front().second);
44344433
vRelayExpiration.pop_front();
44354434
}
44364435

44374436
auto ret = mapRelay.emplace(txid, std::move(txinfo.tx));
44384437
if (ret.second) {
4439-
vRelayExpiration.emplace_back(nNow + std::chrono::microseconds{RELAY_TX_CACHE_TIME}.count(), ret.first);
4438+
vRelayExpiration.emplace_back(count_microseconds(current_time + std::chrono::microseconds{RELAY_TX_CACHE_TIME}), ret.first);
44404439
}
44414440
// Add wtxid-based lookup into mapRelay as well, so that peers can request by wtxid
44424441
auto ret2 = mapRelay.emplace(wtxid, ret.first->second);
44434442
if (ret2.second) {
4444-
vRelayExpiration.emplace_back(nNow + std::chrono::microseconds{RELAY_TX_CACHE_TIME}.count(), ret2.first);
4443+
vRelayExpiration.emplace_back(count_microseconds(current_time + std::chrono::microseconds{RELAY_TX_CACHE_TIME}), ret2.first);
44454444
}
44464445
}
44474446
if (vInv.size() == MAX_INV_SZ) {
@@ -4466,10 +4465,7 @@ bool PeerManager::SendMessages(CNode* pto)
44664465

44674466
// Detect whether we're stalling
44684467
current_time = GetTime<std::chrono::microseconds>();
4469-
// nNow is the current system time (GetTimeMicros is not mockable) and
4470-
// should be replaced by the mockable current_time eventually
4471-
nNow = GetTimeMicros();
4472-
if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
4468+
if (state.nStallingSince && state.nStallingSince < count_microseconds(current_time) - 1000000 * BLOCK_STALLING_TIMEOUT) {
44734469
// Stalling only triggers when the block download window cannot move. During normal steady state,
44744470
// the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
44754471
// should only happen during initial block download.
@@ -4485,7 +4481,7 @@ bool PeerManager::SendMessages(CNode* pto)
44854481
if (state.vBlocksInFlight.size() > 0) {
44864482
QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
44874483
int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
4488-
if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
4484+
if (count_microseconds(current_time) > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
44894485
LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->GetId());
44904486
pto->fDisconnect = true;
44914487
return true;
@@ -4495,7 +4491,7 @@ bool PeerManager::SendMessages(CNode* pto)
44954491
if (state.fSyncStarted && state.nHeadersSyncTimeout < std::numeric_limits<int64_t>::max()) {
44964492
// Detect whether this is a stalling initial-headers-sync peer
44974493
if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - 24 * 60 * 60) {
4498-
if (nNow > state.nHeadersSyncTimeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
4494+
if (count_microseconds(current_time) > state.nHeadersSyncTimeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) {
44994495
// Disconnect a peer (without the noban permission) if it is our only sync peer,
45004496
// and we have others we could be using instead.
45014497
// Note: If all our peers are inbound, then we won't
@@ -4545,7 +4541,7 @@ bool PeerManager::SendMessages(CNode* pto)
45454541
}
45464542
if (state.nBlocksInFlight == 0 && staller != -1) {
45474543
if (State(staller)->nStallingSince == 0) {
4548-
State(staller)->nStallingSince = nNow;
4544+
State(staller)->nStallingSince = count_microseconds(current_time);
45494545
LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
45504546
}
45514547
}
@@ -4629,7 +4625,6 @@ bool PeerManager::SendMessages(CNode* pto)
46294625
!pto->HasPermission(PF_FORCERELAY) // peers with the forcerelay permission should not filter txs to us
46304626
) {
46314627
CAmount currentFilter = m_mempool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
4632-
int64_t timeNow = GetTimeMicros();
46334628
static FeeFilterRounder g_filter_rounder{CFeeRate{DEFAULT_MIN_RELAY_TX_FEE}};
46344629
if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
46354630
// Received tx-inv messages are discarded when the active
@@ -4640,24 +4635,24 @@ bool PeerManager::SendMessages(CNode* pto)
46404635
if (pto->m_tx_relay->lastSentFeeFilter == MAX_FILTER) {
46414636
// Send the current filter if we sent MAX_FILTER previously
46424637
// and made it out of IBD.
4643-
pto->m_tx_relay->nextSendTimeFeeFilter = timeNow - 1;
4638+
pto->m_tx_relay->nextSendTimeFeeFilter = count_microseconds(current_time) - 1;
46444639
}
46454640
}
4646-
if (timeNow > pto->m_tx_relay->nextSendTimeFeeFilter) {
4641+
if (count_microseconds(current_time) > pto->m_tx_relay->nextSendTimeFeeFilter) {
46474642
CAmount filterToSend = g_filter_rounder.round(currentFilter);
46484643
// We always have a fee filter of at least minRelayTxFee
46494644
filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
46504645
if (filterToSend != pto->m_tx_relay->lastSentFeeFilter) {
46514646
m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
46524647
pto->m_tx_relay->lastSentFeeFilter = filterToSend;
46534648
}
4654-
pto->m_tx_relay->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
4649+
pto->m_tx_relay->nextSendTimeFeeFilter = PoissonNextSend(count_microseconds(current_time), AVG_FEEFILTER_BROADCAST_INTERVAL);
46554650
}
46564651
// If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
46574652
// until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
4658-
else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->m_tx_relay->nextSendTimeFeeFilter &&
4653+
else if (count_microseconds(current_time) + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->m_tx_relay->nextSendTimeFeeFilter &&
46594654
(currentFilter < 3 * pto->m_tx_relay->lastSentFeeFilter / 4 || currentFilter > 4 * pto->m_tx_relay->lastSentFeeFilter / 3)) {
4660-
pto->m_tx_relay->nextSendTimeFeeFilter = timeNow + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
4655+
pto->m_tx_relay->nextSendTimeFeeFilter = count_microseconds(current_time) + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
46614656
}
46624657
}
46634658
} // release cs_main

test/functional/p2p_tx_download.py

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -158,23 +158,19 @@ def test_spurious_notfound(self):
158158
self.nodes[0].p2ps[0].send_message(msg_notfound(vec=[CInv(MSG_TX, 1)]))
159159

160160
def run_test(self):
161-
# Setup the p2p connections
162-
self.peers = []
163-
for node in self.nodes:
164-
for _ in range(NUM_INBOUND):
165-
self.peers.append(node.add_p2p_connection(TestP2PConn()))
166-
167-
self.log.info("Nodes are setup with {} incoming connections each".format(NUM_INBOUND))
168-
169-
self.test_spurious_notfound()
170-
171-
# Test the in-flight max first, because we want no transactions in
172-
# flight ahead of this test.
173-
self.test_in_flight_max()
174-
175-
self.test_inv_block()
176-
177-
self.test_tx_requests()
161+
# Run each test against new bitcoind instances, as setting mocktimes has long-term effects on when
162+
# the next trickle relay event happens.
163+
for test in [self.test_spurious_notfound, self.test_in_flight_max, self.test_inv_block, self.test_tx_requests]:
164+
self.stop_nodes()
165+
self.start_nodes()
166+
self.connect_nodes(1, 0)
167+
# Setup the p2p connections
168+
self.peers = []
169+
for node in self.nodes:
170+
for _ in range(NUM_INBOUND):
171+
self.peers.append(node.add_p2p_connection(TestP2PConn()))
172+
self.log.info("Nodes are setup with {} incoming connections each".format(NUM_INBOUND))
173+
test()
178174

179175

180176
if __name__ == '__main__':

test/functional/wallet_resendwallettransactions.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,10 @@ def run_test(self):
6464
# Transaction should be rebroadcast approximately 24 hours in the future,
6565
# but can range from 12-36. So bump 36 hours to be sure.
6666
node.setmocktime(now + 36 * 60 * 60)
67+
# Tell scheduler to call MaybeResendWalletTxn now.
68+
node.mockscheduler(1)
69+
# Give some time for trickle to occur
70+
node.setmocktime(now + 36 * 60 * 60 + 600)
6771
peer_second.wait_for_broadcast([txid])
6872

6973

0 commit comments

Comments
 (0)