Skip to content

Commit 262e081

Browse files
author
Garand Tyson
committed
Target count as a config option (TX_FLOOD_TARGET_LEADERS, 0 = every validator); batch direct sends per peer
1 parent 4854597 commit 262e081

7 files changed

Lines changed: 188 additions & 13 deletions

File tree

‎docs/stellar-core_example.cfg‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,15 @@ EXPERIMENTAL_PARALLEL_TX_SET_DOWNLOAD = false
291291
# also enabled.
292292
BACKGROUND_TX_SIG_VERIFICATION = true
293293

294+
# TX_FLOOD_TARGET_LEADERS (integer) default 2
295+
# Experimental. How many upcoming round leaders get the transactions this
296+
# node accepts (the leader of the node's current round of the next ledger and
297+
# the ones after it). The node sends them the transactions directly instead of
298+
# advertising them to every peer. 0 = every validator of the leader schedule
299+
# (no adverts either, but every validator holds every transaction before the
300+
# leader's set arrives).
301+
TX_FLOOD_TARGET_LEADERS = 2
302+
294303
# NTP_DRIFT_CHECK_SERVER (string) default "pool.ntp.org"
295304
# Hostname of an NTP server that the node periodically queries (about every ten
296305
# minutes) to detect and warn about drift of the local clock. This is detection

‎overlay/src/libp2p_overlay.rs‎

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,15 @@ pub const NODE_ID_PROTOCOL: StreamProtocol = StreamProtocol::new("/stellar/node-
5656
const NODE_ID_BINDING_TAG: &[u8] = b"stellar-overlay-peer-id";
5757
const NODE_ID_FRAME_LEN: usize = 32 + 64;
5858

59+
/// Transaction bodies sent directly to a peer are collected for this long,
60+
/// so that a burst of submissions (a client or load generator step) becomes
61+
/// one write per peer instead of one per transaction.
62+
const DIRECT_SEND_BATCH_INTERVAL: Duration = Duration::from_millis(10);
63+
64+
/// A peer's queue of direct sends is written at once when it reaches this
65+
/// many transactions.
66+
const DIRECT_SEND_BATCH_MAX_TXS: usize = 256;
67+
5968
/// A peer's validator identity claim must arrive within this long of its
6069
/// stream opening.
6170
const NODE_ID_READ_TIMEOUT: Duration = Duration::from_secs(10);
@@ -599,6 +608,9 @@ struct SharedState {
599608
/// Validator identities: ours and unchecked claims. Never held across
600609
/// an await.
601610
identity: std::sync::Mutex<IdentityState>,
611+
/// Transaction bodies queued for a direct send, per peer (see
612+
/// DIRECT_SEND_BATCH_INTERVAL). Never held across an await.
613+
direct_out: std::sync::Mutex<HashMap<PeerId, Vec<Arc<ValidatedTx>>>>,
602614
/// Overlay metrics (shared with App for IPC reporting)
603615
metrics: Arc<OverlayMetrics>,
604616
}
@@ -639,6 +651,7 @@ impl SharedState {
639651
tx_buffer: RwLock::new(TxBuffer::new()),
640652
tx_router,
641653
identity: std::sync::Mutex::new(IdentityState::default()),
654+
direct_out: std::sync::Mutex::new(HashMap::new()),
642655
metrics,
643656
}
644657
}
@@ -820,6 +833,7 @@ impl StellarOverlay {
820833

821834
// Spawn INV/GETDATA housekeeping task
822835
tokio::spawn(inv_getdata_housekeeping_task(state.clone()));
836+
tokio::spawn(direct_send_flush_task(state.clone()));
823837

824838
loop {
825839
tokio::select! {
@@ -1937,14 +1951,52 @@ async fn execute_send_plan(state: &Arc<SharedState>, plan: SendPlan<PeerId>) {
19371951
state.tx_router.lock().unwrap().mark_unflooded(&hashes);
19381952
}
19391953
}
1940-
for (peer, txs) in direct {
1941-
// One task per peer: a slow target must not delay the other one,
1942-
// or the overlay's command loop.
1954+
// Queue the bodies per peer; `direct_send_flush_task` writes them a few
1955+
// milliseconds later, a full queue is written now.
1956+
let full: Vec<(PeerId, Vec<Arc<ValidatedTx>>)> = {
1957+
let mut out = state.direct_out.lock().unwrap();
1958+
let mut full = Vec::new();
1959+
for (peer, txs) in direct {
1960+
let queue = out.entry(peer).or_default();
1961+
queue.extend(txs);
1962+
if queue.len() >= DIRECT_SEND_BATCH_MAX_TXS {
1963+
full.push((peer, std::mem::take(queue)));
1964+
}
1965+
}
1966+
full
1967+
};
1968+
spawn_direct_sends(state, full);
1969+
}
1970+
1971+
/// One task per peer: a slow target must not delay another one, or the
1972+
/// caller.
1973+
fn spawn_direct_sends(state: &Arc<SharedState>, sends: Vec<(PeerId, Vec<Arc<ValidatedTx>>)>) {
1974+
for (peer, txs) in sends {
1975+
if txs.is_empty() {
1976+
continue;
1977+
}
19431978
let state = Arc::clone(state);
19441979
tokio::spawn(async move { send_tx_bodies(&state, peer, txs).await });
19451980
}
19461981
}
19471982

1983+
/// Writes the queued direct sends every DIRECT_SEND_BATCH_INTERVAL.
1984+
async fn direct_send_flush_task(state: Arc<SharedState>) {
1985+
let mut interval = tokio::time::interval(DIRECT_SEND_BATCH_INTERVAL);
1986+
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
1987+
loop {
1988+
interval.tick().await;
1989+
let queued: Vec<(PeerId, Vec<Arc<ValidatedTx>>)> = {
1990+
let mut out = state.direct_out.lock().unwrap();
1991+
if out.is_empty() {
1992+
continue;
1993+
}
1994+
out.drain().collect()
1995+
};
1996+
spawn_direct_sends(&state, queued);
1997+
}
1998+
}
1999+
19482000
/// Ask the router what is owed after the targets or the identified peers
19492001
/// changed, and send it.
19502002
async fn flush_local_txs(state: &Arc<SharedState>) {

‎src/herder/HerderImpl.cpp‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -419,8 +419,23 @@ HerderImpl::computeTxFloodTargets()
419419
// A node that has not started the slot (or does not run SCP at all, like
420420
// a watcher) is at round 0: the first round's leader comes first.
421421
uint64_t const round = std::max<uint64_t>(1, getSCP().getLeaderRound(slot));
422+
uint64_t const leaders = mApp.getConfig().TX_FLOOD_TARGET_LEADERS;
423+
if (leaders == 0)
424+
{
425+
// Every validator of the schedule, in an order that does not change
426+
// from slot to slot (the overlay is only told when the list
427+
// changes).
428+
std::vector<NodeID> everyone =
429+
mHerderSCPDriver.getLeaderSchedule(slot);
430+
if (everyone.empty())
431+
{
432+
return std::nullopt;
433+
}
434+
std::sort(everyone.begin(), everyone.end());
435+
return everyone;
436+
}
422437
std::vector<NodeID> targets;
423-
for (uint64_t r = round; r < round + TX_FLOOD_TARGET_ROUNDS; ++r)
438+
for (uint64_t r = round; r < round + leaders; ++r)
424439
{
425440
if (r > UINT32_MAX)
426441
{
@@ -432,10 +447,12 @@ HerderImpl::computeTxFloodTargets()
432447
{
433448
return std::nullopt;
434449
}
435-
if (std::find(targets.begin(), targets.end(), *leader) == targets.end())
450+
if (std::find(targets.begin(), targets.end(), *leader) != targets.end())
436451
{
437-
targets.emplace_back(*leader);
452+
// Once around the schedule: every validator is in.
453+
break;
438454
}
455+
targets.emplace_back(*leader);
439456
}
440457
if (targets.empty())
441458
{

‎src/herder/HerderImpl.h‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,6 @@ class HerderImpl : public Herder
6767

6868
void lostSync();
6969

70-
// How many consecutive round leaders get this node's transactions: the
71-
// leader of the current round, and the one that takes over if it fails.
72-
static constexpr uint32_t TX_FLOOD_TARGET_ROUNDS = 2;
7370
// A transaction accepted from a client blocks its source account on this
7471
// node for this long at most (the overlay stops sending it after the
7572
// same time, see LOCAL_TX_MAX_AGE in overlay/src/flood/tx_router.rs).

‎src/herder/test/TxFloodTargetsTests.cpp‎

Lines changed: 89 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ using namespace stellar::txtest;
3434
namespace
3535
{
3636
int const NUM_ACCOUNTS = 40;
37+
// Config::TX_FLOOD_TARGET_LEADERS's default.
38+
uint32_t const TARGET_LEADERS = 2;
3739

3840
Config
3941
acceleratedConfig(int configNum)
@@ -108,8 +110,7 @@ expectedTargets(Application::pointer const& app)
108110
std::max<uint32_t>(1, herder.getSCP().getLeaderRound(slot));
109111
auto& driver = herder.getHerderSCPDriver();
110112
std::vector<NodeID> res;
111-
for (uint32_t r = round; r < round + HerderImpl::TX_FLOOD_TARGET_ROUNDS;
112-
++r)
113+
for (uint32_t r = round; r < round + TARGET_LEADERS; ++r)
113114
{
114115
auto leader = driver.getRoundLeader(slot, r);
115116
REQUIRE(leader);
@@ -188,7 +189,7 @@ TEST_CASE("transactions go to the round leaders only",
188189
auto targets = herderOf(app).computeTxFloodTargets();
189190
REQUIRE(targets);
190191
REQUIRE(*targets == expectedTargets(app));
191-
REQUIRE(targets->size() == HerderImpl::TX_FLOOD_TARGET_ROUNDS);
192+
REQUIRE(targets->size() == TARGET_LEADERS);
192193
}
193194

194195
// Submit payments at every node over several ledgers, each from its own
@@ -255,12 +256,96 @@ TEST_CASE("transactions go to the round leaders only",
255256
REQUIRE(after.mDirectRecv > 0);
256257
REQUIRE(after.mDirectSent <=
257258
static_cast<int64_t>(submitted) *
258-
HerderImpl::TX_FLOOD_TARGET_ROUNDS * (ledgers + 1));
259+
TARGET_LEADERS * (ledgers + 1));
259260
// Far fewer than a flood, which delivers every transaction to the three
260261
// other nodes.
261262
REQUIRE(after.mDirectSent < 3 * static_cast<int64_t>(submitted) * 2);
262263
}
263264

265+
TEST_CASE("transactions go to every validator when no leader count is set",
266+
"[herder][tx-flood-targets][simulation]")
267+
{
268+
// TX_FLOOD_TARGET_LEADERS = 0: every validator is a target. Still no
269+
// adverts and no demands, and every transaction goes to each of the
270+
// three other nodes exactly once.
271+
auto simulation = Topologies::core(
272+
4, 0.75, sha256(getTestConfig().NETWORK_PASSPHRASE), [](int i) {
273+
auto cfg = acceleratedConfig(i);
274+
cfg.TX_FLOOD_TARGET_LEADERS = 0;
275+
return cfg;
276+
});
277+
simulation->startAllNodes();
278+
auto nodes = simulation->getNodes();
279+
simulation->crankUntil(
280+
[&]() {
281+
if (!allClosed(nodes, 4))
282+
{
283+
return false;
284+
}
285+
for (auto const& app : nodes)
286+
{
287+
if (identifiedPeers(app) != 3 ||
288+
!herderOf(app).getTxFloodTargetsForTesting())
289+
{
290+
return false;
291+
}
292+
}
293+
return true;
294+
},
295+
std::chrono::seconds(120), false);
296+
for (auto const& app : nodes)
297+
{
298+
auto targets = herderOf(app).computeTxFloodTargets();
299+
REQUIRE(targets);
300+
REQUIRE(targets->size() == 4);
301+
REQUIRE(std::is_sorted(targets->begin(), targets->end()));
302+
// The same list whatever the slot, so it was sent once.
303+
REQUIRE(herderOf(app).mTxFloodTargetHistoryForTesting.size() == 1);
304+
}
305+
306+
auto const appliedBefore = appliedTxs(nodes[0]);
307+
int submitted = 0;
308+
for (int batch = 0; batch < 5; ++batch)
309+
{
310+
for (size_t n = 0; n < nodes.size(); ++n)
311+
{
312+
auto source = getGenesisAccount(*nodes[n], submitted);
313+
auto dest = getGenesisAccount(*nodes[n], NUM_ACCOUNTS - 1);
314+
auto tx = source.tx({payment(dest.getPublicKey(), 1000)});
315+
REQUIRE(nodes[n]->getHerder().recvTransaction(tx, false) ==
316+
TxSubmitStatus::TX_STATUS_PENDING);
317+
++submitted;
318+
}
319+
auto const next =
320+
nodes[0]->getLedgerManager().getLastClosedLedgerNum() + 1;
321+
simulation->crankUntil([&]() { return allClosed(nodes, next); },
322+
std::chrono::seconds(60), false);
323+
}
324+
simulation->crankUntil(
325+
[&]() {
326+
for (auto const& app : nodes)
327+
{
328+
if (appliedTxs(app) - appliedBefore < submitted)
329+
{
330+
return false;
331+
}
332+
}
333+
return true;
334+
},
335+
std::chrono::seconds(120), false);
336+
auto const counts = countTxFlood(nodes);
337+
INFO(counts.toString());
338+
REQUIRE(counts.mAdvertised == 0);
339+
REQUIRE(counts.mDemanded == 0);
340+
REQUIRE(counts.mLocalFlooded == 0);
341+
REQUIRE(counts.mDirectSent == 3 * static_cast<int64_t>(submitted));
342+
REQUIRE(counts.mDirectRecv == counts.mDirectSent);
343+
for (auto const& app : nodes)
344+
{
345+
REQUIRE(appliedTxs(app) - appliedBefore == submitted);
346+
}
347+
}
348+
264349
TEST_CASE("transactions are included while a leader is down",
265350
"[herder][tx-flood-targets][simulation]")
266351
{

‎src/main/Config.cpp‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@ Config::Config() : NODE_SEED(SecretKey::random())
180180
DISABLE_TX_META_FOR_TESTING = false;
181181
BACKGROUND_TX_SIG_VERIFICATION = true;
182182
FORCE_OLD_STYLE_PREPARE_START_TRIGGER_TIMER = false;
183+
TX_FLOOD_TARGET_LEADERS = 2;
183184
NTP_DRIFT_CHECK_SERVER = "pool.ntp.org";
184185
BUCKETLIST_DB_INDEX_PAGE_SIZE_EXPONENT = 14; // 2^14 == 16 kb
185186
BUCKETLIST_DB_INDEX_CUTOFF = 20; // 20 mb
@@ -1239,6 +1240,10 @@ Config::processConfig(std::shared_ptr<cpptoml::table> t)
12391240
FORCE_OLD_STYLE_PREPARE_START_TRIGGER_TIMER =
12401241
readBool(item);
12411242
}},
1243+
{"TX_FLOOD_TARGET_LEADERS",
1244+
[&]() {
1245+
TX_FLOOD_TARGET_LEADERS = readInt<uint32_t>(item);
1246+
}},
12421247
{"NTP_DRIFT_CHECK_SERVER",
12431248
[&]() { NTP_DRIFT_CHECK_SERVER = readString(item); }},
12441249
{"ARTIFICIALLY_DELAY_LEDGER_CLOSE_FOR_TESTING",

‎src/main/Config.h‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,16 @@ class Config : public std::enable_shared_from_this<Config>
566566
// is an emergency fallback and defaults to false.
567567
bool FORCE_OLD_STYLE_PREPARE_START_TRIGGER_TIMER;
568568

569+
// How many upcoming round leaders get the transactions this node
570+
// accepts: the leader of the node's current round of the next slot and
571+
// the ones after it (see HerderImpl::computeTxFloodTargets). The node
572+
// sends them the transaction bodies directly instead of advertising them
573+
// to every peer. 0 means every validator of the leader schedule: no
574+
// adverts either, but every validator holds every transaction before
575+
// the leader's set arrives (and can verify its signatures in the
576+
// background). Experimental; defaults to 2.
577+
uint32_t TX_FLOOD_TARGET_LEADERS;
578+
569579
// Hostname of an NTP server to periodically query in order to detect drift
570580
// of this node's local clock. This is detection only: core never adjusts
571581
// the system clock. Defaults to a pool.ntp.org; set to the empty string to

0 commit comments

Comments
 (0)