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