sequencer/state_signature/relay_server/
lcv1_relay.rs1use std::{
2 collections::{hash_map::Entry, BTreeSet},
3 sync::Arc,
4};
5
6use alloy::primitives::{map::HashMap, U256};
7use hotshot_types::{
8 light_client::{
9 LCV1StateSignatureRequestBody, LCV1StateSignaturesBundle, LightClientState, StateVerKey,
10 },
11 traits::signature_key::LCV1StateSignatureKey,
12};
13use tide_disco::{error::ServerError, Error, StatusCode};
14
15use super::stake_table_tracker::StakeTableTracker;
16
17#[async_trait::async_trait]
18pub trait LCV1StateRelayServerDataSource {
19 fn get_latest_signature_bundle(&self) -> Result<LCV1StateSignaturesBundle, ServerError>;
23
24 async fn post_signature(
28 &mut self,
29 req: LCV1StateSignatureRequestBody,
30 ) -> Result<(), ServerError>;
31}
32
33pub struct LCV1StateRelayServerState {
35 bundles: HashMap<u64, HashMap<LightClientState, LCV1StateSignaturesBundle>>,
37
38 latest_available_bundle: Option<LCV1StateSignaturesBundle>,
40 latest_block_height: Option<u64>,
42
43 gc_queue: BTreeSet<u64>,
45
46 stake_table_tracker: Arc<StakeTableTracker>,
48}
49
50#[async_trait::async_trait]
51impl LCV1StateRelayServerDataSource for LCV1StateRelayServerState {
52 fn get_latest_signature_bundle(&self) -> Result<LCV1StateSignaturesBundle, ServerError> {
53 self.latest_available_bundle
54 .clone()
55 .ok_or(ServerError::catch_all(
56 StatusCode::NOT_FOUND,
57 "The light client V1 state signatures are not ready.".to_owned(),
58 ))
59 }
60
61 async fn post_signature(
62 &mut self,
63 req: LCV1StateSignatureRequestBody,
64 ) -> Result<(), ServerError> {
65 let block_height = req.state.block_height;
66 if block_height <= self.latest_block_height.unwrap_or(0) {
67 return Ok(());
69 }
70 let stake_table = self
71 .stake_table_tracker
72 .genesis_stake_table_info()
73 .await
74 .map_err(|e| {
75 ServerError::catch_all(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
76 })?;
77 let Some(weight) = stake_table.known_nodes.get(&req.key) else {
78 tracing::warn!(
79 "Received invalid legacy signature from unknown node: {:?}",
80 req
81 );
82 return Err(ServerError::catch_all(
83 StatusCode::UNAUTHORIZED,
84 "Legacy signature posted by nodes not on the stake table".to_owned(),
85 ));
86 };
87
88 if !<StateVerKey as LCV1StateSignatureKey>::verify_state_sig(
90 &req.key,
91 &req.signature,
92 &req.state,
93 ) {
94 tracing::warn!("Received invalid legacy signature: {:?}", req);
95 return Err(ServerError::catch_all(
96 StatusCode::BAD_REQUEST,
97 "The posted legacy signature is not valid.".to_owned(),
98 ));
99 }
100
101 let bundles_at_height = self.bundles.entry(block_height).or_default();
102 self.gc_queue.insert(block_height);
103
104 let bundle = bundles_at_height
105 .entry(req.state)
106 .or_insert(LCV1StateSignaturesBundle {
107 state: req.state,
108 signatures: Default::default(),
109 accumulated_weight: U256::from(0),
110 });
111 tracing::debug!(
112 "Accepting new legacy signature for block height {} from {}.",
113 block_height,
114 req.key
115 );
116 match bundle.signatures.entry(req.key) {
117 Entry::Occupied(_) => {
118 return Err(ServerError::catch_all(
120 StatusCode::BAD_REQUEST,
121 "A legacy signature of this light client state is already posted at this \
122 block height for this key."
123 .to_owned(),
124 ));
125 },
126 Entry::Vacant(entry) => {
127 entry.insert(req.signature);
128 bundle.accumulated_weight += *weight;
129 },
130 }
131
132 if bundle.accumulated_weight >= stake_table.threshold {
133 tracing::info!(
134 "Light client V1 state signature bundle at block height {} is ready to serve.",
135 block_height
136 );
137 self.latest_block_height = Some(block_height);
138 self.latest_available_bundle = Some(bundle.clone());
139
140 self.prune(block_height);
142 }
143
144 Ok(())
145 }
146}
147
148impl LCV1StateRelayServerState {
149 pub fn prune(&mut self, until_height: u64) {
152 while let Some(&height) = self.gc_queue.first() {
153 if height > until_height {
154 return;
155 }
156 self.bundles.remove(&height);
157 self.gc_queue.pop_first();
158 tracing::debug!(%height, "garbage collected for ");
159 }
160 }
161
162 pub fn new(stake_table_tracker: Arc<StakeTableTracker>) -> Self {
163 Self {
164 bundles: HashMap::new(),
165 latest_available_bundle: None,
166 latest_block_height: None,
167 gc_queue: BTreeSet::new(),
168 stake_table_tracker,
169 }
170 }
171}