1#![allow(unused_assignments)]
10use std::{fmt::Debug, future::Future, num::NonZeroUsize, pin::Pin, time::Duration};
11
12use alloy::primitives::U256;
13use bincode::Options;
14use displaydoc::Display;
15use stake_table::HSStakeTable;
16use tracing::error;
17use traits::{
18 node_implementation::NodeType,
19 signature_key::{SignatureKey, StateSignatureKey},
20};
21use url::Url;
22use vbs::version::Version;
23use vec1::Vec1;
24
25use crate::utils::bincode_opts;
26pub mod bundle;
27pub mod consensus;
28pub mod constants;
29pub mod data;
30pub mod drb;
32pub mod epoch_membership;
34pub mod error;
35pub mod event;
36pub mod hotshot_config_file;
38pub mod light_client;
39pub mod message;
40
41pub mod network;
43pub mod qc;
44pub mod request_response;
45pub mod signature_key;
46pub mod simple_certificate;
47pub mod simple_vote;
48pub mod stake_table;
49pub mod traits;
50
51pub mod storage_metrics;
52pub mod upgrade_config;
54pub mod utils;
55pub mod vid;
56pub mod vote;
57
58pub type BoxSyncFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + Sync + 'a>>;
60
61pub fn assert_future<T, F>(future: F) -> F
63where
64 F: Future<Output = T>,
65{
66 future
67}
68pub fn boxed_sync<'a, F>(fut: F) -> BoxSyncFuture<'a, F::Output>
70where
71 F: Future + Sized + Send + Sync + 'a,
72{
73 assert_future::<F::Output, _>(Box::pin(fut))
74}
75
76#[derive(Clone, Debug, Display)]
77pub struct ValidatorConfig<TYPES: NodeType> {
79 pub public_key: TYPES::SignatureKey,
81 pub private_key: <TYPES::SignatureKey as SignatureKey>::PrivateKey,
83 pub stake_value: U256,
85 pub state_public_key: TYPES::StateSignatureKey,
87 pub state_private_key: <TYPES::StateSignatureKey as StateSignatureKey>::StatePrivateKey,
89 pub is_da: bool,
91}
92
93impl<TYPES: NodeType> ValidatorConfig<TYPES> {
94 #[must_use]
96 pub fn generated_from_seed_indexed(
97 seed: [u8; 32],
98 index: u64,
99 stake_value: U256,
100 is_da: bool,
101 ) -> Self {
102 let (public_key, private_key) =
103 TYPES::SignatureKey::generated_from_seed_indexed(seed, index);
104 let (state_public_key, state_private_key) =
105 TYPES::StateSignatureKey::generated_from_seed_indexed(seed, index);
106 Self {
107 public_key,
108 private_key,
109 stake_value,
110 state_public_key,
111 state_private_key,
112 is_da,
113 }
114 }
115
116 pub fn public_config(&self) -> PeerConfig<TYPES> {
118 PeerConfig {
119 stake_table_entry: self.public_key.stake_table_entry(self.stake_value),
120 state_ver_key: self.state_public_key.clone(),
121 }
122 }
123}
124
125impl<TYPES: NodeType> Default for ValidatorConfig<TYPES> {
126 fn default() -> Self {
127 Self::generated_from_seed_indexed([0u8; 32], 0, U256::from(1), true)
128 }
129}
130
131#[derive(serde::Serialize, serde::Deserialize, Clone, Display, PartialEq, Eq, Hash)]
132#[serde(bound(deserialize = ""))]
133pub struct PeerConfig<TYPES: NodeType> {
135 pub stake_table_entry: <TYPES::SignatureKey as SignatureKey>::StakeTableEntry,
138 pub state_ver_key: TYPES::StateSignatureKey,
141}
142
143impl<TYPES: NodeType> PeerConfig<TYPES> {
144 pub fn to_bytes(config: &Self) -> Vec<u8> {
146 let x = bincode_opts().serialize(config);
147 match x {
148 Ok(x) => x,
149 Err(e) => {
150 error!(?e, "Failed to serialize public key");
151 vec![]
152 },
153 }
154 }
155
156 pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
160 let x: Result<PeerConfig<TYPES>, _> = bincode_opts().deserialize(bytes);
161 match x {
162 Ok(pub_key) => Some(pub_key),
163 Err(e) => {
164 error!(?e, "Failed to deserialize public key");
165 None
166 },
167 }
168 }
169}
170
171impl<TYPES: NodeType> Default for PeerConfig<TYPES> {
172 fn default() -> Self {
173 let default_validator_config = ValidatorConfig::<TYPES>::default();
174 default_validator_config.public_config()
175 }
176}
177
178impl<TYPES: NodeType> Debug for PeerConfig<TYPES> {
179 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180 f.debug_struct("PeerConfig")
181 .field("stake_table_entry", &self.stake_table_entry)
182 .field("state_ver_key", &format_args!("{}", self.state_ver_key))
183 .finish()
184 }
185}
186
187#[derive(Clone, derive_more::Debug, serde::Serialize, serde::Deserialize)]
188#[serde(bound(deserialize = ""))]
189pub struct VersionedDaCommittee<TYPES: NodeType> {
190 #[serde(with = "version_ser")]
191 pub start_version: Version,
192 pub start_epoch: u64,
193 pub committee: Vec<PeerConfig<TYPES>>,
194}
195
196#[derive(Clone, derive_more::Debug, serde::Serialize, serde::Deserialize)]
198#[serde(bound(deserialize = ""))]
199pub struct HotShotConfig<TYPES: NodeType> {
200 pub start_threshold: (u64, u64),
203 pub num_nodes_with_stake: NonZeroUsize,
206 pub known_nodes_with_stake: Vec<PeerConfig<TYPES>>,
208 pub known_da_nodes: Vec<PeerConfig<TYPES>>,
210 pub da_committees: Vec<VersionedDaCommittee<TYPES>>,
212 pub da_staked_committee_size: usize,
214 pub fixed_leader_for_gpuvid: usize,
216 pub next_view_timeout: u64,
218 pub view_sync_timeout: Duration,
220 pub num_bootstrap: usize,
222 pub builder_timeout: Duration,
224 pub data_request_delay: Duration,
226 pub builder_urls: Vec1<Url>,
228 pub start_proposing_view: u64,
230 pub stop_proposing_view: u64,
232 pub start_voting_view: u64,
234 pub stop_voting_view: u64,
236 pub start_proposing_time: u64,
238 pub stop_proposing_time: u64,
240 pub start_voting_time: u64,
242 pub stop_voting_time: u64,
244 pub epoch_height: u64,
246 #[serde(default = "default_epoch_start_block")]
248 pub epoch_start_block: u64,
249 #[serde(default = "default_stake_table_capacity")]
251 pub stake_table_capacity: usize,
252 pub drb_difficulty: u64,
254 pub drb_upgrade_difficulty: u64,
256}
257
258fn default_epoch_start_block() -> u64 {
259 1
260}
261
262fn default_stake_table_capacity() -> usize {
263 crate::light_client::DEFAULT_STAKE_TABLE_CAPACITY
264}
265
266impl<TYPES: NodeType> HotShotConfig<TYPES> {
267 pub fn set_view_upgrade(&mut self, view: u64) {
269 self.start_proposing_view = view;
270 self.stop_proposing_view = view + 1;
271 self.start_voting_view = view.saturating_sub(1);
272 self.stop_voting_view = view + 10;
273 self.start_proposing_time = 0;
274 self.stop_proposing_time = u64::MAX;
275 self.start_voting_time = 0;
276 self.stop_voting_time = u64::MAX;
277 }
278
279 pub fn hotshot_stake_table(&self) -> HSStakeTable<TYPES> {
281 self.known_nodes_with_stake.clone().into()
282 }
283}
284
285pub mod version_ser {
286
287 use serde::{de, Deserialize, Deserializer, Serializer};
288 use vbs::version::Version;
289
290 pub fn serialize<S>(ver: &Version, serializer: S) -> Result<S::Ok, S::Error>
291 where
292 S: Serializer,
293 {
294 serializer.serialize_str(&ver.to_string())
295 }
296
297 pub fn deserialize<'de, D>(deserializer: D) -> Result<Version, D::Error>
298 where
299 D: Deserializer<'de>,
300 {
301 let version_str = String::deserialize(deserializer)?;
302
303 let version: Vec<_> = version_str.split('.').collect();
304
305 let version = Version {
306 major: version[0]
307 .parse()
308 .map_err(|_| de::Error::custom("invalid version format"))?,
309 minor: version[1]
310 .parse()
311 .map_err(|_| de::Error::custom("invalid version format"))?,
312 };
313
314 Ok(version)
315 }
316}