Skip to main content

sui_rpc_api/ledger_history/
checkpoint_positions.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Start and end positions inside the checkpoints at the edges of a `ListTransactions` /
5//! `ListEvents` request's checkpoint window.
6//!
7//! A position is a gap between items, named by checkpoint-relative offsets: `(checkpoint,
8//! transaction_index[, event_index])` is the gap just before that transaction (or that event of
9//! it). The start position `(start_checkpoint, start_transaction_index[, start_event_index])` is
10//! the first position a scan admits. The end position is exclusive and lies in the window's last
11//! checkpoint, `(end_checkpoint - 1, end_transaction_index[, end_event_index])`, so a server that
12//! ignores it returns a superset. Offsets past the end of their checkpoint (or transaction) clamp
13//! to its end instead of failing: the gap after a checkpoint's last item is `(C, n)` for its
14//! transaction count `n`, which clients cannot know.
15
16use std::ops::Range;
17
18use sui_rpc::proto::sui::rpc::v2::ListEventsRequest;
19use sui_rpc::proto::sui::rpc::v2::ListTransactionsRequest;
20
21use crate::ErrorReason;
22use crate::RpcError;
23use crate::ledger_history::cursor::LedgerPoint;
24use crate::ledger_history::query_options::IntraTxCoordinate;
25use crate::ledger_history::query_options::LedgerWindow;
26use crate::ledger_history::query_options::ScanWindow;
27use crate::proto::google::rpc::bad_request::FieldViolation;
28
29/// A request's start and end positions within its checkpoint window's edge checkpoints. An unset
30/// position leaves its edge at the checkpoint boundary.
31#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
32pub struct CheckpointPositions {
33    /// Where the scan starts in `start_checkpoint` (inclusive).
34    start: Option<PositionInCheckpoint>,
35    /// Where the scan ends in `end_checkpoint - 1` (exclusive).
36    end: Option<PositionInCheckpoint>,
37    /// The request's `start_checkpoint`.
38    start_checkpoint: Option<u64>,
39    /// The request's `end_checkpoint`, set whenever `end` is.
40    end_checkpoint: Option<u64>,
41}
42
43/// A gap between items inside one checkpoint: just before the event at `event_index` of the
44/// transaction at `transaction_index`. Event index 0 is the gap before the whole transaction.
45#[derive(Clone, Copy, Debug, Eq, PartialEq)]
46struct PositionInCheckpoint {
47    transaction_index: u64,
48    event_index: u32,
49}
50
51impl CheckpointPositions {
52    pub fn from_transactions_request(request: &ListTransactionsRequest) -> Result<Self, RpcError> {
53        type Request = ListTransactionsRequest;
54        require_field_when_set(
55            request.start_checkpoint,
56            Request::START_CHECKPOINT_FIELD.name,
57            request.start_transaction_index,
58            Request::START_TRANSACTION_INDEX_FIELD.name,
59        )?;
60        require_field_when_set(
61            request.end_checkpoint,
62            Request::END_CHECKPOINT_FIELD.name,
63            request.end_transaction_index,
64            Request::END_TRANSACTION_INDEX_FIELD.name,
65        )?;
66        Ok(Self {
67            start: PositionInCheckpoint::from_fields(request.start_transaction_index, None),
68            end: PositionInCheckpoint::from_fields(request.end_transaction_index, None),
69            start_checkpoint: request.start_checkpoint,
70            end_checkpoint: request.end_checkpoint,
71        })
72    }
73
74    pub fn from_events_request(request: &ListEventsRequest) -> Result<Self, RpcError> {
75        type Request = ListEventsRequest;
76        require_field_when_set(
77            request.start_checkpoint,
78            Request::START_CHECKPOINT_FIELD.name,
79            request.start_transaction_index,
80            Request::START_TRANSACTION_INDEX_FIELD.name,
81        )?;
82        require_field_when_set(
83            request.start_transaction_index,
84            Request::START_TRANSACTION_INDEX_FIELD.name,
85            request.start_event_index,
86            Request::START_EVENT_INDEX_FIELD.name,
87        )?;
88        require_field_when_set(
89            request.end_checkpoint,
90            Request::END_CHECKPOINT_FIELD.name,
91            request.end_transaction_index,
92            Request::END_TRANSACTION_INDEX_FIELD.name,
93        )?;
94        require_field_when_set(
95            request.end_transaction_index,
96            Request::END_TRANSACTION_INDEX_FIELD.name,
97            request.end_event_index,
98            Request::END_EVENT_INDEX_FIELD.name,
99        )?;
100        Ok(Self {
101            start: PositionInCheckpoint::from_fields(
102                request.start_transaction_index,
103                request.start_event_index,
104            ),
105            end: PositionInCheckpoint::from_fields(
106                request.end_transaction_index,
107                request.end_event_index,
108            ),
109            start_checkpoint: request.start_checkpoint,
110            end_checkpoint: request.end_checkpoint,
111        })
112    }
113
114    /// A superset of the checkpoints whose first transaction's `tx_seq`
115    /// [`Self::transaction_window`] and [`Self::event_window`] read for the checkpoint `window`,
116    /// so a backend can fetch them all in one read.
117    pub fn boundary_checkpoints(&self, window: &Range<u64>) -> Vec<u64> {
118        let mut checkpoints = vec![window.start];
119        if !window.is_empty() {
120            checkpoints.push(window.end);
121            if self.start.is_some() {
122                checkpoints.push(window.start + 1);
123            }
124            if self.end.is_some() {
125                checkpoints.push(window.end - 1);
126            }
127        }
128        checkpoints
129    }
130
131    /// The `tx_seq` scan window for the checkpoint `window` (the request's checkpoint bounds
132    /// resolved against this server's tip), narrowed to these positions. `boundary(c)` returns
133    /// the `tx_seq` of checkpoint `c`'s first transaction, which is one past the last transaction
134    /// of checkpoint `c - 1`.
135    pub fn transaction_window(
136        &self,
137        window: &Range<u64>,
138        boundary: impl FnMut(u64) -> Result<u64, RpcError>,
139    ) -> Result<ScanWindow<u64>, RpcError> {
140        self.narrow(window, boundary, |tx_seq, _event_index| tx_seq)
141    }
142
143    /// The event-coordinate scan window for the checkpoint `window`, narrowed to these positions.
144    /// See [`Self::transaction_window`] for `boundary`. An event index past its transaction's
145    /// events needs no clamp: as a start it admits the next transaction's events, and as an end
146    /// it admits all of its own transaction's.
147    pub fn event_window(
148        &self,
149        window: &Range<u64>,
150        boundary: impl FnMut(u64) -> Result<u64, RpcError>,
151    ) -> Result<ScanWindow<IntraTxCoordinate>, RpcError> {
152        self.narrow(window, boundary, |tx_seq, index| IntraTxCoordinate {
153            tx_seq,
154            index,
155        })
156    }
157
158    fn narrow<P: Copy + Eq>(
159        &self,
160        window: &Range<u64>,
161        mut boundary: impl FnMut(u64) -> Result<u64, RpcError>,
162        position: impl Fn(u64, u32) -> P,
163    ) -> Result<ScanWindow<P>, RpcError> {
164        let window_start = boundary(window.start)?;
165        let start_of_tx = |tx_seq| position(tx_seq, 0);
166        if window.is_empty() {
167            // A window without a checkpoint ends where the request's own fields name; its scan
168            // edge is the start of the window's checkpoint.
169            let edge = start_of_tx(window_start);
170            let edge_point = LedgerPoint::checkpoint_start(window.start);
171            return Ok(ScanWindow::whole_checkpoints(
172                edge..edge,
173                LedgerWindow {
174                    start: edge_point,
175                    end: edge_point,
176                    requested: Some((
177                        self.requested_start(),
178                        self.requested_end().unwrap_or(edge_point),
179                    )),
180                },
181            ));
182        }
183        let window_end = boundary(window.end)?;
184
185        // A non-empty window starts at the requested `start_checkpoint`. A transaction index past
186        // that checkpoint's end starts at the next checkpoint's first transaction, and drops the
187        // event index, which names an event of a transaction past the checkpoint.
188        let (start, ledger_start) = match self.start {
189            None => (
190                start_of_tx(window_start),
191                LedgerPoint::checkpoint_start(window.start),
192            ),
193            Some(start) => {
194                let next_checkpoint = boundary(window.start + 1)?;
195                let tx_seq = window_start.saturating_add(start.transaction_index);
196                if tx_seq < next_checkpoint {
197                    (
198                        position(tx_seq, start.event_index),
199                        start.point(window.start),
200                    )
201                } else {
202                    (
203                        start_of_tx(next_checkpoint),
204                        LedgerPoint::checkpoint_start(window.start + 1),
205                    )
206                }
207            }
208        };
209
210        // The end position applies only while the window still ends at the requested
211        // `end_checkpoint`: an `end_checkpoint` past this server's tip leaves the position's
212        // checkpoint unindexed, so the window ends at the tip instead. A transaction index past
213        // the last checkpoint's end ends after that whole checkpoint.
214        let (end, ledger_end) = match self.end.filter(|_| self.end_checkpoint == Some(window.end)) {
215            None => (
216                start_of_tx(window_end),
217                LedgerPoint::checkpoint_start(window.end),
218            ),
219            Some(end) => {
220                let tx_seq = boundary(window.end - 1)?.saturating_add(end.transaction_index);
221                if tx_seq < window_end {
222                    (position(tx_seq, end.event_index), end.point(window.end - 1))
223                } else {
224                    (
225                        start_of_tx(window_end),
226                        LedgerPoint::checkpoint_start(window.end),
227                    )
228                }
229            }
230        };
231
232        Ok(ScanWindow {
233            start_cuts_checkpoint: start != start_of_tx(window_start),
234            end_cuts_checkpoint: end != start_of_tx(window_end),
235            range: start..end,
236            ledger: LedgerWindow {
237                start: ledger_start,
238                end: ledger_end,
239                requested: None,
240            },
241        })
242    }
243
244    /// The point the request's start fields name.
245    fn requested_start(&self) -> LedgerPoint {
246        let checkpoint = self.start_checkpoint.unwrap_or(0);
247        match self.start {
248            Some(start) => start.point(checkpoint),
249            None => LedgerPoint::checkpoint_start(checkpoint),
250        }
251    }
252
253    /// The point the request's end fields name, if it set `end_checkpoint`: the end position in
254    /// `end_checkpoint - 1`, or the start of `end_checkpoint`.
255    fn requested_end(&self) -> Option<LedgerPoint> {
256        let end_checkpoint = self.end_checkpoint?;
257        Some(match (self.end, end_checkpoint.checked_sub(1)) {
258            (Some(end), Some(last_checkpoint)) => end.point(last_checkpoint),
259            _ => LedgerPoint::checkpoint_start(end_checkpoint),
260        })
261    }
262}
263
264impl PositionInCheckpoint {
265    /// The position a request's index fields name, or `None` when its transaction index is
266    /// unset. An unset event index is the gap before the whole transaction.
267    fn from_fields(transaction_index: Option<u64>, event_index: Option<u32>) -> Option<Self> {
268        transaction_index.map(|transaction_index| Self {
269            transaction_index,
270            event_index: event_index.unwrap_or(0),
271        })
272    }
273
274    /// This position in `checkpoint`, in ledger coordinates.
275    fn point(self, checkpoint: u64) -> LedgerPoint {
276        LedgerPoint::event(checkpoint, self.transaction_index, self.event_index)
277    }
278}
279
280/// `InvalidArgument` when `when_set` is set but `required` is not, for a field that only means
281/// something together with another: an index with the checkpoint or transaction it indexes into.
282fn require_field_when_set<R, W>(
283    required: Option<R>,
284    required_name: &'static str,
285    when_set: Option<W>,
286    when_set_name: &'static str,
287) -> Result<(), RpcError> {
288    if when_set.is_some() && required.is_none() {
289        return Err(FieldViolation::new(required_name)
290            .with_description(format!(
291                "{required_name} is required when {when_set_name} is set"
292            ))
293            .with_reason(ErrorReason::FieldMissing)
294            .into());
295    }
296    Ok(())
297}
298
299#[cfg(test)]
300mod tests {
301    use sui_rpc::proto::sui::rpc::v2::Ordering as ProtoOrdering;
302    use sui_rpc::proto::sui::rpc::v2::QueryOptions as ProtoQueryOptions;
303
304    use crate::ledger_history::cursor::CursorKind;
305    use crate::ledger_history::cursor::CursorToken;
306    use crate::ledger_history::cursor::Position;
307    use crate::ledger_history::query_options::Ordering;
308    use crate::ledger_history::query_options::QueryOptions;
309    use crate::ledger_history::query_options::RangeExhaustion;
310    use crate::ledger_history::query_options::ResolvedCheckpointRange;
311    use crate::ledger_history::query_options::ResolvedScan;
312
313    use super::*;
314
315    /// The model ledger's first transaction of each checkpoint, and the tip. Checkpoint 0 holds
316    /// transactions 0..3, checkpoint 1 none, checkpoint 2 3..7, checkpoint 3 7..9, and checkpoint
317    /// 4 9..14.
318    const BOUNDARIES: [u64; 6] = [0, 3, 3, 7, 9, 14];
319    const TIP: u64 = 5;
320
321    const ORDERINGS: [Ordering; 2] = [Ordering::Ascending, Ordering::Descending];
322
323    fn boundary(checkpoint: u64) -> Result<u64, RpcError> {
324        Ok(BOUNDARIES[checkpoint as usize])
325    }
326
327    /// A request over checkpoints `[start, end)` with the given start and end positions, each a
328    /// `(transaction_index, event_index)`.
329    fn events_request(
330        start: Option<u64>,
331        end: Option<u64>,
332        start_position: Option<(u64, Option<u32>)>,
333        end_position: Option<(u64, Option<u32>)>,
334    ) -> ListEventsRequest {
335        let mut request = ListEventsRequest::default();
336        request.start_checkpoint = start;
337        request.end_checkpoint = end;
338        request.start_transaction_index = start_position.map(|(tx, _)| tx);
339        request.start_event_index = start_position.and_then(|(_, event)| event);
340        request.end_transaction_index = end_position.map(|(tx, _)| tx);
341        request.end_event_index = end_position.and_then(|(_, event)| event);
342        request
343    }
344
345    fn transactions_request(
346        start: Option<u64>,
347        end: Option<u64>,
348        start_transaction_index: Option<u64>,
349        end_transaction_index: Option<u64>,
350    ) -> ListTransactionsRequest {
351        let mut request = ListTransactionsRequest::default();
352        request.start_checkpoint = start;
353        request.end_checkpoint = end;
354        request.start_transaction_index = start_transaction_index;
355        request.end_transaction_index = end_transaction_index;
356        request
357    }
358
359    /// Boundary cursors at `after` and `before`.
360    fn options(
361        ordering: Ordering,
362        after: Option<Position>,
363        before: Option<Position>,
364    ) -> QueryOptions {
365        let mut proto = ProtoQueryOptions::default();
366        if ordering == Ordering::Descending {
367            proto.ordering = Some(ProtoOrdering::Descending as i32);
368        }
369        proto.after = after.map(|position| CursorToken::boundary(position).encode());
370        proto.before = before.map(|position| CursorToken::boundary(position).encode());
371        QueryOptions::transactions_from_proto(Some(&proto), 100, 100).unwrap()
372    }
373
374    /// A cursor position at transaction `tx_seq` of the model ledger, carrying its public
375    /// position.
376    fn tx_position(tx_seq: u64) -> Position {
377        let checkpoint = BOUNDARIES[1..]
378            .iter()
379            .position(|end| tx_seq < *end)
380            .unwrap();
381        let transaction_index = tx_seq - BOUNDARIES[checkpoint];
382        Position::Transactions {
383            tx_seq,
384            public_position: LedgerPoint::transaction(checkpoint as u64, transaction_index),
385        }
386    }
387
388    fn resolve_transactions(
389        request: &ListTransactionsRequest,
390        options: &QueryOptions,
391    ) -> ResolvedScan<u64> {
392        let positions = CheckpointPositions::from_transactions_request(request).unwrap();
393        let cp_range = ResolvedCheckpointRange::from_request(
394            request.start_checkpoint,
395            request.end_checkpoint,
396            TIP,
397            options,
398        )
399        .unwrap();
400        let window = positions
401            .transaction_window(&cp_range.range, boundary)
402            .unwrap();
403        ResolvedScan::resolve(cp_range, window, options).unwrap()
404    }
405
406    fn event_window(request: &ListEventsRequest) -> ScanWindow<IntraTxCoordinate> {
407        let positions = CheckpointPositions::from_events_request(request).unwrap();
408        let window = request.start_checkpoint.unwrap_or(0)..request.end_checkpoint.unwrap_or(TIP);
409        positions.event_window(&window, boundary).unwrap()
410    }
411
412    fn event(tx_seq: u64, index: u32) -> IntraTxCoordinate {
413        IntraTxCoordinate { tx_seq, index }
414    }
415
416    /// Where a transactions request's terminal frame resumes in ledger coordinates, and the
417    /// public position of its cursor.
418    fn transactions_terminal(
419        request: &ListTransactionsRequest,
420        options: &QueryOptions,
421    ) -> (LedgerPoint, LedgerPoint) {
422        let positions = CheckpointPositions::from_transactions_request(request).unwrap();
423        let cp_range = ResolvedCheckpointRange::from_request(
424            request.start_checkpoint,
425            request.end_checkpoint,
426            TIP,
427            options,
428        )
429        .unwrap();
430        let window = positions
431            .transaction_window(&cp_range.range, boundary)
432            .unwrap();
433        let resolved = ResolvedScan::resolve(cp_range, window.clone(), options).unwrap();
434        (
435            resolved.end_resume_position(&window, options),
436            resolved.end_cursor_public_position(options),
437        )
438    }
439
440    /// A window's edges in ledger coordinates are the request's own positions, clamped past a
441    /// checkpoint's end as the scan positions are. A window without a checkpoint keeps the
442    /// request's fields as sent, beside its scan edge.
443    #[test]
444    fn window_edges_in_ledger_coordinates() {
445        let window = event_window(&events_request(
446            Some(2),
447            Some(4),
448            Some((1, Some(2))),
449            Some((0, Some(3))),
450        ));
451        assert_eq!(
452            window.ledger,
453            LedgerWindow {
454                start: LedgerPoint::event(2, 1, 2),
455                end: LedgerPoint::event(3, 0, 3),
456                requested: None,
457            }
458        );
459
460        // Transaction indexes past their checkpoints' ends name the next checkpoint's start.
461        let window = event_window(&events_request(
462            Some(2),
463            Some(4),
464            Some((4, Some(5))),
465            Some((2, Some(1))),
466        ));
467        assert_eq!(
468            window.ledger,
469            LedgerWindow {
470                start: LedgerPoint::checkpoint_start(3),
471                end: LedgerPoint::checkpoint_start(4),
472                requested: None,
473            }
474        );
475
476        let window = event_window(&events_request(Some(3), Some(3), Some((1, None)), None));
477        assert_eq!(
478            window.ledger,
479            LedgerWindow {
480                start: LedgerPoint::checkpoint_start(3),
481                end: LedgerPoint::checkpoint_start(3),
482                requested: Some((
483                    LedgerPoint::transaction(3, 1),
484                    LedgerPoint::checkpoint_start(3)
485                )),
486            }
487        );
488    }
489
490    /// A terminal at the request's own position, or at a request cursor's, needs no read: a
491    /// cursor places it by the public position it carries.
492    #[test]
493    fn terminal_at_a_request_position_needs_no_read() {
494        // Scans transactions 4..8; transaction 5 is at index 2 of checkpoint 2.
495        let request = transactions_request(Some(2), Some(4), Some(1), Some(1));
496        let point = LedgerPoint::transaction(3, 1);
497        assert_eq!(
498            transactions_terminal(&request, &options(Ordering::Ascending, None, None)),
499            (point, point)
500        );
501        let point = LedgerPoint::transaction(2, 1);
502        assert_eq!(
503            transactions_terminal(&request, &options(Ordering::Descending, None, None)),
504            (point, point)
505        );
506        let point = LedgerPoint::transaction(2, 2);
507        assert_eq!(
508            transactions_terminal(
509                &request,
510                &options(Ordering::Ascending, None, Some(tx_position(5)))
511            ),
512            (point, point)
513        );
514        assert_eq!(
515            transactions_terminal(
516                &request,
517                &options(Ordering::Descending, Some(tx_position(5)), None)
518            ),
519            (point, point)
520        );
521        // A window of only the empty checkpoint 1 is one scan position; its terminal names the
522        // edge in scan direction, the one its checkpoint claim reaches.
523        let empty_checkpoint = transactions_request(Some(1), Some(2), None, None);
524        let point = LedgerPoint::checkpoint_start(2);
525        assert_eq!(
526            transactions_terminal(&empty_checkpoint, &options(Ordering::Ascending, None, None)),
527            (point, point)
528        );
529        let point = LedgerPoint::checkpoint_start(1);
530        assert_eq!(
531            transactions_terminal(
532                &empty_checkpoint,
533                &options(Ordering::Descending, None, None)
534            ),
535            (point, point)
536        );
537        // Ascending past the tip, the terminal echoes the request's start fields, behind a
538        // cursor at the tip.
539        let past_tip = transactions_request(Some(TIP + 2), None, Some(3), None);
540        assert_eq!(
541            transactions_terminal(&past_tip, &options(Ordering::Ascending, None, None)),
542            (
543                LedgerPoint::transaction(TIP + 2, 3),
544                LedgerPoint::checkpoint_start(TIP)
545            )
546        );
547    }
548
549    fn is_invalid_argument(error: RpcError) -> bool {
550        error.into_status_proto().code == tonic::Code::InvalidArgument as i32
551    }
552
553    /// What a resolved scan ends with: `(range, terminal cursor's public position, terminal
554    /// position, end reason, natural end claim)`.
555    fn terminal(
556        resolved: &ResolvedScan<u64>,
557        options: &QueryOptions,
558    ) -> (Range<u64>, LedgerPoint, u64, RangeExhaustion, Option<u64>) {
559        (
560            resolved.range(),
561            resolved.end_cursor_public_position(options),
562            resolved.end_scan_position,
563            resolved.exhaustion,
564            resolved.natural_end_claim(options),
565        )
566    }
567
568    const CHECKPOINT_BOUND: RangeExhaustion = RangeExhaustion::CheckpointBound;
569    const CURSOR_BOUND: RangeExhaustion = RangeExhaustion::CursorBound {
570        kind: CursorKind::Boundary,
571    };
572
573    #[test]
574    fn unset_and_zero_start_indexes_scan_whole_checkpoints() {
575        for ordering in ORDERINGS {
576            let options = options(ordering, None, None);
577            let unset = transactions_request(Some(2), Some(4), None, None);
578            let zero = transactions_request(Some(2), Some(4), Some(0), None);
579            let expected = match ordering {
580                Ordering::Ascending => (
581                    3..9,
582                    LedgerPoint::checkpoint_start(4),
583                    9,
584                    CHECKPOINT_BOUND,
585                    Some(3),
586                ),
587                Ordering::Descending => (
588                    3..9,
589                    LedgerPoint::checkpoint_start(2),
590                    3,
591                    CHECKPOINT_BOUND,
592                    Some(2),
593                ),
594            };
595            assert_eq!(
596                terminal(&resolve_transactions(&unset, &options), &options),
597                expected
598            );
599            assert_eq!(
600                terminal(&resolve_transactions(&zero, &options), &options),
601                expected
602            );
603        }
604    }
605
606    /// A start position inside the first checkpoint narrows the scan. Ascending, it vouches for
607    /// the positions before it, so the scan still claims that checkpoint; descending, the scan
608    /// never covers that checkpoint, so its end claims the one above.
609    #[test]
610    fn start_position_inside_checkpoint() {
611        let request = transactions_request(Some(2), Some(4), Some(1), None);
612        let ascending = options(Ordering::Ascending, None, None);
613        assert_eq!(
614            terminal(&resolve_transactions(&request, &ascending), &ascending),
615            (
616                4..9,
617                LedgerPoint::checkpoint_start(4),
618                9,
619                CHECKPOINT_BOUND,
620                Some(3)
621            )
622        );
623        let descending = options(Ordering::Descending, None, None);
624        assert_eq!(
625            terminal(&resolve_transactions(&request, &descending), &descending),
626            (
627                4..9,
628                LedgerPoint::transaction(2, 1),
629                4,
630                CHECKPOINT_BOUND,
631                Some(3)
632            )
633        );
634    }
635
636    /// The end position lies in `end_checkpoint - 1`, and an ascending scan that stops inside it
637    /// does not claim it, so one that stops inside checkpoint 0 claims none. Index 0 excludes that
638    /// whole checkpoint.
639    #[test]
640    fn end_position_inside_last_checkpoint() {
641        let ascending = options(Ordering::Ascending, None, None);
642        let descending = options(Ordering::Descending, None, None);
643        let request = transactions_request(Some(2), Some(4), None, Some(1));
644        assert_eq!(
645            terminal(&resolve_transactions(&request, &ascending), &ascending),
646            (
647                3..8,
648                LedgerPoint::transaction(3, 1),
649                8,
650                CHECKPOINT_BOUND,
651                Some(2)
652            )
653        );
654        assert_eq!(
655            terminal(&resolve_transactions(&request, &descending), &descending),
656            (
657                3..8,
658                LedgerPoint::checkpoint_start(2),
659                3,
660                CHECKPOINT_BOUND,
661                Some(2)
662            )
663        );
664
665        let request = transactions_request(Some(2), Some(4), None, Some(0));
666        assert_eq!(
667            terminal(&resolve_transactions(&request, &ascending), &ascending),
668            (
669                3..7,
670                LedgerPoint::transaction(3, 0),
671                7,
672                CHECKPOINT_BOUND,
673                Some(2)
674            )
675        );
676
677        let genesis = transactions_request(Some(0), Some(1), None, Some(1));
678        assert_eq!(
679            terminal(&resolve_transactions(&genesis, &ascending), &ascending),
680            (
681                0..1,
682                LedgerPoint::transaction(0, 1),
683                1,
684                CHECKPOINT_BOUND,
685                None
686            )
687        );
688    }
689
690    /// Indexes at or past the end of their checkpoint clamp to its end: a start moves to the next
691    /// checkpoint, and an end covers the whole checkpoint.
692    #[test]
693    fn indexes_past_checkpoint_end_clamp() {
694        for (start_index, end_index) in [(4, 2), (u64::MAX, u64::MAX)] {
695            let request =
696                transactions_request(Some(2), Some(4), Some(start_index), Some(end_index));
697            let ascending = options(Ordering::Ascending, None, None);
698            assert_eq!(
699                terminal(&resolve_transactions(&request, &ascending), &ascending),
700                (
701                    7..9,
702                    LedgerPoint::checkpoint_start(4),
703                    9,
704                    CHECKPOINT_BOUND,
705                    Some(3)
706                )
707            );
708            let descending = options(Ordering::Descending, None, None);
709            assert_eq!(
710                terminal(&resolve_transactions(&request, &descending), &descending),
711                (
712                    7..9,
713                    LedgerPoint::checkpoint_start(3),
714                    7,
715                    CHECKPOINT_BOUND,
716                    Some(3)
717                )
718            );
719        }
720    }
721
722    #[test]
723    fn event_positions() {
724        // Mid-checkpoint start and end, with event indexes.
725        let window = event_window(&events_request(
726            Some(2),
727            Some(4),
728            Some((1, Some(2))),
729            Some((0, Some(3))),
730        ));
731        assert_eq!(window.range, event(4, 2)..event(7, 3));
732
733        // An event index past its transaction's events needs no clamp: the end admits all of
734        // that transaction's events.
735        let window = event_window(&events_request(Some(2), Some(4), None, Some((1, Some(9)))));
736        assert_eq!(window.range, event(3, 0)..event(8, 9));
737
738        // A transaction index past the checkpoint drops the event index: the start is the next
739        // checkpoint's first event, and the end covers the whole checkpoint.
740        let window = event_window(&events_request(
741            Some(2),
742            Some(4),
743            Some((4, Some(5))),
744            Some((2, Some(1))),
745        ));
746        assert_eq!(window.range, event(7, 0)..event(9, 0));
747        assert!(window.start_cuts_checkpoint);
748        assert!(!window.end_cuts_checkpoint);
749
750        // In an empty checkpoint, every start position is its end, which is also its start.
751        let window = event_window(&events_request(Some(1), Some(3), Some((0, Some(2))), None));
752        assert_eq!(window.range, event(3, 0)..event(7, 0));
753        assert!(!window.start_cuts_checkpoint);
754    }
755
756    /// A start position past the end position leaves nothing to scan, and claims nothing.
757    #[test]
758    fn crossed_positions_scan_nothing() {
759        let request = transactions_request(Some(3), Some(4), Some(1), Some(0));
760        let ascending = options(Ordering::Ascending, None, None);
761        assert_eq!(
762            terminal(&resolve_transactions(&request, &ascending), &ascending),
763            (
764                7..7,
765                LedgerPoint::transaction(3, 0),
766                7,
767                CHECKPOINT_BOUND,
768                None
769            )
770        );
771        let descending = options(Ordering::Descending, None, None);
772        assert_eq!(
773            terminal(&resolve_transactions(&request, &descending), &descending),
774            (
775                8..8,
776                LedgerPoint::transaction(3, 1),
777                8,
778                CHECKPOINT_BOUND,
779                None
780            )
781        );
782    }
783
784    /// An `end_checkpoint` past the tip leaves its last checkpoint unindexed: the scan ends at
785    /// the tip, ignoring the end position.
786    #[test]
787    fn end_position_past_the_tip_does_not_apply() {
788        let request = transactions_request(Some(3), Some(TIP + 1), None, Some(0));
789        let ascending = options(Ordering::Ascending, None, None);
790        assert_eq!(
791            terminal(&resolve_transactions(&request, &ascending), &ascending),
792            (
793                7..14,
794                LedgerPoint::checkpoint_start(TIP),
795                14,
796                RangeExhaustion::LedgerTip,
797                Some(4)
798            )
799        );
800    }
801
802    /// Positions and cursors bound the scan by intersection: the later start and the earlier end
803    /// win, and the end's reason and cursor follow whichever ends it.
804    #[test]
805    fn positions_intersect_cursors() {
806        // Scans transactions 4..8.
807        let request = transactions_request(Some(2), Some(4), Some(1), Some(1));
808        let cases = [
809            (
810                options(Ordering::Ascending, Some(tx_position(6)), None),
811                (6..8, LedgerPoint::transaction(3, 1), 8, CHECKPOINT_BOUND),
812            ),
813            (
814                options(Ordering::Ascending, Some(tx_position(2)), None),
815                (4..8, LedgerPoint::transaction(3, 1), 8, CHECKPOINT_BOUND),
816            ),
817            (
818                options(Ordering::Ascending, None, Some(tx_position(5))),
819                (4..5, LedgerPoint::transaction(2, 2), 5, CURSOR_BOUND),
820            ),
821            (
822                options(Ordering::Ascending, None, Some(tx_position(9))),
823                (4..8, LedgerPoint::transaction(3, 1), 8, CHECKPOINT_BOUND),
824            ),
825            (
826                options(Ordering::Descending, None, Some(tx_position(6))),
827                (4..6, LedgerPoint::transaction(2, 1), 4, CHECKPOINT_BOUND),
828            ),
829            (
830                options(Ordering::Descending, Some(tx_position(5)), None),
831                (5..8, LedgerPoint::transaction(2, 2), 5, CURSOR_BOUND),
832            ),
833        ];
834        for (options, expected) in cases {
835            let resolved = resolve_transactions(&request, &options);
836            assert_eq!(
837                (
838                    resolved.range(),
839                    resolved.end_cursor_public_position(&options),
840                    resolved.end_scan_position,
841                    resolved.exhaustion
842                ),
843                expected,
844                "{options:?}"
845            );
846        }
847    }
848
849    #[test]
850    fn index_without_its_bound_is_invalid_argument() {
851        let transactions = [
852            transactions_request(None, Some(4), Some(1), None),
853            transactions_request(Some(2), None, None, Some(1)),
854        ];
855        for request in transactions {
856            let error = CheckpointPositions::from_transactions_request(&request).unwrap_err();
857            assert!(is_invalid_argument(error), "{request:?}");
858        }
859
860        let mut start_event_alone = events_request(Some(2), Some(4), None, None);
861        start_event_alone.start_event_index = Some(1);
862        let mut end_event_alone = events_request(Some(2), Some(4), None, None);
863        end_event_alone.end_event_index = Some(1);
864        let events = [
865            events_request(None, Some(4), Some((1, None)), None),
866            events_request(Some(2), None, None, Some((1, Some(0)))),
867            start_event_alone,
868            end_event_alone,
869        ];
870        for request in events {
871            let error = CheckpointPositions::from_events_request(&request).unwrap_err();
872            assert!(is_invalid_argument(error), "{request:?}");
873        }
874    }
875}