Skip to content

Commit fa883ab

Browse files
author
MarcoFalke
committed
net: Use mockable time for tx download
1 parent fce4123 commit fa883ab

File tree

3 files changed

+42
-32
lines changed

3 files changed

+42
-32
lines changed

src/net_processing.cpp

Lines changed: 34 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,13 @@ static constexpr int32_t MAX_PEER_TX_IN_FLIGHT = 100;
6868
/** Maximum number of announced transactions from a peer */
6969
static constexpr int32_t MAX_PEER_TX_ANNOUNCEMENTS = 2 * MAX_INV_SZ;
7070
/** How many microseconds to delay requesting transactions from inbound peers */
71-
static constexpr int64_t INBOUND_PEER_TX_DELAY = 2 * 1000000; // 2 seconds
71+
static constexpr std::chrono::microseconds INBOUND_PEER_TX_DELAY{std::chrono::seconds{2}};
7272
/** How long to wait (in microseconds) before downloading a transaction from an additional peer */
73-
static constexpr int64_t GETDATA_TX_INTERVAL = 60 * 1000000; // 1 minute
73+
static constexpr std::chrono::microseconds GETDATA_TX_INTERVAL{std::chrono::seconds{60}};
7474
/** Maximum delay (in microseconds) for transaction requests to avoid biasing some peers over others. */
75-
static constexpr int64_t MAX_GETDATA_RANDOM_DELAY = 2 * 1000000; // 2 seconds
75+
static constexpr std::chrono::microseconds MAX_GETDATA_RANDOM_DELAY{std::chrono::seconds{2}};
7676
/** How long to wait (in microseconds) before expiring an in-flight getdata request to a peer */
77-
static constexpr int64_t TX_EXPIRY_INTERVAL = 10 * GETDATA_TX_INTERVAL;
77+
static constexpr std::chrono::microseconds TX_EXPIRY_INTERVAL{GETDATA_TX_INTERVAL * 10};
7878
static_assert(INBOUND_PEER_TX_DELAY >= MAX_GETDATA_RANDOM_DELAY,
7979
"To preserve security, MAX_GETDATA_RANDOM_DELAY should not exceed INBOUND_PEER_DELAY");
8080
/** Limit to avoid sending big packets. Not used in processing incoming GETDATA for compatibility */
@@ -340,16 +340,16 @@ struct CNodeState {
340340
/* Track when to attempt download of announced transactions (process
341341
* time in micros -> txid)
342342
*/
343-
std::multimap<int64_t, uint256> m_tx_process_time;
343+
std::multimap<std::chrono::microseconds, uint256> m_tx_process_time;
344344

345345
//! Store all the transactions a peer has recently announced
346346
std::set<uint256> m_tx_announced;
347347

348348
//! Store transactions which were requested by us, with timestamp
349-
std::map<uint256, int64_t> m_tx_in_flight;
349+
std::map<uint256, std::chrono::microseconds> m_tx_in_flight;
350350

351351
//! Periodically check for stuck getdata requests
352-
int64_t m_check_expiry_timer{0};
352+
std::chrono::microseconds m_check_expiry_timer{0};
353353
};
354354

355355
TxDownloadState m_tx_download;
@@ -391,7 +391,7 @@ struct CNodeState {
391391
};
392392

393393
// Keeps track of the time (in microseconds) when transactions were requested last time
394-
limitedmap<uint256, int64_t> g_already_asked_for GUARDED_BY(cs_main)(MAX_INV_SZ);
394+
limitedmap<uint256, std::chrono::microseconds> g_already_asked_for GUARDED_BY(cs_main)(MAX_INV_SZ);
395395

396396
/** Map maintaining per-node state. */
397397
static std::map<NodeId, CNodeState> mapNodeState GUARDED_BY(cs_main);
@@ -688,16 +688,16 @@ void EraseTxRequest(const uint256& txid) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
688688
g_already_asked_for.erase(txid);
689689
}
690690

691-
int64_t GetTxRequestTime(const uint256& txid) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
691+
std::chrono::microseconds GetTxRequestTime(const uint256& txid) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
692692
{
693693
auto it = g_already_asked_for.find(txid);
694694
if (it != g_already_asked_for.end()) {
695695
return it->second;
696696
}
697-
return 0;
697+
return {};
698698
}
699699

700-
void UpdateTxRequestTime(const uint256& txid, int64_t request_time) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
700+
void UpdateTxRequestTime(const uint256& txid, std::chrono::microseconds request_time) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
701701
{
702702
auto it = g_already_asked_for.find(txid);
703703
if (it == g_already_asked_for.end()) {
@@ -707,17 +707,17 @@ void UpdateTxRequestTime(const uint256& txid, int64_t request_time) EXCLUSIVE_LO
707707
}
708708
}
709709

710-
int64_t CalculateTxGetDataTime(const uint256& txid, int64_t current_time, bool use_inbound_delay) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
710+
std::chrono::microseconds CalculateTxGetDataTime(const uint256& txid, std::chrono::microseconds current_time, bool use_inbound_delay) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
711711
{
712-
int64_t process_time;
713-
int64_t last_request_time = GetTxRequestTime(txid);
712+
std::chrono::microseconds process_time;
713+
const auto last_request_time = GetTxRequestTime(txid);
714714
// First time requesting this tx
715-
if (last_request_time == 0) {
715+
if (last_request_time.count() == 0) {
716716
process_time = current_time;
717717
} else {
718718
// Randomize the delay to avoid biasing some peers over others (such as due to
719719
// fixed ordering of peer processing in ThreadMessageHandler)
720-
process_time = last_request_time + GETDATA_TX_INTERVAL + GetRand(MAX_GETDATA_RANDOM_DELAY);
720+
process_time = last_request_time + GETDATA_TX_INTERVAL + GetRandMicros(MAX_GETDATA_RANDOM_DELAY);
721721
}
722722

723723
// We delay processing announcements from inbound peers
@@ -726,7 +726,7 @@ int64_t CalculateTxGetDataTime(const uint256& txid, int64_t current_time, bool u
726726
return process_time;
727727
}
728728

729-
void RequestTx(CNodeState* state, const uint256& txid, int64_t nNow) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
729+
void RequestTx(CNodeState* state, const uint256& txid, std::chrono::microseconds current_time) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
730730
{
731731
CNodeState::TxDownloadState& peer_download_state = state->m_tx_download;
732732
if (peer_download_state.m_tx_announced.size() >= MAX_PEER_TX_ANNOUNCEMENTS ||
@@ -740,7 +740,7 @@ void RequestTx(CNodeState* state, const uint256& txid, int64_t nNow) EXCLUSIVE_L
740740

741741
// Calculate the time to try requesting this transaction. Use
742742
// fPreferredDownload as a proxy for outbound peers.
743-
int64_t process_time = CalculateTxGetDataTime(txid, nNow, !state->fPreferredDownload);
743+
const auto process_time = CalculateTxGetDataTime(txid, current_time, !state->fPreferredDownload);
744744

745745
peer_download_state.m_tx_process_time.emplace(process_time, txid);
746746
}
@@ -2218,7 +2218,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
22182218
LOCK(cs_main);
22192219

22202220
uint32_t nFetchFlags = GetFetchFlags(pfrom);
2221-
int64_t nNow = GetTimeMicros();
2221+
const auto current_time = GetTime<std::chrono::microseconds>();
22222222

22232223
for (CInv &inv : vInv)
22242224
{
@@ -2250,7 +2250,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
22502250
if (fBlocksOnly) {
22512251
LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->GetId());
22522252
} else if (!fAlreadyHave && !fImporting && !fReindex && !::ChainstateActive().IsInitialBlockDownload()) {
2253-
RequestTx(State(pfrom->GetId()), inv.hash, nNow);
2253+
RequestTx(State(pfrom->GetId()), inv.hash, current_time);
22542254
}
22552255
}
22562256
}
@@ -2524,12 +2524,12 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
25242524
}
25252525
if (!fRejectedParents) {
25262526
uint32_t nFetchFlags = GetFetchFlags(pfrom);
2527-
int64_t nNow = GetTimeMicros();
2527+
const auto current_time = GetTime<std::chrono::microseconds>();
25282528

25292529
for (const CTxIn& txin : tx.vin) {
25302530
CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
25312531
pfrom->AddInventoryKnown(_inv);
2532-
if (!AlreadyHave(_inv)) RequestTx(State(pfrom->GetId()), _inv.hash, nNow);
2532+
if (!AlreadyHave(_inv)) RequestTx(State(pfrom->GetId()), _inv.hash, current_time);
25332533
}
25342534
AddOrphanTx(ptx, pfrom->GetId());
25352535

@@ -3900,6 +3900,9 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
39003900
connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
39013901

39023902
// Detect whether we're stalling
3903+
const auto current_time = GetTime<std::chrono::microseconds>();
3904+
// nNow is the current system time (GetTimeMicros is not mockable) and
3905+
// should be replaced by the mockable current_time eventually
39033906
nNow = GetTimeMicros();
39043907
if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
39053908
// Stalling only triggers when the block download window cannot move. During normal steady state,
@@ -3992,9 +3995,9 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
39923995
// were unresponsive in the past.
39933996
// Eventually we should consider disconnecting peers, but this is
39943997
// conservative.
3995-
if (state.m_tx_download.m_check_expiry_timer <= nNow) {
3998+
if (state.m_tx_download.m_check_expiry_timer <= current_time) {
39963999
for (auto it=state.m_tx_download.m_tx_in_flight.begin(); it != state.m_tx_download.m_tx_in_flight.end();) {
3997-
if (it->second <= nNow - TX_EXPIRY_INTERVAL) {
4000+
if (it->second <= current_time - TX_EXPIRY_INTERVAL) {
39984001
LogPrint(BCLog::NET, "timeout of inflight tx %s from peer=%d\n", it->first.ToString(), pto->GetId());
39994002
state.m_tx_download.m_tx_announced.erase(it->first);
40004003
state.m_tx_download.m_tx_in_flight.erase(it++);
@@ -4004,11 +4007,11 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
40044007
}
40054008
// On average, we do this check every TX_EXPIRY_INTERVAL. Randomize
40064009
// so that we're not doing this for all peers at the same time.
4007-
state.m_tx_download.m_check_expiry_timer = nNow + TX_EXPIRY_INTERVAL/2 + GetRand(TX_EXPIRY_INTERVAL);
4010+
state.m_tx_download.m_check_expiry_timer = current_time + TX_EXPIRY_INTERVAL / 2 + GetRandMicros(TX_EXPIRY_INTERVAL);
40084011
}
40094012

40104013
auto& tx_process_time = state.m_tx_download.m_tx_process_time;
4011-
while (!tx_process_time.empty() && tx_process_time.begin()->first <= nNow && state.m_tx_download.m_tx_in_flight.size() < MAX_PEER_TX_IN_FLIGHT) {
4014+
while (!tx_process_time.empty() && tx_process_time.begin()->first <= current_time && state.m_tx_download.m_tx_in_flight.size() < MAX_PEER_TX_IN_FLIGHT) {
40124015
const uint256 txid = tx_process_time.begin()->second;
40134016
// Erase this entry from tx_process_time (it may be added back for
40144017
// processing at a later time, see below)
@@ -4017,22 +4020,22 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
40174020
if (!AlreadyHave(inv)) {
40184021
// If this transaction was last requested more than 1 minute ago,
40194022
// then request.
4020-
int64_t last_request_time = GetTxRequestTime(inv.hash);
4021-
if (last_request_time <= nNow - GETDATA_TX_INTERVAL) {
4023+
const auto last_request_time = GetTxRequestTime(inv.hash);
4024+
if (last_request_time <= current_time - GETDATA_TX_INTERVAL) {
40224025
LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());
40234026
vGetData.push_back(inv);
40244027
if (vGetData.size() >= MAX_GETDATA_SZ) {
40254028
connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
40264029
vGetData.clear();
40274030
}
4028-
UpdateTxRequestTime(inv.hash, nNow);
4029-
state.m_tx_download.m_tx_in_flight.emplace(inv.hash, nNow);
4031+
UpdateTxRequestTime(inv.hash, current_time);
4032+
state.m_tx_download.m_tx_in_flight.emplace(inv.hash, current_time);
40304033
} else {
40314034
// This transaction is in flight from someone else; queue
40324035
// up processing to happen after the download times out
40334036
// (with a slight delay for inbound peers, to prefer
40344037
// requests to outbound peers).
4035-
int64_t next_process_time = CalculateTxGetDataTime(txid, nNow, !state.fPreferredDownload);
4038+
const auto next_process_time = CalculateTxGetDataTime(txid, current_time, !state.fPreferredDownload);
40364039
tx_process_time.emplace(next_process_time, txid);
40374040
}
40384041
} else {

src/random.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -667,6 +667,11 @@ uint64_t GetRand(uint64_t nMax) noexcept
667667
return FastRandomContext(g_mock_deterministic_tests).randrange(nMax);
668668
}
669669

670+
std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept
671+
{
672+
return std::chrono::microseconds{GetRand(duration_max.count())};
673+
}
674+
670675
int GetRandInt(int nMax) noexcept
671676
{
672677
return GetRand(nMax);

src/random.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
#include <crypto/common.h>
1111
#include <uint256.h>
1212

13-
#include <stdint.h>
13+
#include <chrono> // For std::chrono::microseconds
14+
#include <cstdint>
1415
#include <limits>
1516

1617
/**
@@ -69,6 +70,7 @@
6970
*/
7071
void GetRandBytes(unsigned char* buf, int num) noexcept;
7172
uint64_t GetRand(uint64_t nMax) noexcept;
73+
std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept;
7274
int GetRandInt(int nMax) noexcept;
7375
uint256 GetRandHash() noexcept;
7476

0 commit comments

Comments
 (0)