sequencer/state_signature/relay_server/
lcv2_relay.rs

1use std::{
2    collections::{hash_map::Entry, BTreeSet, HashMap},
3    sync::Arc,
4};
5
6use alloy::primitives::U256;
7use hotshot_types::{
8    light_client::{
9        LCV2StateSignatureRequestBody, LCV2StateSignaturesBundle, LightClientState, StateVerKey,
10    },
11    traits::signature_key::LCV2StateSignatureKey,
12};
13use tide_disco::{error::ServerError, Error, StatusCode};
14
15use super::stake_table_tracker::StakeTableTracker;
16
17#[async_trait::async_trait]
18pub trait LCV2StateRelayServerDataSource {
19    /// Get the latest available signatures bundle.
20    /// # Errors
21    /// Errors if there's no available signatures bundle.
22    fn get_latest_signature_bundle(&self) -> Result<LCV2StateSignaturesBundle, ServerError>;
23
24    /// Post a signature to the relay server
25    /// # Errors
26    /// Errors if the signature is invalid, already posted, or no longer needed.
27    async fn post_signature(
28        &mut self,
29        req: LCV2StateSignatureRequestBody,
30    ) -> Result<(), ServerError>;
31}
32
33/// Server state that tracks the light client V2 state and signatures
34pub struct LCV2StateRelayServerState {
35    /// Bundles for light client V2
36    bundles: HashMap<u64, HashMap<LightClientState, LCV2StateSignaturesBundle>>,
37
38    /// The latest state signatures bundle for legacy light client
39    latest_available_bundle: Option<LCV2StateSignaturesBundle>,
40    /// The block height of the latest available legacy state signature bundle
41    latest_block_height: Option<u64>,
42
43    /// A ordered queue of block heights for legacy light client state, used for garbage collection.
44    gc_queue: BTreeSet<u64>,
45
46    /// Stake table tracker
47    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, ServerError> {
53        self.latest_available_bundle
54            .clone()
55            .ok_or(ServerError::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<(), ServerError> {
65        let block_height = req.state.block_height;
66        if block_height <= self.latest_block_height.unwrap_or(0) {
67            // This signature is no longer needed
68            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| {
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        // sanity check the signature validity first before adding in
89        if !<StateVerKey as LCV2StateSignatureKey>::verify_state_sig(
90            &req.key,
91            &req.signature,
92            &req.state,
93            &req.next_stake,
94        ) {
95            tracing::warn!("Received invalid legacy signature: {:?}", req);
96            return Err(ServerError::catch_all(
97                StatusCode::BAD_REQUEST,
98                "The posted legacy signature is not valid.".to_owned(),
99            ));
100        }
101
102        let bundles_at_height = self.bundles.entry(block_height).or_default();
103        self.gc_queue.insert(block_height);
104
105        let bundle = bundles_at_height
106            .entry(req.state)
107            .or_insert(LCV2StateSignaturesBundle {
108                state: req.state,
109                next_stake: req.next_stake,
110                signatures: Default::default(),
111                accumulated_weight: U256::from(0),
112            });
113        tracing::debug!(
114            "Accepting new legacy 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 legacy signature of this light client state is already posted at this \
124                     block 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 V2 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 LCV2StateRelayServerState {
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}