1use std::{
2 collections::{BTreeMap, HashMap, HashSet},
3 path::Path,
4 time::Duration,
5};
6
7use alloy_consensus::Header as ConsensusHeader;
8use alloy_rlp::Decodable;
9use evm_fork_cache_event_protocol::{
10 MAX_MESSAGE_SIZE_BYTES,
11 v1::{
12 Acknowledge, ApplyDesiredState, Barrier, BlockRef, Cursor, Delivery, DeliveryScope,
13 DesiredStateApplied, FinalityKind, chain_event, delivery,
14 },
15};
16use prost::Message;
17use rusqlite::{Connection, OptionalExtension, params};
18
19use crate::{DesiredStateError, validate_desired_state};
20
21pub const SESSION_SCHEMA_VERSION: u32 = 3;
23
24#[derive(Clone, Debug, Default)]
26#[non_exhaustive]
27pub struct PersistedSession {
28 pub desired_state: Option<ApplyDesiredState>,
30 pub acknowledged_cursor: Option<Cursor>,
32 pub runtime_checkpoint_cursor: Option<Cursor>,
34 pub pending_delivery: Option<Delivery>,
36 pub expected_reorg_tip: Option<BlockRef>,
39}
40
41pub struct SessionStore {
43 connection: Connection,
44}
45
46impl SessionStore {
47 pub fn open(path: impl AsRef<Path>) -> Result<Self, SessionStoreError> {
54 Self::from_connection(Connection::open(path)?)
55 }
56
57 pub fn open_in_memory() -> Result<Self, SessionStoreError> {
64 Self::from_connection(Connection::open_in_memory()?)
65 }
66
67 fn from_connection(mut connection: Connection) -> Result<Self, SessionStoreError> {
68 connection.busy_timeout(Duration::from_secs(5))?;
69 connection.execute_batch(
70 "PRAGMA journal_mode = WAL;
71 PRAGMA synchronous = FULL;
72 PRAGMA foreign_keys = ON;",
73 )?;
74 let schema_version: u32 =
75 connection.query_row("PRAGMA user_version", [], |row| row.get(0))?;
76 if schema_version > SESSION_SCHEMA_VERSION {
77 return Err(SessionStoreError::Schema(format!(
78 "database schema version {schema_version} is newer than supported version {SESSION_SCHEMA_VERSION}"
79 )));
80 }
81 let transaction = connection.transaction()?;
82 let table_exists = transaction.query_row(
83 "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sessions')",
84 [],
85 |row| row.get::<_, bool>(0),
86 )?;
87 if !table_exists {
88 transaction.execute_batch(
89 "CREATE TABLE sessions (
90 session_id TEXT NOT NULL,
91 chain_id INTEGER NOT NULL,
92 revision INTEGER NOT NULL,
93 desired_state BLOB,
94 acknowledged_cursor BLOB,
95 runtime_checkpoint_cursor BLOB,
96 pending_delivery BLOB,
97 activation_sequence INTEGER NOT NULL DEFAULT 0,
98 expected_reorg_tip BLOB,
99 PRIMARY KEY (session_id, chain_id)
100 );",
101 )?;
102 } else {
103 migrate_sessions_table(&transaction)?;
104 }
105 transaction.pragma_update(None, "user_version", SESSION_SCHEMA_VERSION)?;
106 transaction.commit()?;
107 Ok(Self { connection })
108 }
109
110 pub fn load(
118 &self,
119 session_id: &str,
120 chain_id: u64,
121 ) -> Result<PersistedSession, SessionStoreError> {
122 let chain_id = chain_id_to_sql_integer(chain_id);
123 let row = self
124 .connection
125 .query_row(
126 "SELECT revision, desired_state, acknowledged_cursor,
127 runtime_checkpoint_cursor, pending_delivery, activation_sequence,
128 expected_reorg_tip
129 FROM sessions WHERE session_id = ?1 AND chain_id = ?2",
130 params![session_id, chain_id],
131 |row| {
132 Ok((
133 row.get::<_, i64>(0)?,
134 row.get::<_, Option<Vec<u8>>>(1)?,
135 row.get::<_, Option<Vec<u8>>>(2)?,
136 row.get::<_, Option<Vec<u8>>>(3)?,
137 row.get::<_, Option<Vec<u8>>>(4)?,
138 row.get::<_, i64>(5)?,
139 row.get::<_, Option<Vec<u8>>>(6)?,
140 ))
141 },
142 )
143 .optional()?;
144 let Some((
145 revision,
146 desired_state,
147 acknowledged_cursor,
148 runtime_checkpoint_cursor,
149 pending_delivery,
150 activation_sequence,
151 expected_reorg_tip,
152 )) = row
153 else {
154 return Ok(PersistedSession::default());
155 };
156 let persisted = PersistedSession {
157 desired_state: decode_optional(desired_state, "desired state")?,
158 acknowledged_cursor: decode_optional(acknowledged_cursor, "acknowledged cursor")?,
159 runtime_checkpoint_cursor: decode_optional(
160 runtime_checkpoint_cursor,
161 "runtime checkpoint cursor",
162 )?,
163 pending_delivery: decode_optional(pending_delivery, "pending delivery")?,
164 expected_reorg_tip: decode_optional(expected_reorg_tip, "expected reorg tip")?,
165 };
166 validate_persisted_session(
167 session_id,
168 chain_id_from_sql_integer(chain_id),
169 from_sql_integer(revision, "revision")?,
170 sequence_from_sql_integer(activation_sequence),
171 &persisted,
172 )?;
173 Ok(persisted)
174 }
175
176 pub fn apply_desired_state(
185 &mut self,
186 request: ApplyDesiredState,
187 ) -> Result<DesiredStateApplied, SessionStoreError> {
188 self.apply_desired_state_with_cursor(request, None)
189 }
190
191 pub fn apply_desired_state_with_cursor(
200 &mut self,
201 request: ApplyDesiredState,
202 prepared_cursor: Option<&Cursor>,
203 ) -> Result<DesiredStateApplied, SessionStoreError> {
204 self.apply_desired_state_with_cursor_and_limit(
205 request,
206 prepared_cursor,
207 MAX_MESSAGE_SIZE_BYTES,
208 usize::MAX,
209 )
210 .map(|(applied, _)| applied)
211 }
212
213 pub(crate) fn apply_desired_state_with_cursor_and_limit(
214 &mut self,
215 request: ApplyDesiredState,
216 prepared_cursor: Option<&Cursor>,
217 max_delivery_bytes: usize,
218 max_persisted_sessions: usize,
219 ) -> Result<(DesiredStateApplied, bool), SessionStoreError> {
220 validate_desired_state(&request)?;
221 let _ = self.load(&request.session_id, request.chain_id)?;
225 if prepared_cursor.is_some_and(|cursor| {
226 cursor.chain_id != request.chain_id || cursor.query_revision != request.new_revision
227 }) {
228 return Err(SessionStoreError::InvalidDelivery(
229 "prepared activation cursor does not match desired state",
230 ));
231 }
232 let chain_id = chain_id_to_sql_integer(request.chain_id);
233 let expected = to_sql_integer(request.expected_revision, "expected revision")?;
234 let revision = to_sql_integer(request.new_revision, "new revision")?;
235 let transaction = self.connection.transaction()?;
236 let committed_row = transaction
237 .query_row(
238 "SELECT revision, desired_state, acknowledged_cursor,
239 pending_delivery, activation_sequence
240 FROM sessions
241 WHERE session_id = ?1 AND chain_id = ?2",
242 params![request.session_id, chain_id],
243 |row| {
244 Ok((
245 row.get::<_, i64>(0)?,
246 row.get::<_, Option<Vec<u8>>>(1)?,
247 row.get::<_, Option<Vec<u8>>>(2)?,
248 row.get::<_, Option<Vec<u8>>>(3)?,
249 row.get::<_, i64>(4)?,
250 ))
251 },
252 )
253 .optional()?;
254 let committed = committed_row.as_ref().map_or(0, |row| row.0);
255 if committed_row.is_none() {
256 let persisted_count: i64 =
257 transaction.query_row("SELECT COUNT(*) FROM sessions", [], |row| row.get(0))?;
258 let persisted_count = usize::try_from(persisted_count)
259 .map_err(|_| SessionStoreError::IntegerRange("persisted session count"))?;
260 if persisted_count >= max_persisted_sessions {
261 return Err(SessionStoreError::PersistedSessionLimit {
262 limit: max_persisted_sessions,
263 });
264 }
265 }
266 if committed != expected {
267 if committed == revision
268 && let Some(row) = committed_row
269 && let Some(encoded) = row.1
270 && ApplyDesiredState::decode(encoded.as_slice())? == request
271 {
272 return Ok((
273 DesiredStateApplied {
274 session_id: request.session_id,
275 revision: request.new_revision,
276 activation_sequence: sequence_from_sql_integer(row.4),
277 },
278 false,
279 ));
280 }
281 return Err(SessionStoreError::RevisionConflict {
282 expected: request.expected_revision,
283 committed: from_sql_integer(committed, "committed revision")?,
284 });
285 }
286 if request.expected_revision.checked_add(1) != Some(request.new_revision) {
287 return Err(SessionStoreError::DesiredState(
288 DesiredStateError::InvalidState(
289 "new revision must immediately follow the committed revision",
290 ),
291 ));
292 }
293 if committed_row.as_ref().is_some_and(|row| row.3.is_some()) {
294 return Err(SessionStoreError::PendingDelivery);
295 }
296 let acknowledged_cursor: Option<Cursor> = committed_row
297 .as_ref()
298 .and_then(|row| row.2.clone())
299 .map(|encoded| Cursor::decode(encoded.as_slice()))
300 .transpose()?;
301 let activation_sequence = acknowledged_cursor.as_ref().map_or(Ok(1), |cursor| {
302 cursor
303 .batch_sequence
304 .checked_add(1)
305 .ok_or(SessionStoreError::SequenceOverflow)
306 })?;
307 let mut cursor = prepared_cursor.cloned().unwrap_or_else(|| {
308 acknowledged_cursor.clone().unwrap_or_else(|| Cursor {
309 chain_id: request.chain_id,
310 query_revision: request.new_revision,
311 next_block: request
312 .owners
313 .iter()
314 .filter_map(|owner| owner.backfill.as_ref().map(|backfill| backfill.from_block))
315 .min()
316 .unwrap_or_default(),
317 canonical_head: None,
318 batch_sequence: 0,
319 provider_checkpoint: Vec::new(),
320 owner_backfill_activation_block: None,
321 })
322 });
323 cursor.query_revision = request.new_revision;
324 cursor.batch_sequence = activation_sequence;
325 let activation = Delivery {
326 session_id: request.session_id.clone(),
327 sequence: activation_sequence,
328 query_revision: request.new_revision,
329 delivery_token: activation_sequence.to_be_bytes().to_vec(),
330 cursor: Some(cursor.clone()),
331 payload: Some(delivery::Payload::Barrier(Barrier {
332 id: format!("desired-state:{}", request.new_revision).into_bytes(),
333 block: None,
334 })),
335 checkpoint_neutral: true,
336 };
337 validate_delivery_size(&activation, max_delivery_bytes.min(MAX_MESSAGE_SIZE_BYTES))?;
338 validate_delivery_payload(&request, &activation)?;
339 validate_delivery_progress(acknowledged_cursor.as_ref(), &request, &activation)?;
340 let activation_sequence_sql = sequence_to_sql_integer(activation_sequence);
341 transaction.execute(
342 "INSERT INTO sessions (
343 session_id, chain_id, revision, desired_state,
344 pending_delivery, activation_sequence
345 )
346 VALUES (?1, ?2, ?3, ?4, ?5, ?6)
347 ON CONFLICT(session_id, chain_id) DO UPDATE SET
348 revision = excluded.revision,
349 desired_state = excluded.desired_state,
350 pending_delivery = excluded.pending_delivery,
351 activation_sequence = excluded.activation_sequence",
352 params![
353 request.session_id,
354 chain_id,
355 revision,
356 request.encode_to_vec(),
357 activation.encode_to_vec(),
358 activation_sequence_sql,
359 ],
360 )?;
361 transaction.commit()?;
362 Ok((
363 DesiredStateApplied {
364 session_id: request.session_id,
365 revision: request.new_revision,
366 activation_sequence,
367 },
368 true,
369 ))
370 }
371
372 pub fn save_pending(
380 &mut self,
381 desired_state: &ApplyDesiredState,
382 delivery: &Delivery,
383 ) -> Result<(), SessionStoreError> {
384 self.save_pending_with_status(desired_state, delivery)
385 .map(|_| ())
386 }
387
388 pub(crate) fn save_pending_with_status(
389 &mut self,
390 desired_state: &ApplyDesiredState,
391 delivery: &Delivery,
392 ) -> Result<bool, SessionStoreError> {
393 let cursor = delivery
394 .cursor
395 .as_ref()
396 .ok_or(SessionStoreError::InvalidDelivery(
397 "delivery cursor is missing",
398 ))?;
399 if delivery.session_id != desired_state.session_id
400 || cursor.chain_id != desired_state.chain_id
401 || delivery.query_revision != desired_state.new_revision
402 || cursor.query_revision != desired_state.new_revision
403 {
404 return Err(SessionStoreError::InvalidDelivery(
405 "delivery identity or revision does not match the active desired state",
406 ));
407 }
408 let chain_id = chain_id_to_sql_integer(desired_state.chain_id);
409 let existing = self.load(&desired_state.session_id, desired_state.chain_id)?;
410 let desired = existing
411 .desired_state
412 .ok_or(SessionStoreError::UnknownSession)?;
413 if desired != *desired_state {
414 return Err(SessionStoreError::InvalidDelivery(
415 "delivery desired state is not authoritative",
416 ));
417 }
418 if delivery.sequence != cursor.batch_sequence
419 || delivery.delivery_token != delivery.sequence.to_be_bytes()
420 || delivery.payload.is_none()
421 || delivery.sequence
422 != existing
423 .acknowledged_cursor
424 .as_ref()
425 .map_or(Ok(1), |cursor| {
426 cursor
427 .batch_sequence
428 .checked_add(1)
429 .ok_or(SessionStoreError::SequenceOverflow)
430 })?
431 {
432 return Err(SessionStoreError::InvalidDelivery(
433 "delivery sequence, token, cursor, payload, or predecessor is invalid",
434 ));
435 }
436 validate_delivery_size(delivery, MAX_MESSAGE_SIZE_BYTES)?;
437 validate_delivery_payload(desired_state, delivery)?;
438 validate_delivery_progress(
439 existing.acknowledged_cursor.as_ref(),
440 desired_state,
441 delivery,
442 )?;
443 if existing
444 .expected_reorg_tip
445 .as_ref()
446 .is_some_and(|expected| !delivery_certifies_reorg_tip(delivery, expected))
447 {
448 return Err(SessionStoreError::InvalidDelivery(
449 "delivery does not certify the promised reorg replacement tip",
450 ));
451 }
452 if let Some(pending) = existing.pending_delivery {
453 if pending == *delivery {
454 return Ok(false);
455 }
456 return Err(SessionStoreError::PendingDelivery);
457 }
458 self.connection.execute(
459 "UPDATE sessions SET pending_delivery = ?3
460 WHERE session_id = ?1 AND chain_id = ?2",
461 params![desired_state.session_id, chain_id, delivery.encode_to_vec()],
462 )?;
463 Ok(true)
464 }
465
466 pub fn acknowledge(
474 &mut self,
475 chain_id: u64,
476 acknowledgement: &Acknowledge,
477 ) -> Result<Cursor, SessionStoreError> {
478 self.acknowledge_with_status(chain_id, acknowledgement)
479 .map(|(cursor, _)| cursor)
480 }
481
482 pub(crate) fn acknowledge_with_status(
483 &mut self,
484 chain_id: u64,
485 acknowledgement: &Acknowledge,
486 ) -> Result<(Cursor, bool), SessionStoreError> {
487 let _ = self.load(&acknowledgement.session_id, chain_id)?;
488 let sql_chain_id = chain_id_to_sql_integer(chain_id);
489 let transaction = self.connection.transaction()?;
490 let row = transaction
491 .query_row(
492 "SELECT acknowledged_cursor, runtime_checkpoint_cursor, pending_delivery,
493 expected_reorg_tip FROM sessions
494 WHERE session_id = ?1 AND chain_id = ?2",
495 params![acknowledgement.session_id, sql_chain_id],
496 |row| {
497 Ok((
498 row.get::<_, Option<Vec<u8>>>(0)?,
499 row.get::<_, Option<Vec<u8>>>(1)?,
500 row.get::<_, Option<Vec<u8>>>(2)?,
501 row.get::<_, Option<Vec<u8>>>(3)?,
502 ))
503 },
504 )
505 .optional()?
506 .ok_or(SessionStoreError::UnknownSession)?;
507 let acknowledged: Option<Cursor> = decode_optional(row.0, "acknowledged cursor")?;
508 let runtime_checkpoint: Option<Cursor> =
509 decode_optional(row.1, "runtime checkpoint cursor")?;
510 let expected_reorg_tip: Option<BlockRef> = decode_optional(row.3, "expected reorg tip")?;
511 let Some(encoded_pending) = row.2 else {
512 if let Some(cursor) = acknowledged
513 && cursor.batch_sequence == acknowledgement.sequence
514 && acknowledgement.delivery_token == acknowledgement.sequence.to_be_bytes()
515 {
516 return Ok((cursor, false));
517 }
518 return if acknowledgement.delivery_token != acknowledgement.sequence.to_be_bytes() {
519 Err(SessionStoreError::DeliveryTokenMismatch)
520 } else {
521 Err(SessionStoreError::NoPendingDelivery)
522 };
523 };
524 let pending = Delivery::decode(encoded_pending.as_slice())?;
525 if pending.sequence != acknowledgement.sequence
526 || pending.delivery_token != acknowledgement.delivery_token
527 {
528 return Err(SessionStoreError::DeliveryTokenMismatch);
529 }
530 let next_expected_reorg_tip =
531 expected_reorg_tip_after_ack(expected_reorg_tip.as_ref(), &pending)?;
532 let cursor = pending.cursor.ok_or(SessionStoreError::InvalidDelivery(
533 "delivery cursor is missing",
534 ))?;
535 let encoded_cursor = cursor.encode_to_vec();
536 let encoded_runtime_checkpoint = if pending.checkpoint_neutral {
537 runtime_checkpoint.map(|cursor| cursor.encode_to_vec())
538 } else {
539 Some(encoded_cursor.clone())
540 };
541 transaction.execute(
542 "UPDATE sessions
543 SET acknowledged_cursor = ?3,
544 runtime_checkpoint_cursor = ?4,
545 pending_delivery = NULL,
546 expected_reorg_tip = ?5
547 WHERE session_id = ?1 AND chain_id = ?2",
548 params![
549 acknowledgement.session_id,
550 sql_chain_id,
551 encoded_cursor,
552 encoded_runtime_checkpoint,
553 next_expected_reorg_tip.map(|tip| tip.encode_to_vec()),
554 ],
555 )?;
556 transaction.commit()?;
557 Ok((cursor, true))
558 }
559}
560
561fn validate_delivery_size(
562 delivery: &Delivery,
563 max_delivery_bytes: usize,
564) -> Result<(), SessionStoreError> {
565 let delivery_bytes = delivery.encoded_len();
566 let encoded_bytes = delivery_bytes
570 .saturating_add(prost::length_delimiter_len(delivery_bytes))
571 .saturating_add(1);
572 if encoded_bytes > max_delivery_bytes {
573 return Err(SessionStoreError::DeliveryTooLarge {
574 encoded_bytes,
575 max_delivery_bytes,
576 });
577 }
578 Ok(())
579}
580
581fn validate_delivery_payload(
582 desired_state: &ApplyDesiredState,
583 delivery: &Delivery,
584) -> Result<(), SessionStoreError> {
585 if let Some(head) = delivery
586 .cursor
587 .as_ref()
588 .and_then(|cursor| cursor.canonical_head.as_ref())
589 {
590 validate_block_ref(head)?;
591 }
592 let Some(payload) = delivery.payload.as_ref() else {
593 return Err(SessionStoreError::InvalidDelivery(
594 "delivery payload is missing",
595 ));
596 };
597 let is_neutral_control = is_activation_delivery(delivery, desired_state.new_revision)
598 || is_cursor_progress_barrier(delivery);
599 if delivery.checkpoint_neutral != is_neutral_control {
600 return Err(SessionStoreError::InvalidDelivery(
601 "checkpoint-neutral marker must identify exactly an activation or scan-only progress barrier",
602 ));
603 }
604 let delivery::Payload::Data(data) = payload else {
605 return match payload {
606 delivery::Payload::Reorg(reorg) => {
607 let ancestor =
608 reorg
609 .common_ancestor
610 .as_ref()
611 .ok_or(SessionStoreError::InvalidDelivery(
612 "reorg is missing its common ancestor",
613 ))?;
614 let old_tip = reorg
615 .old_tip
616 .as_ref()
617 .ok_or(SessionStoreError::InvalidDelivery(
618 "reorg is missing its old tip",
619 ))?;
620 let new_tip = reorg
621 .new_tip
622 .as_ref()
623 .ok_or(SessionStoreError::InvalidDelivery(
624 "reorg is missing its new tip",
625 ))?;
626 for block in [ancestor, old_tip, new_tip] {
627 validate_block_ref(block)?;
628 }
629 validate_reorg_shape(ancestor, old_tip, new_tip)
630 }
631 delivery::Payload::Finality(finality) => {
632 if matches!(
633 FinalityKind::try_from(finality.kind),
634 Err(_) | Ok(FinalityKind::Unspecified)
635 ) {
636 return Err(SessionStoreError::InvalidDelivery(
637 "finality kind is unspecified or unknown",
638 ));
639 }
640 validate_block_ref(finality.block.as_ref().ok_or(
641 SessionStoreError::InvalidDelivery("finality block is missing"),
642 )?)
643 }
644 delivery::Payload::Barrier(barrier) => {
645 if barrier.id.is_empty() {
646 return Err(SessionStoreError::InvalidDelivery(
647 "barrier identifier is empty",
648 ));
649 }
650 if let Some(block) = barrier.block.as_ref() {
651 validate_block_ref(block)?;
652 }
653 Ok(())
654 }
655 delivery::Payload::Data(_) => unreachable!("data payload was matched above"),
656 };
657 };
658 if data.records.is_empty() {
659 return Err(SessionStoreError::InvalidDelivery(
660 "data delivery contains no records",
661 ));
662 }
663 let known_owners: HashSet<&str> = desired_state
664 .owners
665 .iter()
666 .filter(|owner| !owner.canonical)
667 .map(|owner| owner.owner_id.as_str())
668 .collect();
669 let mut explicit_headers = HashSet::new();
670 let mut explicit_progress = HashSet::new();
671 let mut block_identities = HashMap::<u64, (Vec<u8>, u64)>::new();
672 let mut log_identities = HashSet::new();
673 let mut transaction_indexes = HashMap::<(Vec<u8>, Vec<u8>), u64>::new();
674 let mut transaction_hashes = HashMap::<(Vec<u8>, u64), Vec<u8>>::new();
675 let mut last_event_order = None;
676 let mut highest_canonical_record = None;
677 let mut highest_canonical_coverage = None;
678 for record in &data.records {
679 let scope = DeliveryScope::try_from(record.scope).map_err(|_| {
680 SessionStoreError::InvalidDelivery("data record has an unknown delivery scope")
681 })?;
682 if scope == DeliveryScope::Unspecified {
683 return Err(SessionStoreError::InvalidDelivery(
684 "data record has an unspecified delivery scope",
685 ));
686 }
687 if record.canonical_audience {
688 if !record.owner_ids.is_empty() {
689 return Err(SessionStoreError::InvalidDelivery(
690 "canonical audience also names owners",
691 ));
692 }
693 } else {
694 let mut seen = HashSet::with_capacity(record.owner_ids.len());
695 if record.owner_ids.is_empty()
696 || record.owner_ids.iter().any(|owner| {
697 owner.is_empty()
698 || !known_owners.contains(owner.as_str())
699 || !seen.insert(owner.as_str())
700 })
701 {
702 return Err(SessionStoreError::InvalidDelivery(
703 "owner audience is empty, duplicated, or not authoritative",
704 ));
705 }
706 }
707 if scope == DeliveryScope::OwnerCatchup && record.canonical_audience {
708 return Err(SessionStoreError::InvalidDelivery(
709 "owner catch-up cannot use canonical broadcast audience",
710 ));
711 }
712 let event = record
713 .event
714 .as_ref()
715 .and_then(|event| event.event.as_ref())
716 .ok_or(SessionStoreError::InvalidDelivery(
717 "data record is missing its chain event",
718 ))?;
719 let event_order = match event {
720 chain_event::Event::BlockHeader(header) => (
721 header.block.as_ref().map_or(0, |block| block.number),
722 0_u8,
723 0,
724 0,
725 ),
726 chain_event::Event::Log(log) => {
727 (log.block_number, 1_u8, log.transaction_index, log.log_index)
728 }
729 chain_event::Event::BlockProgress(progress) => (
730 progress.block.as_ref().map_or(0, |block| block.number),
731 2_u8,
732 0,
733 0,
734 ),
735 };
736 if scope != DeliveryScope::OwnerCatchup {
737 highest_canonical_record = Some(
738 highest_canonical_record
739 .map_or(event_order.0, |known: u64| known.max(event_order.0)),
740 );
741 if matches!(
742 event,
743 chain_event::Event::BlockHeader(_) | chain_event::Event::BlockProgress(_)
744 ) {
745 highest_canonical_coverage = Some(
746 highest_canonical_coverage
747 .map_or(event_order.0, |known: u64| known.max(event_order.0)),
748 );
749 }
750 }
751 if last_event_order.is_some_and(|previous| event_order < previous) {
752 return Err(SessionStoreError::InvalidDelivery(
753 "data records are not in canonical event order",
754 ));
755 }
756 last_event_order = Some(event_order);
757 match event {
758 chain_event::Event::Log(log) => {
759 if log.address.len() != 20
760 || log.block_hash.len() != 32
761 || log.transaction_hash.len() != 32
762 || log.topics.len() > 4
763 || log.topics.iter().any(|topic| topic.len() != 32)
764 {
765 return Err(SessionStoreError::InvalidDelivery(
766 "log record has an invalid address, hash, or topic shape",
767 ));
768 }
769 if !log_identities.insert((log.block_hash.clone(), log.log_index)) {
770 return Err(SessionStoreError::InvalidDelivery(
771 "delivery contains the same log more than once",
772 ));
773 }
774 if transaction_indexes
775 .insert(
776 (log.block_hash.clone(), log.transaction_hash.clone()),
777 log.transaction_index,
778 )
779 .is_some_and(|known| known != log.transaction_index)
780 || transaction_hashes
781 .insert(
782 (log.block_hash.clone(), log.transaction_index),
783 log.transaction_hash.clone(),
784 )
785 .is_some_and(|known| known != log.transaction_hash)
786 {
787 return Err(SessionStoreError::InvalidDelivery(
788 "logs disagree on transaction hash/index identity within a block",
789 ));
790 }
791 validate_block_identity(
792 &mut block_identities,
793 log.block_number,
794 &log.block_hash,
795 log.block_timestamp,
796 )?;
797 }
798 chain_event::Event::BlockHeader(header) => {
799 let block = header
800 .block
801 .as_ref()
802 .ok_or(SessionStoreError::InvalidDelivery(
803 "block header reference is missing",
804 ))?;
805 validate_block_ref(block)?;
806 if header.consensus_header_rlp.is_empty()
807 || header.total_difficulty.len() > 32
808 || header.size.len() > 32
809 {
810 return Err(SessionStoreError::InvalidDelivery(
811 "block header encoding or quantity width is invalid",
812 ));
813 }
814 if !explicit_headers.insert(block.number) {
815 return Err(SessionStoreError::InvalidDelivery(
816 "delivery contains more than one full header record at a height",
817 ));
818 }
819 validate_block_identity(
820 &mut block_identities,
821 block.number,
822 &block.hash,
823 block.timestamp,
824 )?;
825 validate_consensus_header(&header.consensus_header_rlp, block)?;
826 }
827 chain_event::Event::BlockProgress(progress) => {
828 let block = progress
829 .block
830 .as_ref()
831 .ok_or(SessionStoreError::InvalidDelivery(
832 "block progress reference is missing",
833 ))?;
834 validate_block_ref(block)?;
835 if !explicit_progress.insert(block.number) {
836 return Err(SessionStoreError::InvalidDelivery(
837 "delivery contains more than one compact progress record at a height",
838 ));
839 }
840 validate_block_identity(
841 &mut block_identities,
842 block.number,
843 &block.hash,
844 block.timestamp,
845 )?;
846 }
847 }
848 if scope == DeliveryScope::OwnerCatchup
849 && matches!(event, chain_event::Event::BlockProgress(_))
850 {
851 return Err(SessionStoreError::InvalidDelivery(
852 "owner catch-up cannot advance canonical block progress",
853 ));
854 }
855 }
856 if highest_canonical_record
857 .zip(highest_canonical_coverage)
858 .is_none_or(|(record, coverage)| coverage < record)
859 && highest_canonical_record.is_some()
860 {
861 return Err(SessionStoreError::InvalidDelivery(
862 "canonical data is not certified by a final block identity at or above every canonical record",
863 ));
864 }
865 Ok(())
866}
867
868fn validate_delivery_progress(
869 acknowledged_cursor: Option<&Cursor>,
870 desired_state: &ApplyDesiredState,
871 delivery: &Delivery,
872) -> Result<(), SessionStoreError> {
873 let cursor = delivery
874 .cursor
875 .as_ref()
876 .ok_or(SessionStoreError::InvalidDelivery(
877 "delivery cursor is missing",
878 ))?;
879 let payload = delivery
880 .payload
881 .as_ref()
882 .ok_or(SessionStoreError::InvalidDelivery(
883 "delivery payload is missing",
884 ))?;
885 let is_reorg = matches!(payload, delivery::Payload::Reorg(_));
886 let is_activation = is_exact_activation(acknowledged_cursor, desired_state, delivery);
887 validate_owner_backfill_activation_boundary(
888 acknowledged_cursor,
889 desired_state,
890 cursor,
891 is_activation,
892 )?;
893 if !is_reorg
894 && acknowledged_cursor.is_some_and(|acknowledged| {
895 (cursor.next_block < acknowledged.next_block && !is_activation)
896 || canonical_head_regresses_or_changes(acknowledged, cursor)
897 })
898 {
899 return Err(SessionStoreError::InvalidDelivery(
900 "non-reorg delivery cursor regresses canonical progress",
901 ));
902 }
903 if let delivery::Payload::Reorg(reorg) = payload {
904 let ancestor = reorg
905 .common_ancestor
906 .as_ref()
907 .ok_or(SessionStoreError::InvalidDelivery(
908 "reorg is missing its common ancestor",
909 ))?;
910 let old_tip = reorg
911 .old_tip
912 .as_ref()
913 .ok_or(SessionStoreError::InvalidDelivery(
914 "reorg is missing its old tip",
915 ))?;
916 let new_tip = reorg
917 .new_tip
918 .as_ref()
919 .ok_or(SessionStoreError::InvalidDelivery(
920 "reorg is missing its new tip",
921 ))?;
922 if acknowledged_cursor.and_then(|cursor| cursor.canonical_head.as_ref()) != Some(old_tip)
923 || old_tip.number <= ancestor.number
924 || new_tip.number <= ancestor.number
925 || ancestor.number.checked_add(1) != Some(cursor.next_block)
926 {
927 return Err(SessionStoreError::InvalidDelivery(
928 "reorg ancestry, prior tip, or cursor successor is invalid",
929 ));
930 }
931 }
932
933 let declared_head = match payload {
934 delivery::Payload::Data(data) => {
935 let mut head = None;
936 let mut last_number = None;
937 for record in &data.records {
938 let scope = DeliveryScope::try_from(record.scope).map_err(|_| {
939 SessionStoreError::InvalidDelivery("data record has an unknown delivery scope")
940 })?;
941 if scope == DeliveryScope::OwnerCatchup {
942 continue;
943 }
944 let event = record
945 .event
946 .as_ref()
947 .and_then(|event| event.event.as_ref())
948 .ok_or(SessionStoreError::InvalidDelivery(
949 "data record is missing its chain event",
950 ))?;
951 let block = match event {
952 chain_event::Event::BlockHeader(header) => header.block.as_ref(),
953 chain_event::Event::BlockProgress(progress) => progress.block.as_ref(),
954 chain_event::Event::Log(_) => None,
955 };
956 if let Some(block) = block {
957 if last_number.is_some_and(|previous| block.number < previous) {
958 return Err(SessionStoreError::InvalidDelivery(
959 "canonical block records are not ordered by height",
960 ));
961 }
962 last_number = Some(block.number);
963 head = Some(block);
964 }
965 }
966 head.or_else(|| {
967 data.records
968 .iter()
969 .all(|record| record.scope == i32::from(DeliveryScope::OwnerCatchup))
970 .then(|| {
971 acknowledged_cursor
972 .and_then(|acknowledged| acknowledged.canonical_head.as_ref())
973 })
974 .flatten()
975 })
976 }
977 delivery::Payload::Reorg(reorg) => reorg.common_ancestor.as_ref(),
978 delivery::Payload::Finality(_) => {
979 acknowledged_cursor.and_then(|acknowledged| acknowledged.canonical_head.as_ref())
980 }
981 delivery::Payload::Barrier(barrier) => barrier
982 .block
983 .as_ref()
984 .or_else(|| {
985 acknowledged_cursor.and_then(|acknowledged| acknowledged.canonical_head.as_ref())
986 })
987 .or({
988 if is_activation {
992 cursor.canonical_head.as_ref()
993 } else {
994 None
995 }
996 }),
997 };
998
999 if cursor.canonical_head.as_ref() != declared_head {
1000 return Err(SessionStoreError::InvalidDelivery(
1001 "delivery cursor canonical head disagrees with its payload",
1002 ));
1003 }
1004 let cursor_is_behind_coverage = cursor
1005 .canonical_head
1006 .as_ref()
1007 .is_some_and(|head| cursor.next_block <= head.number);
1008 let is_owner_catchup_data = matches!(payload, delivery::Payload::Data(data)
1009 if data.records.iter().all(|record| {
1010 record.scope == i32::from(DeliveryScope::OwnerCatchup)
1011 }));
1012 let is_scan_progress = is_cursor_progress_barrier(delivery);
1013 let preserves_acknowledged_head = acknowledged_cursor
1014 .is_none_or(|acknowledged| cursor.canonical_head == acknowledged.canonical_head);
1015 if cursor_is_behind_coverage
1016 && !(preserves_acknowledged_head
1017 && (is_activation || is_owner_catchup_data || is_scan_progress))
1018 {
1019 return Err(SessionStoreError::InvalidDelivery(
1020 "delivery cursor next block does not follow its canonical head",
1021 ));
1022 }
1023 Ok(())
1024}
1025
1026fn validate_owner_backfill_activation_boundary(
1027 acknowledged_cursor: Option<&Cursor>,
1028 desired_state: &ApplyDesiredState,
1029 cursor: &Cursor,
1030 is_activation: bool,
1031) -> Result<(), SessionStoreError> {
1032 if is_activation {
1033 let has_open_backfill = desired_state.owners.iter().any(|owner| {
1034 owner
1035 .backfill
1036 .as_ref()
1037 .is_some_and(|backfill| backfill.to_block_excl.is_none())
1038 });
1039 if has_open_backfill && cursor.owner_backfill_activation_block.is_none() {
1040 return Err(SessionStoreError::InvalidDelivery(
1041 "open owner backfill activation is missing its portable boundary",
1042 ));
1043 }
1044 if cursor
1045 .owner_backfill_activation_block
1046 .is_some_and(|activation| activation < cursor.next_block)
1047 {
1048 return Err(SessionStoreError::InvalidDelivery(
1049 "owner backfill activation boundary precedes its scan cursor",
1050 ));
1051 }
1052 } else if acknowledged_cursor.is_some_and(|acknowledged| {
1053 acknowledged.query_revision == cursor.query_revision
1054 && acknowledged.owner_backfill_activation_block
1055 != cursor.owner_backfill_activation_block
1056 }) {
1057 return Err(SessionStoreError::InvalidDelivery(
1058 "owner backfill activation boundary changed within one revision",
1059 ));
1060 }
1061 Ok(())
1062}
1063
1064fn validate_block_identity(
1065 identities: &mut HashMap<u64, (Vec<u8>, u64)>,
1066 number: u64,
1067 hash: &[u8],
1068 timestamp: u64,
1069) -> Result<(), SessionStoreError> {
1070 if let Some((known_hash, known_timestamp)) = identities.get(&number) {
1071 if known_hash.as_slice() != hash || *known_timestamp != timestamp {
1072 return Err(SessionStoreError::InvalidDelivery(
1073 "records for one block height disagree on hash or timestamp",
1074 ));
1075 }
1076 } else {
1077 identities.insert(number, (hash.to_vec(), timestamp));
1078 }
1079 Ok(())
1080}
1081
1082fn validate_consensus_header(encoded: &[u8], block: &BlockRef) -> Result<(), SessionStoreError> {
1083 let mut remaining = encoded;
1084 let header = ConsensusHeader::decode(&mut remaining).map_err(|_| {
1085 SessionStoreError::InvalidDelivery("block header contains invalid consensus RLP")
1086 })?;
1087 if !remaining.is_empty()
1088 || header.hash_slow().as_slice() != block.hash.as_slice()
1089 || header.number != block.number
1090 || header.parent_hash.as_slice() != block.parent_hash.as_slice()
1091 || header.timestamp != block.timestamp
1092 {
1093 return Err(SessionStoreError::InvalidDelivery(
1094 "block header RLP does not match its block reference",
1095 ));
1096 }
1097 Ok(())
1098}
1099
1100fn validate_block_ref(block: &BlockRef) -> Result<(), SessionStoreError> {
1101 if block.hash.len() != 32 || block.parent_hash.len() != 32 {
1102 return Err(SessionStoreError::InvalidDelivery(
1103 "block reference hashes must be 32 bytes",
1104 ));
1105 }
1106 Ok(())
1107}
1108
1109fn validate_reorg_shape(
1110 ancestor: &BlockRef,
1111 old_tip: &BlockRef,
1112 new_tip: &BlockRef,
1113) -> Result<(), SessionStoreError> {
1114 let direct_old_parent_mismatch =
1115 old_tip.number == ancestor.number.saturating_add(1) && old_tip.parent_hash != ancestor.hash;
1116 let direct_new_parent_mismatch =
1117 new_tip.number == ancestor.number.saturating_add(1) && new_tip.parent_hash != ancestor.hash;
1118 if old_tip.number <= ancestor.number
1119 || new_tip.number <= ancestor.number
1120 || old_tip.timestamp <= ancestor.timestamp
1121 || new_tip.timestamp <= ancestor.timestamp
1122 || old_tip.hash == new_tip.hash
1123 || old_tip.hash == ancestor.hash
1124 || new_tip.hash == ancestor.hash
1125 || direct_old_parent_mismatch
1126 || direct_new_parent_mismatch
1127 {
1128 return Err(SessionStoreError::InvalidDelivery(
1129 "reorg tips do not describe two distinct descendant branches",
1130 ));
1131 }
1132 Ok(())
1133}
1134
1135fn validate_persisted_session(
1136 session_id: &str,
1137 chain_id: u64,
1138 revision: u64,
1139 activation_sequence: u64,
1140 persisted: &PersistedSession,
1141) -> Result<(), SessionStoreError> {
1142 let desired_state = match persisted.desired_state.as_ref() {
1143 Some(desired) => {
1144 validate_desired_state(desired)?;
1145 if desired.session_id != session_id
1146 || desired.chain_id != chain_id
1147 || desired.new_revision != revision
1148 {
1149 return Err(SessionStoreError::InvalidDelivery(
1150 "durable desired state does not match its row identity or revision",
1151 ));
1152 }
1153 desired
1154 }
1155 None if revision == 0
1156 && persisted.acknowledged_cursor.is_none()
1157 && persisted.runtime_checkpoint_cursor.is_none()
1158 && persisted.pending_delivery.is_none()
1159 && persisted.expected_reorg_tip.is_none() =>
1160 {
1161 return Ok(());
1162 }
1163 None => {
1164 return Err(SessionStoreError::InvalidDelivery(
1165 "durable revision is missing its desired state",
1166 ));
1167 }
1168 };
1169
1170 if let Some(cursor) = persisted.acknowledged_cursor.as_ref() {
1171 if cursor.chain_id != chain_id
1172 || cursor.query_revision > revision
1173 || cursor.batch_sequence == 0
1174 {
1175 return Err(SessionStoreError::InvalidDelivery(
1176 "durable acknowledged cursor does not match its row",
1177 ));
1178 }
1179 if let Some(head) = cursor.canonical_head.as_ref() {
1180 validate_block_ref(head)?;
1181 }
1182 }
1183 if let Some(runtime_cursor) = persisted.runtime_checkpoint_cursor.as_ref() {
1184 if runtime_cursor.chain_id != chain_id
1185 || runtime_cursor.query_revision > revision
1186 || runtime_cursor.batch_sequence == 0
1187 {
1188 return Err(SessionStoreError::InvalidDelivery(
1189 "durable runtime checkpoint cursor does not match its row",
1190 ));
1191 }
1192 if let Some(head) = runtime_cursor.canonical_head.as_ref() {
1193 validate_block_ref(head)?;
1194 }
1195 let transport_cursor =
1196 persisted
1197 .acknowledged_cursor
1198 .as_ref()
1199 .ok_or(SessionStoreError::InvalidDelivery(
1200 "runtime checkpoint cursor exists without transport acknowledgement",
1201 ))?;
1202 if runtime_cursor.batch_sequence > transport_cursor.batch_sequence
1203 || (runtime_cursor.batch_sequence == transport_cursor.batch_sequence
1204 && runtime_cursor != transport_cursor)
1205 {
1206 return Err(SessionStoreError::InvalidDelivery(
1207 "runtime checkpoint cursor is ahead of or conflicts with transport authority",
1208 ));
1209 }
1210 }
1211 if let Some(expected_tip) = persisted.expected_reorg_tip.as_ref() {
1212 validate_block_ref(expected_tip)?;
1213 if persisted
1214 .acknowledged_cursor
1215 .as_ref()
1216 .and_then(|cursor| cursor.canonical_head.as_ref())
1217 .is_some_and(|head| head.number >= expected_tip.number)
1218 {
1219 return Err(SessionStoreError::InvalidDelivery(
1220 "durable reorg replacement promise is at or behind acknowledged canonical progress",
1221 ));
1222 }
1223 }
1224 if let Some(pending) = persisted.pending_delivery.as_ref() {
1225 let cursor = pending
1226 .cursor
1227 .as_ref()
1228 .ok_or(SessionStoreError::InvalidDelivery(
1229 "durable pending delivery is missing its cursor",
1230 ))?;
1231 let predecessor = persisted
1232 .acknowledged_cursor
1233 .as_ref()
1234 .map_or(Ok(1), |cursor| {
1235 cursor
1236 .batch_sequence
1237 .checked_add(1)
1238 .ok_or(SessionStoreError::SequenceOverflow)
1239 })?;
1240 if pending.session_id != session_id
1241 || pending.query_revision != revision
1242 || pending.sequence != predecessor
1243 || pending.sequence != cursor.batch_sequence
1244 || pending.delivery_token != pending.sequence.to_be_bytes()
1245 || pending.payload.is_none()
1246 || cursor.chain_id != chain_id
1247 || cursor.query_revision != revision
1248 {
1249 return Err(SessionStoreError::InvalidDelivery(
1250 "durable pending delivery violates its row invariants",
1251 ));
1252 }
1253 validate_delivery_size(pending, MAX_MESSAGE_SIZE_BYTES)?;
1254 validate_delivery_payload(
1255 persisted
1256 .desired_state
1257 .as_ref()
1258 .expect("validated desired state exists"),
1259 pending,
1260 )?;
1261 validate_delivery_progress(
1262 persisted.acknowledged_cursor.as_ref(),
1263 desired_state,
1264 pending,
1265 )?;
1266 if persisted
1267 .expected_reorg_tip
1268 .as_ref()
1269 .is_some_and(|expected| {
1270 !is_activation_delivery(pending, desired_state.new_revision)
1271 && !delivery_certifies_reorg_tip(pending, expected)
1272 })
1273 {
1274 return Err(SessionStoreError::InvalidDelivery(
1275 "durable pending delivery does not certify the promised reorg replacement tip",
1276 ));
1277 }
1278 if persisted.expected_reorg_tip.is_some()
1279 && matches!(pending.payload, Some(delivery::Payload::Reorg(_)))
1280 {
1281 return Err(SessionStoreError::InvalidDelivery(
1282 "durable session contains a second reorg before its promised replacement",
1283 ));
1284 }
1285 }
1286 let acknowledged_sequence = persisted
1287 .acknowledged_cursor
1288 .as_ref()
1289 .map_or(0, |cursor| cursor.batch_sequence);
1290 let current_sequence = persisted
1291 .pending_delivery
1292 .as_ref()
1293 .map_or(acknowledged_sequence, |delivery| delivery.sequence);
1294 if activation_sequence > current_sequence {
1295 return Err(SessionStoreError::InvalidDelivery(
1296 "durable activation sequence is ahead of session sequence",
1297 ));
1298 }
1299 let pending_is_activation = persisted
1300 .pending_delivery
1301 .as_ref()
1302 .is_some_and(|delivery| is_activation_delivery(delivery, desired_state.new_revision));
1303 if activation_sequence == 0 {
1304 if !pending_is_activation
1308 && persisted
1309 .acknowledged_cursor
1310 .as_ref()
1311 .is_none_or(|cursor| cursor.query_revision != revision)
1312 {
1313 return Err(SessionStoreError::InvalidDelivery(
1314 "legacy durable desired state has no acknowledged or pending activation",
1315 ));
1316 }
1317 } else if acknowledged_sequence < activation_sequence {
1318 if persisted.pending_delivery.as_ref().is_none_or(|delivery| {
1319 delivery.sequence != activation_sequence || !pending_is_activation
1320 }) {
1321 return Err(SessionStoreError::InvalidDelivery(
1322 "durable desired state is missing its pending activation barrier",
1323 ));
1324 }
1325 } else if persisted
1326 .acknowledged_cursor
1327 .as_ref()
1328 .is_none_or(|cursor| cursor.query_revision != revision)
1329 {
1330 return Err(SessionStoreError::InvalidDelivery(
1331 "durable desired state is not acknowledged at its current revision",
1332 ));
1333 }
1334 Ok(())
1335}
1336
1337fn is_activation_delivery(delivery: &Delivery, revision: u64) -> bool {
1338 if delivery.cursor.is_none() {
1339 return false;
1340 }
1341 matches!(
1342 delivery.payload.as_ref(),
1343 Some(delivery::Payload::Barrier(barrier))
1344 if barrier.id == format!("desired-state:{revision}").as_bytes()
1345 && barrier.block.is_none()
1346 )
1347}
1348
1349fn is_exact_activation(
1350 acknowledged_cursor: Option<&Cursor>,
1351 desired_state: &ApplyDesiredState,
1352 delivery: &Delivery,
1353) -> bool {
1354 let expected_head = acknowledged_cursor
1355 .and_then(|cursor| cursor.canonical_head.clone())
1356 .or_else(|| {
1357 desired_state
1358 .owners
1359 .iter()
1360 .find(|owner| owner.canonical)
1361 .and_then(|owner| owner.backfill.as_ref())
1362 .and_then(|backfill| backfill.retained_baseline.clone())
1363 });
1364 is_activation_delivery(delivery, desired_state.new_revision)
1365 && desired_state.expected_revision
1366 == acknowledged_cursor.map_or(0, |cursor| cursor.query_revision)
1367 && delivery.query_revision == desired_state.new_revision
1368 && delivery
1369 .cursor
1370 .as_ref()
1371 .is_some_and(|cursor| cursor.canonical_head == expected_head)
1372}
1373
1374fn is_cursor_progress_barrier(delivery: &Delivery) -> bool {
1375 let Some(cursor) = delivery.cursor.as_ref() else {
1376 return false;
1377 };
1378 matches!(
1379 delivery.payload.as_ref(),
1380 Some(delivery::Payload::Barrier(barrier))
1381 if barrier.block.is_none()
1382 && barrier.id
1383 == format!(
1384 "source-progress:{}:{}",
1385 delivery.query_revision, cursor.next_block
1386 )
1387 .as_bytes()
1388 )
1389}
1390
1391fn delivery_certifies_reorg_tip(delivery: &Delivery, expected_tip: &BlockRef) -> bool {
1392 let Some(cursor) = delivery.cursor.as_ref() else {
1393 return false;
1394 };
1395 match delivery.payload.as_ref() {
1396 Some(delivery::Payload::Data(data)) => {
1397 let mut canonical_blocks = BTreeMap::<u64, &BlockRef>::new();
1404 for record in &data.records {
1405 let Ok(scope) = DeliveryScope::try_from(record.scope) else {
1406 return false;
1407 };
1408 if scope == DeliveryScope::OwnerCatchup {
1409 continue;
1410 }
1411 let Some(event) = record.event.as_ref().and_then(|event| event.event.as_ref())
1412 else {
1413 return false;
1414 };
1415 let block = match event {
1416 chain_event::Event::BlockHeader(header) => header.block.as_ref(),
1417 chain_event::Event::BlockProgress(progress) => progress.block.as_ref(),
1418 chain_event::Event::Log(_) => None,
1419 };
1420 if let Some(block) = block
1421 && canonical_blocks
1422 .insert(block.number, block)
1423 .is_some_and(|known| known != block)
1424 {
1425 return false;
1426 }
1427 }
1428 if canonical_blocks.get(&expected_tip.number).copied() != Some(expected_tip) {
1429 return false;
1430 }
1431 let mut suffix = canonical_blocks
1432 .range(expected_tip.number..)
1433 .map(|(_, block)| *block);
1434 let Some(mut previous) = suffix.next() else {
1435 return false;
1436 };
1437 for block in suffix {
1438 if previous.number.checked_add(1) != Some(block.number)
1439 || block.parent_hash != previous.hash
1440 {
1441 return false;
1442 }
1443 previous = block;
1444 }
1445 cursor.canonical_head.as_ref() == Some(previous)
1446 && previous
1447 .number
1448 .checked_add(1)
1449 .is_some_and(|successor| cursor.next_block == successor)
1450 }
1451 Some(delivery::Payload::Barrier(barrier)) => {
1452 barrier.block.as_ref() == Some(expected_tip)
1453 && cursor.canonical_head.as_ref() == Some(expected_tip)
1454 && expected_tip
1455 .number
1456 .checked_add(1)
1457 .is_some_and(|successor| cursor.next_block == successor)
1458 }
1459 _ => false,
1460 }
1461}
1462
1463fn expected_reorg_tip_after_ack(
1464 current: Option<&BlockRef>,
1465 pending: &Delivery,
1466) -> Result<Option<BlockRef>, SessionStoreError> {
1467 if let Some(delivery::Payload::Reorg(reorg)) = pending.payload.as_ref() {
1468 if current.is_some() {
1469 return Err(SessionStoreError::InvalidDelivery(
1470 "a second reorg cannot replace an unfulfilled replacement promise",
1471 ));
1472 }
1473 return reorg
1474 .new_tip
1475 .clone()
1476 .map(Some)
1477 .ok_or(SessionStoreError::InvalidDelivery(
1478 "reorg is missing its new tip",
1479 ));
1480 }
1481 Ok(match current {
1482 Some(expected) if delivery_certifies_reorg_tip(pending, expected) => None,
1483 Some(expected) => Some(expected.clone()),
1484 None => None,
1485 })
1486}
1487
1488fn canonical_head_regresses_or_changes(previous: &Cursor, current: &Cursor) -> bool {
1489 match (
1490 previous.canonical_head.as_ref(),
1491 current.canonical_head.as_ref(),
1492 ) {
1493 (Some(previous), Some(current)) => {
1494 current.number < previous.number
1495 || (current.number == previous.number && current != previous)
1496 }
1497 (Some(_), None) => true,
1498 _ => false,
1499 }
1500}
1501
1502fn decode_optional<M: Message + Default>(
1503 encoded: Option<Vec<u8>>,
1504 _field: &'static str,
1505) -> Result<Option<M>, SessionStoreError> {
1506 encoded
1507 .map(|encoded| M::decode(encoded.as_slice()).map_err(SessionStoreError::from))
1508 .transpose()
1509}
1510
1511fn chain_id_to_sql_integer(value: u64) -> i64 {
1517 i64::from_ne_bytes(value.to_ne_bytes())
1518}
1519
1520fn chain_id_from_sql_integer(value: i64) -> u64 {
1521 u64::from_ne_bytes(value.to_ne_bytes())
1522}
1523
1524fn sequence_to_sql_integer(value: u64) -> i64 {
1528 i64::from_ne_bytes(value.to_ne_bytes())
1529}
1530
1531fn sequence_from_sql_integer(value: i64) -> u64 {
1532 u64::from_ne_bytes(value.to_ne_bytes())
1533}
1534
1535fn to_sql_integer(value: u64, field: &'static str) -> Result<i64, SessionStoreError> {
1536 i64::try_from(value).map_err(|_| SessionStoreError::IntegerRange(field))
1537}
1538
1539fn from_sql_integer(value: i64, field: &'static str) -> Result<u64, SessionStoreError> {
1540 u64::try_from(value).map_err(|_| SessionStoreError::IntegerRange(field))
1541}
1542
1543#[derive(Debug, thiserror::Error)]
1545#[non_exhaustive]
1546pub enum SessionStoreError {
1547 #[error(transparent)]
1549 Database(#[from] rusqlite::Error),
1550 #[error(transparent)]
1552 Decode(#[from] prost::DecodeError),
1553 #[error("session database schema error: {0}")]
1555 Schema(String),
1556 #[error(transparent)]
1558 DesiredState(#[from] DesiredStateError),
1559 #[error("desired-state revision conflict: expected {expected}, committed {committed}")]
1561 RevisionConflict {
1562 expected: u64,
1564 committed: u64,
1566 },
1567 #[error("{0} exceeds SQLite integer range")]
1569 IntegerRange(&'static str),
1570 #[error("delivery sequence is exhausted")]
1572 SequenceOverflow,
1573 #[error("unknown event session")]
1575 UnknownSession,
1576 #[error("a different delivery is already pending")]
1578 PendingDelivery,
1579 #[error("persisted session limit {limit} is exhausted")]
1581 PersistedSessionLimit {
1582 limit: usize,
1584 },
1585 #[error("no delivery is awaiting acknowledgement")]
1587 NoPendingDelivery,
1588 #[error("delivery acknowledgement does not match the pending batch")]
1590 DeliveryTokenMismatch,
1591 #[error("invalid delivery: {0}")]
1593 InvalidDelivery(&'static str),
1594 #[error(
1596 "encoded delivery is {encoded_bytes} bytes, exceeding the {max_delivery_bytes}-byte limit"
1597 )]
1598 DeliveryTooLarge {
1599 encoded_bytes: usize,
1601 max_delivery_bytes: usize,
1603 },
1604}
1605
1606fn migrate_sessions_table(
1607 transaction: &rusqlite::Transaction<'_>,
1608) -> Result<(), SessionStoreError> {
1609 let columns = {
1610 let mut statement = transaction.prepare("PRAGMA table_info(sessions)")?;
1611 let columns = statement.query_map([], |row| {
1612 Ok((row.get::<_, String>(1)?, row.get::<_, i64>(5)?))
1613 })?;
1614 columns.collect::<Result<HashMap<_, _>, _>>()?
1615 };
1616 for required in ["session_id", "chain_id"] {
1617 if !columns.contains_key(required) {
1618 return Err(SessionStoreError::Schema(format!(
1619 "sessions table is missing required `{required}` column"
1620 )));
1621 }
1622 }
1623 if columns.get("session_id") != Some(&1)
1624 || columns.get("chain_id") != Some(&2)
1625 || columns.values().any(|position| *position > 2)
1626 {
1627 return Err(SessionStoreError::Schema(
1628 "sessions table must use PRIMARY KEY (session_id, chain_id)".into(),
1629 ));
1630 }
1631 let had_runtime_checkpoint_cursor = columns.contains_key("runtime_checkpoint_cursor");
1632 let additions = [
1633 ("revision", "INTEGER NOT NULL DEFAULT 0"),
1634 ("desired_state", "BLOB"),
1635 ("acknowledged_cursor", "BLOB"),
1636 ("runtime_checkpoint_cursor", "BLOB"),
1637 ("pending_delivery", "BLOB"),
1638 ("activation_sequence", "INTEGER NOT NULL DEFAULT 0"),
1639 ("expected_reorg_tip", "BLOB"),
1640 ];
1641 for (column, declaration) in additions {
1642 if !columns.contains_key(column) {
1643 transaction.execute_batch(&format!(
1644 "ALTER TABLE sessions ADD COLUMN {column} {declaration};"
1645 ))?;
1646 }
1647 }
1648 if columns.contains_key("pending_batch") && !columns.contains_key("pending_delivery") {
1649 transaction.execute(
1650 "UPDATE sessions SET pending_delivery = pending_batch WHERE pending_delivery IS NULL",
1651 [],
1652 )?;
1653 }
1654 if !had_runtime_checkpoint_cursor {
1655 transaction.execute(
1659 "UPDATE sessions
1660 SET runtime_checkpoint_cursor = acknowledged_cursor
1661 WHERE runtime_checkpoint_cursor IS NULL",
1662 [],
1663 )?;
1664 }
1665 Ok(())
1666}