sequencer/state_signature/relay_server/
lcv3_relay.rs

1use std::{
2    collections::{hash_map::Entry, BTreeSet, HashMap},
3    sync::Arc,
4};
5
6use alloy::primitives::U256;
7use hotshot_task_impls::helpers::derive_signed_state_digest;
8use hotshot_types::{
9    light_client::{
10        LCV3StateSignatureRequestBody, LCV3StateSignaturesBundle, LightClientState, StateVerKey,
11    },
12    traits::signature_key::LCV3StateSignatureKey,
13};
14use tide_disco::{error::ServerError, Error, StatusCode};
15
16use super::stake_table_tracker::StakeTableTracker;
17
18#[async_trait::async_trait]
19pub trait LCV3StateRelayServerDataSource {
20    /// Get the latest available signatures bundle.
21    /// # Errors
22    /// Errors if there's no available signatures bundle.
23    fn get_latest_signature_bundle(&self) -> Result<LCV3StateSignaturesBundle, ServerError>;
24
25    /// Post a signature to the relay server
26    /// # Errors
27    /// Errors if the signature is invalid, already posted, or no longer needed.
28    async fn post_signature(
29        &mut self,
30        req: LCV3StateSignatureRequestBody,
31    ) -> Result<(), ServerError>;
32}
33
34/// Server state that tracks the light client V3 state and signatures
35pub struct LCV3StateRelayServerState {
36    /// Bundles for light client V3
37    bundles: HashMap<u64, HashMap<LightClientState, LCV3StateSignaturesBundle>>,
38
39    /// The latest state signatures bundle for LCV3 light client
40    latest_available_bundle: Option<LCV3StateSignaturesBundle>,
41    /// The block height of the latest available LCV3 state signature bundle
42    latest_block_height: Option<u64>,
43
44    /// A ordered queue of block heights for V3 light client state, used for garbage collection.
45    gc_queue: BTreeSet<u64>,
46
47    /// Stake table tracker
48    stake_table_tracker: Arc<StakeTableTracker>,
49}
50
51#[async_trait::async_trait]
52impl LCV3StateRelayServerDataSource for LCV3StateRelayServerState {
53    fn get_latest_signature_bundle(&self) -> Result<LCV3StateSignaturesBundle, ServerError> {
54        self.latest_available_bundle
55            .clone()
56            .ok_or(ServerError::catch_all(
57                StatusCode::NOT_FOUND,
58                "The light client V3 state signatures are not ready.".to_owned(),
59            ))
60    }
61
62    async fn post_signature(
63        &mut self,
64        req: LCV3StateSignatureRequestBody,
65    ) -> Result<(), ServerError> {
66        let block_height = req.state.block_height;
67        if block_height <= self.latest_block_height.unwrap_or(0) {
68            // This signature is no longer needed
69            return Ok(());
70        }
71        let stake_table = self
72            .stake_table_tracker
73            .stake_table_info_for_block(block_height)
74            .await
75            .map_err(|e| {
76                ServerError::catch_all(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
77            })?;
78        let Some(weight) = stake_table.known_nodes.get(&req.key) else {
79            tracing::warn!("Received LCV3 signature from unknown node: {req}");
80            return Err(ServerError::catch_all(
81                StatusCode::UNAUTHORIZED,
82                "LCV3 signature posted by nodes not on the stake table".to_owned(),
83            ));
84        };
85
86        // sanity check the signature validity first before adding in
87        let signed_state_digest =
88            derive_signed_state_digest(&req.state, &req.next_stake, &req.auth_root);
89        if !<StateVerKey as LCV3StateSignatureKey>::verify_state_sig(
90            &req.key,
91            &req.signature,
92            signed_state_digest,
93        ) {
94            tracing::warn!("Couldn't verify the received LCV3 signature: {req}");
95            return Err(ServerError::catch_all(
96                StatusCode::BAD_REQUEST,
97                "The posted LCV3 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(LCV3StateSignaturesBundle {
107                state: req.state,
108                next_stake: req.next_stake,
109                auth_root: req.auth_root,
110                signatures: Default::default(),
111                accumulated_weight: U256::from(0),
112            });
113        tracing::debug!(
114            "Accepting new LCV3 signature for block height {} from {}.",
115            block_height,
116            req.key
117        );
118        match bundle.signatures.entry(req.key) {
119            Entry::Occupied(_) => {
120                // A signature is already posted for this key with this state
121                return Err(ServerError::catch_all(
122                    StatusCode::BAD_REQUEST,
123                    "A LCV3 signature of this light client state is already posted at this block \
124                     height for this key."
125                        .to_owned(),
126                ));
127            },
128            Entry::Vacant(entry) => {
129                entry.insert(req.signature);
130                bundle.accumulated_weight += *weight;
131            },
132        }
133
134        if bundle.accumulated_weight >= stake_table.threshold {
135            tracing::info!(
136                "Light client V3 state signature bundle at block height {} is ready to serve.",
137                block_height
138            );
139            self.latest_block_height = Some(block_height);
140            self.latest_available_bundle = Some(bundle.clone());
141
142            // garbage collect
143            self.prune(block_height);
144        }
145
146        Ok(())
147    }
148}
149
150impl LCV3StateRelayServerState {
151    /// Centralizing all garbage-collection logic, won't panic, won't error, simply do nothing if nothing to prune.
152    /// `until_height` is inclusive, meaning that would also be pruned.
153    pub fn prune(&mut self, until_height: u64) {
154        while let Some(&height) = self.gc_queue.first() {
155            if height > until_height {
156                return;
157            }
158            self.bundles.remove(&height);
159            self.gc_queue.pop_first();
160            tracing::debug!(%height, "garbage collected for ");
161        }
162    }
163
164    pub fn new(stake_table_tracker: Arc<StakeTableTracker>) -> Self {
165        Self {
166            bundles: HashMap::new(),
167            latest_available_bundle: None,
168            latest_block_height: None,
169            gc_queue: BTreeSet::new(),
170            stake_table_tracker,
171        }
172    }
173}