1#[cfg(feature = "hotshot-testing")]
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::{collections::VecDeque, marker::PhantomData, sync::Arc};
10#[cfg(feature = "hotshot-testing")]
11use std::{path::Path, time::Duration};
12
13use async_trait::async_trait;
14use bincode::config::Options;
15use cdn_broker::reexports::{
16 connection::protocols::{Quic, Tcp},
17 def::{hook::NoMessageHook, ConnectionDef, RunDef, Topic as TopicTrait},
18 discovery::{Embedded, Redis},
19};
20#[cfg(feature = "hotshot-testing")]
21use cdn_broker::{Broker, Config as BrokerConfig};
22pub use cdn_client::reexports::crypto::signature::KeyPair;
23use cdn_client::{
24 reexports::{
25 crypto::signature::{Serializable, SignatureScheme},
26 message::{Broadcast, Direct, Message as PushCdnMessage},
27 },
28 Client, Config as ClientConfig,
29};
30#[cfg(feature = "hotshot-testing")]
31use cdn_marshal::{Config as MarshalConfig, Marshal};
32#[cfg(feature = "hotshot-testing")]
33use hotshot_types::traits::network::{
34 AsyncGenerator, NetworkReliability, TestableNetworkingImplementation,
35};
36use hotshot_types::{
37 boxed_sync,
38 data::ViewNumber,
39 traits::{
40 metrics::{Counter, Metrics, NoMetrics},
41 network::{BroadcastDelay, ConnectedNetwork, Topic as HotShotTopic},
42 signature_key::SignatureKey,
43 },
44 utils::bincode_opts,
45 BoxSyncFuture,
46};
47use num_enum::{IntoPrimitive, TryFromPrimitive};
48use parking_lot::Mutex;
49#[cfg(feature = "hotshot-testing")]
50use rand::{rngs::StdRng, RngCore, SeedableRng};
51use tokio::sync::mpsc::error::TrySendError;
52#[cfg(feature = "hotshot-testing")]
53use tokio::{spawn, time::sleep};
54#[cfg(feature = "hotshot-testing")]
55use tracing::error;
56
57use super::NetworkError;
58#[cfg(feature = "hotshot-testing")]
59use crate::NodeType;
60
61#[derive(Clone)]
63pub struct CdnMetricsValue {
64 pub num_failed_messages: Box<dyn Counter>,
66}
67
68impl CdnMetricsValue {
69 pub fn new(metrics: &dyn Metrics) -> Self {
71 let subgroup = metrics.subgroup("cdn".into());
73
74 Self {
76 num_failed_messages: subgroup.create_counter("num_failed_messages".into(), None),
77 }
78 }
79}
80
81impl Default for CdnMetricsValue {
82 fn default() -> Self {
84 Self::new(&*NoMetrics::boxed())
85 }
86}
87
88#[derive(Clone, Eq, PartialEq)]
91pub struct WrappedSignatureKey<T: SignatureKey + 'static>(pub T);
92impl<T: SignatureKey> SignatureScheme for WrappedSignatureKey<T> {
93 type PrivateKey = T::PrivateKey;
94 type PublicKey = Self;
95
96 fn sign(
98 private_key: &Self::PrivateKey,
99 namespace: &str,
100 message: &[u8],
101 ) -> anyhow::Result<Vec<u8>> {
102 let message = [namespace.as_bytes(), message].concat();
104
105 let signature = T::sign(private_key, &message)?;
106 Ok(bincode_opts().serialize(&signature)?)
107 }
108
109 fn verify(
111 public_key: &Self::PublicKey,
112 namespace: &str,
113 message: &[u8],
114 signature: &[u8],
115 ) -> bool {
116 let signature: T::PureAssembledSignatureType = match bincode_opts().deserialize(signature) {
118 Ok(key) => key,
119 Err(_) => return false,
120 };
121
122 let message = [namespace.as_bytes(), message].concat();
124
125 public_key.0.validate(&signature, &message)
126 }
127}
128
129impl<T: SignatureKey> Serializable for WrappedSignatureKey<T> {
132 fn serialize(&self) -> anyhow::Result<Vec<u8>> {
133 Ok(self.0.to_bytes())
134 }
135
136 fn deserialize(serialized: &[u8]) -> anyhow::Result<Self> {
137 Ok(WrappedSignatureKey(T::from_bytes(serialized)?))
138 }
139}
140
141pub struct ProductionDef<K: SignatureKey + 'static>(PhantomData<K>);
144impl<K: SignatureKey + 'static> RunDef for ProductionDef<K> {
145 type User = UserDef<K>;
146 type Broker = BrokerDef<K>;
147 type DiscoveryClientType = Redis;
148 type Topic = Topic;
149}
150
151pub struct UserDef<K: SignatureKey + 'static>(PhantomData<K>);
154impl<K: SignatureKey + 'static> ConnectionDef for UserDef<K> {
155 type Scheme = WrappedSignatureKey<K>;
156 type Protocol = Quic;
157 type MessageHook = NoMessageHook;
158}
159
160pub struct BrokerDef<K: SignatureKey + 'static>(PhantomData<K>);
163impl<K: SignatureKey> ConnectionDef for BrokerDef<K> {
164 type Scheme = WrappedSignatureKey<K>;
165 type Protocol = Tcp;
166 type MessageHook = NoMessageHook;
167}
168
169#[derive(Clone)]
173pub struct ClientDef<K: SignatureKey + 'static>(PhantomData<K>);
174impl<K: SignatureKey> ConnectionDef for ClientDef<K> {
175 type Scheme = WrappedSignatureKey<K>;
176 type Protocol = Quic;
177 type MessageHook = NoMessageHook;
178}
179
180pub struct TestingDef<K: SignatureKey + 'static>(PhantomData<K>);
183impl<K: SignatureKey + 'static> RunDef for TestingDef<K> {
184 type User = UserDef<K>;
185 type Broker = BrokerDef<K>;
186 type DiscoveryClientType = Embedded;
187 type Topic = Topic;
188}
189
190#[derive(Clone)]
193pub struct PushCdnNetwork<K: SignatureKey + 'static> {
195 client: Client<ClientDef<K>>,
197 metrics: Arc<CdnMetricsValue>,
199 internal_queue: Arc<Mutex<VecDeque<Vec<u8>>>>,
201 public_key: K,
203 #[cfg(feature = "hotshot-testing")]
205 is_paused: Arc<AtomicBool>,
206 }
209
210#[repr(u8)]
212#[derive(IntoPrimitive, TryFromPrimitive, Clone, PartialEq, Eq)]
213pub enum Topic {
214 Global = 0,
216 Da = 1,
218}
219
220impl TopicTrait for Topic {}
223
224impl<K: SignatureKey + 'static> PushCdnNetwork<K> {
225 pub fn new(
232 marshal_endpoint: String,
233 topics: Vec<Topic>,
234 keypair: KeyPair<WrappedSignatureKey<K>>,
235 metrics: CdnMetricsValue,
236 ) -> anyhow::Result<Self> {
237 let config = ClientConfig {
239 endpoint: marshal_endpoint,
240 subscribed_topics: topics.into_iter().map(|t| t as u8).collect(),
241 keypair: keypair.clone(),
242 use_local_authority: true,
243 };
244
245 let client = Client::new(config);
247
248 Ok(Self {
249 client,
250 metrics: Arc::from(metrics),
251 internal_queue: Arc::new(Mutex::new(VecDeque::new())),
252 public_key: keypair.public_key.0,
253 #[cfg(feature = "hotshot-testing")]
255 is_paused: Arc::from(AtomicBool::new(false)),
256 })
257 }
258
259 async fn broadcast_message(&self, message: Vec<u8>, topic: Topic) -> Result<(), NetworkError> {
265 #[cfg(feature = "hotshot-testing")]
267 if self.is_paused.load(Ordering::Relaxed) {
268 return Ok(());
269 }
270
271 if let Err(err) = self
273 .client
274 .send_broadcast_message(vec![topic as u8], message)
275 .await
276 {
277 return Err(NetworkError::MessageReceiveError(format!(
278 "failed to send broadcast message: {err}"
279 )));
280 };
281
282 Ok(())
283 }
284}
285
286#[cfg(feature = "hotshot-testing")]
287impl<TYPES: NodeType> TestableNetworkingImplementation<TYPES>
288 for PushCdnNetwork<TYPES::SignatureKey>
289{
290 #[allow(clippy::too_many_lines)]
293 fn generator(
294 _expected_node_count: usize,
295 _num_bootstrap: usize,
296 _network_id: usize,
297 da_committee_size: usize,
298 _reliability_config: Option<Box<dyn NetworkReliability>>,
299 _secondary_network_delay: Duration,
300 ) -> AsyncGenerator<Arc<Self>> {
301 let (broker_public_key, broker_private_key) =
305 TYPES::SignatureKey::generated_from_seed_indexed([0u8; 32], 1337);
306
307 let temp_dir = std::env::temp_dir();
309
310 let discovery_endpoint = temp_dir
312 .join(Path::new(&format!(
313 "test-{}.sqlite",
314 StdRng::from_entropy().next_u64()
315 )))
316 .to_string_lossy()
317 .into_owned();
318
319 let public_address_1 = format!(
321 "127.0.0.1:{}",
322 portpicker::pick_unused_port().expect("could not find an open port")
323 );
324 let public_address_2 = format!(
325 "127.0.0.1:{}",
326 portpicker::pick_unused_port().expect("could not find an open port")
327 );
328
329 for i in 0..2 {
331 let private_port = portpicker::pick_unused_port().expect("could not find an open port");
333
334 let private_address = format!("127.0.0.1:{private_port}");
336 let (public_address, other_public_address) = if i == 0 {
337 (public_address_1.clone(), public_address_2.clone())
338 } else {
339 (public_address_2.clone(), public_address_1.clone())
340 };
341
342 let broker_identifier = format!("{public_address}/{public_address}");
344 let other_broker_identifier = format!("{other_public_address}/{other_public_address}");
345
346 let config: BrokerConfig<TestingDef<TYPES::SignatureKey>> = BrokerConfig {
348 public_advertise_endpoint: public_address.clone(),
349 public_bind_endpoint: public_address,
350 private_advertise_endpoint: private_address.clone(),
351 private_bind_endpoint: private_address,
352 metrics_bind_endpoint: None,
353 keypair: KeyPair {
354 public_key: WrappedSignatureKey(broker_public_key.clone()),
355 private_key: broker_private_key.clone(),
356 },
357 discovery_endpoint: discovery_endpoint.clone(),
358
359 user_message_hook: NoMessageHook,
360 broker_message_hook: NoMessageHook,
361
362 ca_cert_path: None,
363 ca_key_path: None,
364 global_memory_pool_size: Some(1024 * 1024 * 1024),
366 };
367
368 spawn(async move {
370 let broker: Broker<TestingDef<TYPES::SignatureKey>> =
371 Broker::new(config).await.expect("broker failed to start");
372
373 if other_broker_identifier > broker_identifier {
376 sleep(Duration::from_secs(2)).await;
377 }
378
379 if let Err(err) = broker.start().await {
381 error!("broker stopped: {err}");
382 }
383 });
384 }
385
386 let marshal_port = portpicker::pick_unused_port().expect("could not find an open port");
388
389 let marshal_endpoint = format!("127.0.0.1:{marshal_port}");
391 let marshal_config = MarshalConfig {
392 bind_endpoint: marshal_endpoint.clone(),
393 discovery_endpoint,
394 metrics_bind_endpoint: None,
395 ca_cert_path: None,
396 ca_key_path: None,
397 global_memory_pool_size: Some(1024 * 1024 * 1024),
399 };
400
401 spawn(async move {
403 let marshal: Marshal<TestingDef<TYPES::SignatureKey>> = Marshal::new(marshal_config)
404 .await
405 .expect("failed to spawn marshal");
406
407 if let Err(err) = marshal.start().await {
409 error!("marshal stopped: {err}");
410 }
411 });
412
413 Box::pin({
415 move |node_id| {
416 let marshal_endpoint = marshal_endpoint.clone();
418
419 Box::pin(async move {
420 let private_key =
422 TYPES::SignatureKey::generated_from_seed_indexed([0u8; 32], node_id).1;
423 let public_key = TYPES::SignatureKey::from_private(&private_key);
424
425 let topics = if node_id < da_committee_size as u64 {
427 vec![Topic::Da as u8, Topic::Global as u8]
428 } else {
429 vec![Topic::Global as u8]
430 };
431
432 let client_config: ClientConfig<ClientDef<TYPES::SignatureKey>> =
434 ClientConfig {
435 keypair: KeyPair {
436 public_key: WrappedSignatureKey(public_key.clone()),
437 private_key,
438 },
439 subscribed_topics: topics,
440 endpoint: marshal_endpoint,
441 use_local_authority: true,
442 };
443
444 Arc::new(PushCdnNetwork {
446 client: Client::new(client_config),
447 metrics: Arc::new(CdnMetricsValue::default()),
448 internal_queue: Arc::new(Mutex::new(VecDeque::new())),
449 public_key,
450 #[cfg(feature = "hotshot-testing")]
451 is_paused: Arc::from(AtomicBool::new(false)),
452 })
453 })
454 }
455 })
456 }
457
458 fn in_flight_message_count(&self) -> Option<usize> {
460 None
461 }
462}
463
464#[async_trait]
465impl<K: SignatureKey + 'static> ConnectedNetwork<K> for PushCdnNetwork<K> {
466 fn pause(&self) {
468 #[cfg(feature = "hotshot-testing")]
469 self.is_paused.store(true, Ordering::Relaxed);
470 }
471
472 fn resume(&self) {
474 #[cfg(feature = "hotshot-testing")]
475 self.is_paused.store(false, Ordering::Relaxed);
476 }
477
478 async fn wait_for_ready(&self) {
480 let _ = self.client.ensure_initialized().await;
481 }
482
483 fn shut_down<'a, 'b>(&'a self) -> BoxSyncFuture<'b, ()>
485 where
486 'a: 'b,
487 Self: 'b,
488 {
489 boxed_sync(async move { self.client.close().await })
490 }
491
492 async fn broadcast_message(
498 &self,
499 message: Vec<u8>,
500 topic: HotShotTopic,
501 _broadcast_delay: BroadcastDelay,
502 ) -> Result<(), NetworkError> {
503 #[cfg(feature = "hotshot-testing")]
505 if self.is_paused.load(Ordering::Relaxed) {
506 return Ok(());
507 }
508 self.broadcast_message(message, topic.into())
509 .await
510 .inspect_err(|_e| {
511 self.metrics.num_failed_messages.add(1);
512 })
513 }
514
515 async fn da_broadcast_message(
521 &self,
522 message: Vec<u8>,
523 _recipients: Vec<K>,
524 _broadcast_delay: BroadcastDelay,
525 ) -> Result<(), NetworkError> {
526 #[cfg(feature = "hotshot-testing")]
528 if self.is_paused.load(Ordering::Relaxed) {
529 return Ok(());
530 }
531 self.broadcast_message(message, Topic::Da)
532 .await
533 .inspect_err(|_e| {
534 self.metrics.num_failed_messages.add(1);
535 })
536 }
537
538 async fn direct_message(&self, message: Vec<u8>, recipient: K) -> Result<(), NetworkError> {
543 if recipient == self.public_key {
545 self.internal_queue.lock().push_back(message);
546 return Ok(());
547 }
548
549 #[cfg(feature = "hotshot-testing")]
551 if self.is_paused.load(Ordering::Relaxed) {
552 return Ok(());
553 }
554
555 if let Err(e) = self
557 .client
558 .send_direct_message(&WrappedSignatureKey(recipient), message)
559 .await
560 {
561 self.metrics.num_failed_messages.add(1);
562 return Err(NetworkError::MessageSendError(format!(
563 "failed to send direct message: {e}"
564 )));
565 };
566
567 Ok(())
568 }
569
570 async fn recv_message(&self) -> Result<Vec<u8>, NetworkError> {
576 let queued_message = self.internal_queue.lock().pop_front();
578 if let Some(message) = queued_message {
579 return Ok(message);
580 }
581
582 let message = self.client.receive_message().await;
584
585 #[cfg(feature = "hotshot-testing")]
587 if self.is_paused.load(Ordering::Relaxed) {
588 sleep(Duration::from_millis(100)).await;
589 return Ok(vec![]);
590 }
591
592 let message = match message {
594 Ok(message) => message,
595 Err(error) => {
596 return Err(NetworkError::MessageReceiveError(format!(
597 "failed to receive message: {error}"
598 )));
599 },
600 };
601
602 let (PushCdnMessage::Broadcast(Broadcast { message, topics: _ })
604 | PushCdnMessage::Direct(Direct {
605 message,
606 recipient: _,
607 })) = message
608 else {
609 return Ok(vec![]);
610 };
611
612 Ok(message)
613 }
614
615 fn queue_node_lookup(
617 &self,
618 _view_number: ViewNumber,
619 _pk: K,
620 ) -> Result<(), TrySendError<Option<(ViewNumber, K)>>> {
621 Ok(())
622 }
623}
624
625impl From<HotShotTopic> for Topic {
626 fn from(topic: HotShotTopic) -> Self {
627 match topic {
628 HotShotTopic::Global => Topic::Global,
629 HotShotTopic::Da => Topic::Da,
630 }
631 }
632}