Skip to content

Commit d96b731

Browse files
authored
Fix for #6296: Deterministic RNG in peer DAS publish block tests (#7192)
#6296: Deterministic RNG in peer DAS publish block tests Made test functions to call publish-block APIs with true for the deterministic RNG boolean parameter while production code with false. This will deterministically shuffle columns for unit tests under broadcast_validation_tests.rs.
1 parent 759b061 commit d96b731

File tree

9 files changed

+36
-5
lines changed

9 files changed

+36
-5
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

beacon_node/beacon_chain/src/beacon_chain.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ use operation_pool::{
9292
};
9393
use parking_lot::{Mutex, RwLock, RwLockWriteGuard};
9494
use proto_array::{DoNotReOrg, ProposerHeadError};
95+
use rand::RngCore;
9596
use safe_arith::SafeArith;
9697
use slasher::Slasher;
9798
use slot_clock::SlotClock;
@@ -491,6 +492,8 @@ pub struct BeaconChain<T: BeaconChainTypes> {
491492
pub data_availability_checker: Arc<DataAvailabilityChecker<T>>,
492493
/// The KZG trusted setup used by this chain.
493494
pub kzg: Arc<Kzg>,
495+
/// RNG instance used by the chain. Currently used for shuffling column sidecars in block publishing.
496+
pub rng: Arc<Mutex<Box<dyn RngCore + Send>>>,
494497
}
495498

496499
pub enum BeaconBlockResponseWrapper<E: EthSpec> {

beacon_node/beacon_chain/src/builder.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ use logging::crit;
3030
use operation_pool::{OperationPool, PersistedOperationPool};
3131
use parking_lot::{Mutex, RwLock};
3232
use proto_array::{DisallowedReOrgOffsets, ReOrgThreshold};
33+
use rand::RngCore;
3334
use rayon::prelude::*;
3435
use slasher::Slasher;
3536
use slot_clock::{SlotClock, TestingSlotClock};
@@ -105,6 +106,7 @@ pub struct BeaconChainBuilder<T: BeaconChainTypes> {
105106
task_executor: Option<TaskExecutor>,
106107
validator_monitor_config: Option<ValidatorMonitorConfig>,
107108
import_all_data_columns: bool,
109+
rng: Option<Box<dyn RngCore + Send>>,
108110
}
109111

110112
impl<TSlotClock, TEth1Backend, E, THotStore, TColdStore>
@@ -145,6 +147,7 @@ where
145147
task_executor: None,
146148
validator_monitor_config: None,
147149
import_all_data_columns: false,
150+
rng: None,
148151
}
149152
}
150153

@@ -691,6 +694,14 @@ where
691694
self
692695
}
693696

697+
/// Sets the `rng` field.
698+
///
699+
/// Currently used for shuffling column sidecars in block publishing.
700+
pub fn rng(mut self, rng: Box<dyn RngCore + Send>) -> Self {
701+
self.rng = Some(rng);
702+
self
703+
}
704+
694705
/// Consumes `self`, returning a `BeaconChain` if all required parameters have been supplied.
695706
///
696707
/// An error will be returned at runtime if all required parameters have not been configured.
@@ -716,6 +727,7 @@ where
716727
.genesis_state_root
717728
.ok_or("Cannot build without a genesis state root")?;
718729
let validator_monitor_config = self.validator_monitor_config.unwrap_or_default();
730+
let rng = self.rng.ok_or("Cannot build without an RNG")?;
719731
let beacon_proposer_cache: Arc<Mutex<BeaconProposerCache>> = <_>::default();
720732

721733
let mut validator_monitor =
@@ -979,6 +991,7 @@ where
979991
.map_err(|e| format!("Error initializing DataAvailabilityChecker: {:?}", e))?,
980992
),
981993
kzg: self.kzg.clone(),
994+
rng: Arc::new(Mutex::new(rng)),
982995
};
983996

984997
let head = beacon_chain.head_snapshot();
@@ -1184,6 +1197,8 @@ mod test {
11841197
use genesis::{
11851198
generate_deterministic_keypairs, interop_genesis_state, DEFAULT_ETH1_BLOCK_HASH,
11861199
};
1200+
use rand::rngs::StdRng;
1201+
use rand::SeedableRng;
11871202
use ssz::Encode;
11881203
use std::time::Duration;
11891204
use store::config::StoreConfig;
@@ -1230,6 +1245,7 @@ mod test {
12301245
.testing_slot_clock(Duration::from_secs(1))
12311246
.expect("should configure testing slot clock")
12321247
.shutdown_sender(shutdown_tx)
1248+
.rng(Box::new(StdRng::seed_from_u64(42)))
12331249
.build()
12341250
.expect("should build");
12351251

beacon_node/beacon_chain/src/test_utils.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,7 @@ use kzg::{Kzg, TrustedSetup};
3838
use logging::create_test_tracing_subscriber;
3939
use merkle_proof::MerkleTree;
4040
use operation_pool::ReceivedPreCapella;
41-
use parking_lot::Mutex;
42-
use parking_lot::RwLockWriteGuard;
41+
use parking_lot::{Mutex, RwLockWriteGuard};
4342
use rand::rngs::StdRng;
4443
use rand::Rng;
4544
use rand::SeedableRng;
@@ -588,7 +587,8 @@ where
588587
.chain_config(chain_config)
589588
.import_all_data_columns(self.import_all_data_columns)
590589
.event_handler(Some(ServerSentEventHandler::new_with_capacity(5)))
591-
.validator_monitor_config(validator_monitor_config);
590+
.validator_monitor_config(validator_monitor_config)
591+
.rng(Box::new(StdRng::seed_from_u64(42)));
592592

593593
builder = if let Some(mutator) = self.initial_mutator {
594594
mutator(builder)

beacon_node/beacon_chain/tests/store_tests.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use beacon_chain::{
1616
};
1717
use logging::create_test_tracing_subscriber;
1818
use maplit::hashset;
19+
use rand::rngs::StdRng;
1920
use rand::Rng;
2021
use slot_clock::{SlotClock, TestingSlotClock};
2122
use state_processing::{state_advance::complete_state_advance, BlockReplayer};
@@ -2373,6 +2374,7 @@ async fn weak_subjectivity_sync_test(slots: Vec<Slot>, checkpoint_slot: Slot) {
23732374
.chain_config(ChainConfig::default())
23742375
.event_handler(Some(ServerSentEventHandler::new_with_capacity(1)))
23752376
.execution_layer(Some(mock.el))
2377+
.rng(Box::new(StdRng::seed_from_u64(42)))
23762378
.build()
23772379
.expect("should build");
23782380

beacon_node/client/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ logging = { workspace = true }
3131
metrics = { workspace = true }
3232
monitoring_api = { workspace = true }
3333
network = { workspace = true }
34+
rand = { workspace = true }
3435
sensitive_url = { workspace = true }
3536
serde = { workspace = true }
3637
serde_json = { workspace = true }

beacon_node/client/src/builder.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ use genesis::{interop_genesis_state, Eth1GenesisService, DEFAULT_ETH1_BLOCK_HASH
3333
use lighthouse_network::{prometheus_client::registry::Registry, NetworkGlobals};
3434
use monitoring_api::{MonitoringHttpClient, ProcessType};
3535
use network::{NetworkConfig, NetworkSenders, NetworkService};
36+
use rand::rngs::{OsRng, StdRng};
37+
use rand::SeedableRng;
3638
use slasher::Slasher;
3739
use slasher_service::SlasherService;
3840
use std::net::TcpListener;
@@ -210,7 +212,10 @@ where
210212
.event_handler(event_handler)
211213
.execution_layer(execution_layer)
212214
.import_all_data_columns(config.network.subscribe_all_data_column_subnets)
213-
.validator_monitor_config(config.validator_monitor.clone());
215+
.validator_monitor_config(config.validator_monitor.clone())
216+
.rng(Box::new(
217+
StdRng::from_rng(OsRng).map_err(|e| format!("Failed to create RNG: {:?}", e))?,
218+
));
214219

215220
let builder = if let Some(slasher) = self.slasher.clone() {
216221
builder.slasher(slasher)

beacon_node/http_api/src/publish_blocks.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -521,7 +521,7 @@ fn publish_column_sidecars<T: BeaconChainTypes>(
521521
.len()
522522
.saturating_sub(malicious_withhold_count);
523523
// Randomize columns before dropping the last malicious_withhold_count items
524-
data_column_sidecars.shuffle(&mut rand::thread_rng());
524+
data_column_sidecars.shuffle(&mut **chain.rng.lock());
525525
data_column_sidecars.truncate(columns_to_keep);
526526
}
527527
let pubsub_messages = data_column_sidecars

beacon_node/network/src/subnet_service/tests/mod.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ use beacon_chain::{
77
};
88
use genesis::{generate_deterministic_keypairs, interop_genesis_state, DEFAULT_ETH1_BLOCK_HASH};
99
use lighthouse_network::NetworkConfig;
10+
use rand::rngs::StdRng;
11+
use rand::SeedableRng;
1012
use slot_clock::{SlotClock, SystemTimeSlotClock};
1113
use std::sync::{Arc, LazyLock};
1214
use std::time::{Duration, SystemTime};
@@ -76,6 +78,7 @@ impl TestBeaconChain {
7678
Duration::from_millis(SLOT_DURATION_MILLIS),
7779
))
7880
.shutdown_sender(shutdown_tx)
81+
.rng(Box::new(StdRng::seed_from_u64(42)))
7982
.build()
8083
.expect("should build"),
8184
);

0 commit comments

Comments
 (0)