Skip to main content

evm_fork_cache_event_service/
desired_state.rs

1use std::collections::{HashMap, HashSet};
2
3use evm_fork_cache_event_protocol::{
4    PROTOCOL_VERSION,
5    v1::{ApplyDesiredState, BlockMode, DesiredStateApplied, portable_interest},
6};
7
8/// In-memory authority for committed session desired state.
9#[derive(Debug, Default)]
10pub struct DesiredStateRegistry {
11    sessions: HashMap<(String, u64), ApplyDesiredState>,
12}
13
14impl DesiredStateRegistry {
15    /// Create an empty desired-state registry.
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    /// Atomically replace a session's desired state when its revision matches.
21    ///
22    /// # Errors
23    ///
24    /// Returns [`DesiredStateError`] when the request is structurally invalid,
25    /// uses an unsupported protocol/interest, or loses the revision
26    /// compare-and-swap. Failure leaves the committed registry unchanged.
27    pub fn apply(
28        &mut self,
29        request: ApplyDesiredState,
30    ) -> Result<DesiredStateApplied, DesiredStateError> {
31        validate_desired_state(&request)?;
32        let key = (request.session_id.clone(), request.chain_id);
33        let existing = self.sessions.get(&key);
34        let committed = existing.map_or(0, |state| state.new_revision);
35        if request.expected_revision != committed {
36            if existing == Some(&request) {
37                return Ok(DesiredStateApplied {
38                    session_id: request.session_id,
39                    revision: request.new_revision,
40                    activation_sequence: 0,
41                });
42            }
43            return Err(DesiredStateError::RevisionConflict {
44                expected: request.expected_revision,
45                committed,
46            });
47        }
48        if committed.checked_add(1) != Some(request.new_revision) {
49            return Err(DesiredStateError::InvalidState(
50                "new revision must immediately follow the committed revision",
51            ));
52        }
53
54        let applied = DesiredStateApplied {
55            session_id: request.session_id.clone(),
56            revision: request.new_revision,
57            activation_sequence: 0,
58        };
59        self.sessions.insert(key, request);
60        Ok(applied)
61    }
62
63    /// Borrow the committed state for a session and chain.
64    pub fn committed(&self, session_id: &str, chain_id: u64) -> Option<&ApplyDesiredState> {
65        self.sessions.get(&(session_id.to_owned(), chain_id))
66    }
67}
68
69/// Validate protocol identity, owner topology, filters, and backfill bounds for
70/// one complete desired-state replacement.
71///
72/// # Errors
73///
74/// Returns [`DesiredStateError`] for an incompatible protocol version,
75/// malformed identity/topology/filter/backfill, or an interest protocol v1
76/// cannot represent.
77pub fn validate_desired_state(request: &ApplyDesiredState) -> Result<(), DesiredStateError> {
78    if request.protocol_version != PROTOCOL_VERSION {
79        return Err(DesiredStateError::ProtocolVersion {
80            received: request.protocol_version,
81            supported: PROTOCOL_VERSION,
82        });
83    }
84    if request.session_id.is_empty() {
85        return Err(DesiredStateError::InvalidState("session id is empty"));
86    }
87    if request.expected_revision == u64::MAX {
88        return Err(DesiredStateError::InvalidState(
89            "expected revision has no representable successor",
90        ));
91    }
92    // Service-level quotas run before this validator. Keep the standalone
93    // validator free of attacker-sized eager allocation as well.
94    let mut owner_ids = HashSet::new();
95    let mut has_canonical_interests = false;
96    for owner in &request.owners {
97        if owner.canonical {
98            if !owner.owner_id.is_empty() {
99                return Err(DesiredStateError::InvalidState(
100                    "canonical interests must not carry an owner id",
101                ));
102            }
103            if has_canonical_interests {
104                return Err(DesiredStateError::InvalidState(
105                    "canonical interests appear more than once",
106                ));
107            }
108            has_canonical_interests = true;
109        } else if owner.owner_id.is_empty() {
110            return Err(DesiredStateError::InvalidState("owner id is empty"));
111        } else if !owner_ids.insert(owner.owner_id.as_str()) {
112            return Err(DesiredStateError::InvalidState("owner ids must be unique"));
113        }
114        if let Some(backfill) = owner.backfill.as_ref() {
115            if backfill.to_block_excl.is_some_and(|end| {
116                end < backfill.from_block
117                    || (end == backfill.from_block && backfill.retained_baseline.is_none())
118            }) {
119                return Err(DesiredStateError::InvalidState(
120                    "backfill end precedes its start or encodes an uncertified empty range",
121                ));
122            }
123            if let Some(baseline) = backfill.retained_baseline.as_ref() {
124                if baseline.number.checked_add(1) != Some(backfill.from_block) {
125                    return Err(DesiredStateError::InvalidState(
126                        "retained backfill baseline must immediately precede its start",
127                    ));
128                }
129                if baseline.hash.len() != 32 || baseline.parent_hash.len() != 32 {
130                    return Err(DesiredStateError::InvalidState(
131                        "retained backfill baseline hashes must be 32 bytes",
132                    ));
133                }
134            }
135        }
136        for interest in &owner.interests {
137            match interest.kind.as_ref() {
138                Some(portable_interest::Kind::Block(block)) => {
139                    match BlockMode::try_from(block.mode) {
140                        Ok(BlockMode::Header) => {}
141                        Ok(BlockMode::FullBlock) => {
142                            return Err(DesiredStateError::UnsupportedInterest {
143                                owner_id: owner.owner_id.clone(),
144                                interest: "full block",
145                            });
146                        }
147                        _ => {
148                            return Err(DesiredStateError::InvalidState(
149                                "block interest mode is unspecified or unknown",
150                            ));
151                        }
152                    }
153                }
154                Some(portable_interest::Kind::Log(log)) => {
155                    if log.addresses.iter().any(|address| address.len() != 20) {
156                        return Err(DesiredStateError::InvalidState(
157                            "log addresses must be 20 bytes",
158                        ));
159                    }
160                    if log.topics.len() > 4 {
161                        return Err(DesiredStateError::InvalidState(
162                            "log interests support at most four topic positions",
163                        ));
164                    }
165                    if log
166                        .topics
167                        .iter()
168                        .flat_map(|topic| &topic.values)
169                        .any(|topic| topic.len() != 32)
170                    {
171                        return Err(DesiredStateError::InvalidState(
172                            "log topics must be 32 bytes",
173                        ));
174                    }
175                }
176                None => {
177                    return Err(DesiredStateError::InvalidState(
178                        "portable interest kind is missing",
179                    ));
180                }
181            }
182        }
183    }
184    Ok(())
185}
186
187/// Desired-state validation or compare-and-swap failure.
188#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
189#[non_exhaustive]
190pub enum DesiredStateError {
191    /// The desired state is structurally invalid.
192    #[error("invalid desired state: {0}")]
193    InvalidState(&'static str),
194    /// The client and service do not share a compatible wire version.
195    #[error("unsupported protocol version {received}; service supports {supported}")]
196    ProtocolVersion {
197        /// Version supplied by the client.
198        received: u32,
199        /// Version supported by this service.
200        supported: u32,
201    },
202    /// A syntactically valid interest is outside the service's supported set.
203    #[error("owner `{owner_id}` requested unsupported {interest} interest")]
204    UnsupportedInterest {
205        /// Owner that requested the interest.
206        owner_id: String,
207        /// Human-readable interest kind.
208        interest: &'static str,
209    },
210    /// The request was based on a stale committed revision.
211    #[error("desired-state revision conflict: expected {expected}, committed {committed}")]
212    RevisionConflict {
213        /// Revision supplied by the client.
214        expected: u64,
215        /// Current authoritative revision.
216        committed: u64,
217    },
218}