1use std::collections::BTreeSet;
5use std::sync::Arc;
6use std::time::Duration;
7
8use parking_lot::Mutex;
9
10use fastcrypto::groups::bls12381;
11use fastcrypto_tbls::{tbls::ThresholdBls, types::ThresholdBls12381MinSig};
12use mysten_common::debug_fatal_no_invariant;
13use mysten_common::fatal;
14use mysten_metrics::spawn_monitored_task;
15use serde::{Deserialize, Serialize};
16use sui_macros::fail_point_async;
17use sui_types::committee::EpochId;
18use sui_types::crypto::RandomnessRound;
19use sui_types::crypto::RandomnessSignature;
20use sui_types::effects::TransactionEffectsAPI;
21use sui_types::executable_transaction::VerifiedExecutableTransaction;
22use sui_types::execution_status::ExecutionStatus;
23use sui_types::transaction::{TransactionKey, VerifiedTransaction};
24use tokio::sync::{broadcast, mpsc, watch};
25use tokio::task::JoinHandle;
26use tracing::{debug, info, instrument, warn};
27
28use crate::authority::AuthorityState;
29
30#[derive(Debug, Serialize, Deserialize, Clone)]
32pub struct RandomnessSignatureMessage {
33 pub epoch: EpochId,
34 pub round: RandomnessRound,
35 pub signature_bytes: Vec<u8>,
36}
37
38const SIGNATURES_BROADCAST_CAPACITY: usize = 1000;
39const CONSENSUS_SIGNATURES_CHANNEL_SIZE: usize = 1000;
40const EXECUTED_ROUNDS_CACHE_CAPACITY: usize = 1000;
41
42pub struct RandomnessRoundReceiverHandle {
43 consensus_signatures_tx: mysten_metrics::monitored_mpsc::Sender<bytes::Bytes>,
44 vss_pk_tx: watch::Sender<Option<bls12381::G2Element>>,
45 signatures_broadcast: broadcast::Sender<bytes::Bytes>,
46 #[cfg(test)]
47 executed_consensus_rounds: Arc<Mutex<BTreeSet<(EpochId, RandomnessRound)>>>,
48 _task_handle: JoinHandle<()>,
49}
50
51impl RandomnessRoundReceiverHandle {
52 pub fn set_public_key(&self, vss_pk: bls12381::G2Element) {
55 self.vss_pk_tx.send(Some(vss_pk)).ok();
56 }
57
58 pub fn clear_public_key(&self) {
62 self.vss_pk_tx.send(None).ok();
63 }
64}
65
66impl RandomnessRoundReceiverHandle {
67 pub fn new_for_testing() -> Arc<Self> {
68 let (consensus_signatures_tx, _) =
69 mysten_metrics::monitored_mpsc::channel("test_auxiliary", 1);
70 let (vss_pk_tx, vss_pk_rx) = watch::channel(None);
71 let (signatures_broadcast, _) = broadcast::channel(1);
72 Arc::new(Self {
73 consensus_signatures_tx,
74 vss_pk_tx,
75 signatures_broadcast,
76 #[cfg(test)]
77 executed_consensus_rounds: Arc::new(Mutex::new(BTreeSet::new())),
78 _task_handle: tokio::spawn(async move {
79 let _vss_pk_rx = vss_pk_rx;
80 futures::future::pending::<()>().await;
81 }),
82 })
83 }
84
85 #[cfg(test)]
86 pub(crate) fn public_key_for_testing(&self) -> Option<bls12381::G2Element> {
87 let rx = self.vss_pk_tx.subscribe();
88 *rx.borrow()
89 }
90
91 #[cfg(test)]
92 pub(crate) fn mark_round_executed(&self, epoch: EpochId, round: RandomnessRound) {
93 self.executed_consensus_rounds.lock().insert((epoch, round));
94 }
95}
96
97impl consensus_core::RandomnessSignatureHandler for RandomnessRoundReceiverHandle {
98 fn handle_randomness_signature(&self, data: bytes::Bytes) {
99 if let Err(e) = self.consensus_signatures_tx.try_send(data) {
100 warn!(
101 "RandomnessRoundReceiverHandle: failed to forward randomness round signature: {e}"
102 );
103 }
104 }
105
106 fn subscribe_randomness_signatures(&self) -> broadcast::Receiver<bytes::Bytes> {
107 self.signatures_broadcast.subscribe()
108 }
109}
110
111pub struct RandomnessRoundReceiver {
112 authority_state: Arc<AuthorityState>,
113 randomness_rx: mpsc::Receiver<(EpochId, RandomnessRound, Vec<u8>)>,
114 consensus_signatures_rx: mysten_metrics::monitored_mpsc::Receiver<bytes::Bytes>,
115 vss_pk_rx: watch::Receiver<Option<bls12381::G2Element>>,
116 signatures_broadcast: broadcast::Sender<bytes::Bytes>,
120 executed_consensus_rounds: Arc<Mutex<BTreeSet<(EpochId, RandomnessRound)>>>,
124}
125
126impl RandomnessRoundReceiver {
127 pub fn spawn(
129 authority_state: Arc<AuthorityState>,
130 randomness_rx: mpsc::Receiver<(EpochId, RandomnessRound, Vec<u8>)>,
131 ) -> Arc<RandomnessRoundReceiverHandle> {
132 let (signatures_broadcast, _) =
133 broadcast::channel::<bytes::Bytes>(SIGNATURES_BROADCAST_CAPACITY);
134
135 let (consensus_signatures_tx, consensus_signatures_rx) =
136 mysten_metrics::monitored_mpsc::channel(
137 "consensus_randomness_round_signatures",
138 CONSENSUS_SIGNATURES_CHANNEL_SIZE,
139 );
140 let (vss_pk_tx, vss_pk_rx) = watch::channel(None);
141 let executed_consensus_rounds = Arc::new(Mutex::new(BTreeSet::new()));
142
143 let rrr = RandomnessRoundReceiver {
144 authority_state,
145 randomness_rx,
146 consensus_signatures_rx,
147 vss_pk_rx,
148 signatures_broadcast: signatures_broadcast.clone(),
149 executed_consensus_rounds: executed_consensus_rounds.clone(),
150 };
151 let task_handle = spawn_monitored_task!(rrr.run());
152
153 Arc::new(RandomnessRoundReceiverHandle {
154 consensus_signatures_tx,
155 vss_pk_tx,
156 signatures_broadcast,
157 #[cfg(test)]
158 executed_consensus_rounds,
159 _task_handle: task_handle,
160 })
161 }
162
163 async fn run(mut self) {
164 info!("RandomnessRoundReceiver event loop started");
165
166 loop {
167 let vss_pk = *self.vss_pk_rx.borrow_and_update();
168 tokio::select! {
169 maybe_recv = self.randomness_rx.recv() => {
170 if let Some((epoch, round, bytes)) = maybe_recv {
171 self.handle_new_randomness(epoch, round, bytes).await;
172 } else {
173 break;
174 }
175 },
176 Some(data) = self.consensus_signatures_rx.recv(), if vss_pk.is_some() => {
177 self.handle_consensus_randomness_signature(vss_pk.unwrap(), &data).await;
178 },
179 _ = self.vss_pk_rx.changed() => {},
181 }
182 }
183
184 info!("RandomnessRoundReceiver event loop ended");
185 }
186
187 async fn handle_consensus_randomness_signature(
190 &mut self,
191 vss_pk: bls12381::G2Element,
192 data: &bytes::Bytes,
193 ) {
194 let msg: RandomnessSignatureMessage = match bcs::from_bytes(data) {
195 Ok(msg) => msg,
196 Err(e) => {
197 warn!("RandomnessRoundReceiver: failed to deserialize round signature: {e}");
198 return;
199 }
200 };
201
202 let sig: RandomnessSignature = match bcs::from_bytes(&msg.signature_bytes) {
203 Ok(sig) => sig,
204 Err(e) => {
205 warn!(
206 "RandomnessRoundReceiver: failed to deserialize signature \
207 for epoch {} round {}: {e}",
208 msg.epoch, msg.round
209 );
210 return;
211 }
212 };
213
214 if let Err(e) =
215 ThresholdBls12381MinSig::verify(&vss_pk, &msg.round.signature_message(), &sig)
216 {
217 warn!(
218 "RandomnessRoundReceiver: invalid auxiliary signature \
219 for epoch {} round {}: {e}",
220 msg.epoch, msg.round
221 );
222 return;
223 }
224
225 if self
226 .executed_consensus_rounds
227 .lock()
228 .contains(&(msg.epoch, msg.round))
229 {
230 info!(
231 "RandomnessRoundReceiver: dropping already-executed auxiliary signature for epoch {} round {}",
232 msg.epoch, msg.round
233 );
234 return;
235 }
236
237 debug!(
238 "RandomnessRoundReceiver: verified auxiliary signature for epoch {} round {}",
239 msg.epoch, msg.round
240 );
241
242 self.handle_new_randomness(msg.epoch, msg.round, msg.signature_bytes)
243 .await;
244 }
245
246 #[instrument(level = "debug", skip_all, fields(?epoch, ?round))]
247 async fn handle_new_randomness(&self, epoch: EpochId, round: RandomnessRound, bytes: Vec<u8>) {
248 fail_point_async!("randomness-delay");
249
250 let epoch_store = self.authority_state.load_epoch_store_one_call_per_task();
251 if epoch_store.epoch() != epoch {
252 warn!(
253 "dropping randomness for epoch {epoch}, round {round}, because we are in epoch {}",
254 epoch_store.epoch()
255 );
256 return;
257 }
258 let msg = RandomnessSignatureMessage {
261 epoch,
262 round,
263 signature_bytes: bytes.clone(),
264 };
265 match bcs::to_bytes(&msg) {
266 Ok(encoded) => {
267 let _ = self.signatures_broadcast.send(bytes::Bytes::from(encoded));
268 }
269 Err(err) => {
270 warn!("serialisation of RandomnessSignatureMessage failed: {err}");
271 }
272 }
273
274 let key = TransactionKey::RandomnessRound(epoch, round);
275 let transaction = VerifiedTransaction::new_randomness_state_update(
276 epoch,
277 round,
278 bytes,
279 epoch_store
280 .epoch_start_config()
281 .randomness_obj_initial_shared_version()
282 .expect("randomness state obj must exist"),
283 );
284 debug!(
285 "created randomness state update transaction with digest: {:?}",
286 transaction.digest()
287 );
288 let transaction = VerifiedExecutableTransaction::new_system(transaction, epoch);
289 let digest = *transaction.digest();
290
291 self.authority_state
296 .get_cache_commit()
297 .persist_transaction(&transaction);
298
299 epoch_store.insert_tx_key(key, digest);
301
302 let authority_state = self.authority_state.clone();
303 let executed_consensus_rounds = self.executed_consensus_rounds.clone();
304 spawn_monitored_task!(async move {
305 const RANDOMNESS_STATE_UPDATE_EXECUTION_TIMEOUT: Duration = Duration::from_secs(300);
312 let result = tokio::time::timeout(
313 RANDOMNESS_STATE_UPDATE_EXECUTION_TIMEOUT,
314 authority_state
315 .get_transaction_cache_reader()
316 .notify_read_executed_effects(
317 "RandomnessRoundReceiver::notify_read_executed_effects_first",
318 &[digest],
319 ),
320 )
321 .await;
322 let mut effects = match result {
323 Ok(result) => result,
324 Err(_) => {
325 debug_fatal_no_invariant!(
327 "randomness state update transaction execution timed out at epoch {epoch}, round {round}"
328 );
329 authority_state
331 .get_transaction_cache_reader()
332 .notify_read_executed_effects(
333 "RandomnessRoundReceiver::notify_read_executed_effects_second",
334 &[digest],
335 )
336 .await
337 }
338 };
339
340 let effects = effects.pop().expect("should return effects");
341 if *effects.status() != ExecutionStatus::Success {
342 fatal!(
343 "failed to execute randomness state update transaction at epoch {epoch}, round {round}: {effects:?}"
344 );
345 }
346 debug!(
347 "successfully executed randomness state update transaction at epoch {epoch}, round {round}"
348 );
349
350 let cache = &mut *executed_consensus_rounds.lock();
351 cache.insert((epoch, round));
352 while cache.len() > EXECUTED_ROUNDS_CACHE_CAPACITY {
353 cache.pop_first();
354 }
355 });
356 }
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362 use crate::authority::test_authority_builder::TestAuthorityBuilder;
363 use consensus_core::RandomnessSignatureHandler;
364 use fastcrypto::groups::{GroupElement, HashToGroupElement, bls12381};
365
366 fn generate_keypair() -> (bls12381::Scalar, bls12381::G2Element) {
367 let sk = bls12381::Scalar::generator();
368 let pk = bls12381::G2Element::generator() * sk;
369 (sk, pk)
370 }
371
372 fn sign(sk: &bls12381::Scalar, msg: &[u8]) -> RandomnessSignature {
373 bls12381::G1Element::hash_to_group_element(msg) * sk
374 }
375
376 fn build_message(
377 epoch: EpochId,
378 round: RandomnessRound,
379 sig: &RandomnessSignature,
380 ) -> bytes::Bytes {
381 let msg = RandomnessSignatureMessage {
382 epoch,
383 round,
384 signature_bytes: bcs::to_bytes(sig).unwrap(),
385 };
386 bytes::Bytes::from(bcs::to_bytes(&msg).unwrap())
387 }
388
389 #[tokio::test]
390 async fn test_invalid_signature_not_broadcast() {
391 let (_sk, pk) = generate_keypair();
392 let state = TestAuthorityBuilder::new().build().await;
393 let epoch = state.epoch_store_for_testing().epoch();
394
395 let (_randomness_tx, randomness_rx) = mpsc::channel(1);
396 let handle = RandomnessRoundReceiver::spawn(state, randomness_rx);
397 let mut sig_rx = handle.subscribe_randomness_signatures();
398
399 handle.set_public_key(pk);
400 tokio::task::yield_now().await;
401
402 let wrong_sk = bls12381::Scalar::generator() + bls12381::Scalar::generator();
403 let round = RandomnessRound(1);
404 let bad_sig = sign(&wrong_sk, &round.signature_message());
405 handle.handle_randomness_signature(build_message(epoch, round, &bad_sig));
406
407 let result =
408 tokio::time::timeout(std::time::Duration::from_millis(200), sig_rx.recv()).await;
409 assert!(result.is_err(), "should have timed out (no broadcast)");
410 }
411
412 #[tokio::test]
413 async fn test_malformed_data_not_broadcast() {
414 let (_sk, pk) = generate_keypair();
415 let state = TestAuthorityBuilder::new().build().await;
416
417 let (_randomness_tx, randomness_rx) = mpsc::channel(1);
418 let handle = RandomnessRoundReceiver::spawn(state, randomness_rx);
419 let mut sig_rx = handle.subscribe_randomness_signatures();
420
421 handle.set_public_key(pk);
422 tokio::task::yield_now().await;
423
424 handle.handle_randomness_signature(bytes::Bytes::from(vec![0u8; 32]));
425
426 let result =
427 tokio::time::timeout(std::time::Duration::from_millis(200), sig_rx.recv()).await;
428 assert!(result.is_err(), "should have timed out (no broadcast)");
429 }
430
431 #[tokio::test]
432 async fn test_signatures_buffer_until_dkg_completes() {
433 let (sk, pk) = generate_keypair();
434 let state = TestAuthorityBuilder::new().build().await;
435 let epoch = state.epoch_store_for_testing().epoch();
436
437 let (_randomness_tx, randomness_rx) = mpsc::channel(1);
438 let handle = RandomnessRoundReceiver::spawn(state, randomness_rx);
439 let mut sig_rx = handle.subscribe_randomness_signatures();
440
441 let round = RandomnessRound(1);
443 let sig = sign(&sk, &round.signature_message());
444 handle.handle_randomness_signature(build_message(epoch, round, &sig));
445
446 let result =
447 tokio::time::timeout(std::time::Duration::from_millis(200), sig_rx.recv()).await;
448 assert!(result.is_err(), "should have timed out (DKG not complete)");
449
450 handle.set_public_key(pk);
452
453 let received = tokio::time::timeout(std::time::Duration::from_secs(5), sig_rx.recv())
454 .await
455 .expect("timed out")
456 .expect("channel closed");
457
458 let decoded: RandomnessSignatureMessage = bcs::from_bytes(&received).unwrap();
459 assert_eq!(decoded.epoch, epoch);
460 assert_eq!(decoded.round, round);
461 }
462
463 #[tokio::test]
464 async fn test_executed_consensus_signature_not_rebroadcast() {
465 let (sk, pk) = generate_keypair();
466 let state = TestAuthorityBuilder::new().build().await;
467 let epoch = state.epoch_store_for_testing().epoch();
468
469 let (_randomness_tx, randomness_rx) = mpsc::channel(1);
470 let handle = RandomnessRoundReceiver::spawn(state, randomness_rx);
471 let mut sig_rx = handle.subscribe_randomness_signatures();
472
473 handle.set_public_key(pk);
474 tokio::task::yield_now().await;
475
476 let round = RandomnessRound(1);
477 let sig = sign(&sk, &round.signature_message());
478 let msg = build_message(epoch, round, &sig);
479
480 handle.mark_round_executed(epoch, round);
482
483 handle.handle_randomness_signature(msg);
484
485 let result =
486 tokio::time::timeout(std::time::Duration::from_millis(200), sig_rx.recv()).await;
487 assert!(
488 result.is_err(),
489 "already-executed round should not be rebroadcast"
490 );
491 }
492
493 #[tokio::test]
494 async fn test_clear_public_key_pauses_processing() {
495 let (sk, pk) = generate_keypair();
496 let state = TestAuthorityBuilder::new().build().await;
497 let epoch = state.epoch_store_for_testing().epoch();
498
499 let (_randomness_tx, randomness_rx) = mpsc::channel(1);
500 let handle = RandomnessRoundReceiver::spawn(state, randomness_rx);
501 let mut sig_rx = handle.subscribe_randomness_signatures();
502
503 handle.set_public_key(pk);
505 tokio::task::yield_now().await;
506
507 let round1 = RandomnessRound(1);
508 let sig1 = sign(&sk, &round1.signature_message());
509 handle.handle_randomness_signature(build_message(epoch, round1, &sig1));
510
511 tokio::time::timeout(std::time::Duration::from_secs(5), sig_rx.recv())
512 .await
513 .expect("timed out")
514 .expect("channel closed");
515
516 handle.clear_public_key();
518 for _ in 0..5 {
520 tokio::task::yield_now().await;
521 }
522
523 let round2 = RandomnessRound(2);
524 let sig2 = sign(&sk, &round2.signature_message());
525 handle.handle_randomness_signature(build_message(epoch, round2, &sig2));
526
527 let result =
528 tokio::time::timeout(std::time::Duration::from_millis(200), sig_rx.recv()).await;
529 assert!(result.is_err(), "should have timed out (key cleared)");
530
531 handle.set_public_key(pk);
533
534 let received = tokio::time::timeout(std::time::Duration::from_secs(5), sig_rx.recv())
535 .await
536 .expect("timed out")
537 .expect("channel closed");
538
539 let decoded: RandomnessSignatureMessage = bcs::from_bytes(&received).unwrap();
540 assert_eq!(decoded.round, round2);
541 }
542}