Skip to main content

drive/query/drive_document_count_query/
proof_plan.rs

1//! The request-only half of a proved count: which proof answers the
2//! request, what that proof reads, and the limit and walk direction its
3//! path query carries.
4//!
5//! The server's dispatcher proves what the plan names, and the SDK's
6//! verifier rebuilds the path query from the same plan, so the two cannot
7//! read one request differently; a client refuses before sending what the
8//! plan refuses, in the server's words.
9
10use super::{DocumentCountMode, DriveDocumentCountQuery, QuerySyntaxError};
11use crate::config::DEFAULT_QUERY_LIMIT;
12use crate::error::drive::DriveError;
13use crate::error::Error;
14use crate::query::{OrderClause, ResolvedTimeRange, WhereClause};
15use dpp::data_contract::document_type::accessors::{DocumentTypeV0Getters, DocumentTypeV2Getters};
16use dpp::data_contract::document_type::{DocumentTypeRef, Index};
17use dpp::version::PlatformVersion;
18use grovedb::PathQuery;
19
20/// What a proved count reads, decided from its request alone.
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub enum CountProofPlan<'a> {
23    /// An unfiltered count of a `documentsCountable` document type: the
24    /// type's primary-key count tree.
25    PrimaryKeyCountTree,
26    /// `Equal` / `In` clauses on a countable index: one count tree per
27    /// matched branch.
28    PointLookup(&'a Index),
29    /// A range on a range-countable index, ungrouped: one aggregate over the
30    /// range.
31    Range(&'a Index),
32    /// A range grouped by its values: one count per distinct value, walking
33    /// at most `limit` of them.
34    RangeDistinct {
35        /// The range-countable index the walk reads.
36        index: &'a Index,
37        /// The `SizedQuery` limit of the walk.
38        limit: u16,
39        /// The walk's direction, `Query::left_to_right`.
40        left_to_right: bool,
41    },
42    /// A range grouped by an outer `In` or range: one aggregate per outer
43    /// key.
44    RangeAggregateCarrier {
45        /// The range-countable index the carrier reads.
46        index: &'a Index,
47        /// The `SizedQuery` limit of the outer walk; `None` for an `In`
48        /// outer, whose values bound it.
49        limit: Option<u16>,
50        /// The outer walk's direction, `Query::left_to_right`.
51        left_to_right: bool,
52    },
53}
54
55impl DriveDocumentCountQuery<'_> {
56    /// The [`CountProofPlan`] of a proved count over `document_type`.
57    ///
58    /// `where_clauses` are the request's clauses as the dispatcher reads them
59    /// (typed array elements keyed, canonicalized), `resolved_time_ranges`
60    /// their window provenance, and `mode` the proof mode
61    /// [`Self::detect_mode_versioned`] resolved them to. `order_clauses` and
62    /// `limit` are the request's, `limit` `None` when unset; a distinct or
63    /// carrier walk runs in the first order clause's direction, ascending
64    /// by default.
65    ///
66    /// `max_query_limit` is the node's configured cap on a distinct walk's
67    /// limit, checked before the index is picked. A client, which cannot
68    /// know a node's configuration, passes `None`; the node refuses a limit
69    /// above its own cap.
70    ///
71    /// The plan reads no version table, so every protocol version that serves
72    /// a proved count plans the same proof for the same request.
73    pub fn proof_plan<'a>(
74        document_type: &'a DocumentTypeRef<'_>,
75        where_clauses: &[WhereClause],
76        resolved_time_ranges: &[ResolvedTimeRange],
77        mode: DocumentCountMode,
78        order_clauses: &[OrderClause],
79        limit: Option<u32>,
80        max_query_limit: Option<u16>,
81    ) -> Result<CountProofPlan<'a>, Error> {
82        let left_to_right = order_clauses.first().map(|c| c.ascending).unwrap_or(true);
83        let range_index = || {
84            Self::find_range_countable_index_for_where_clauses(
85                document_type.indexes(),
86                where_clauses,
87                resolved_time_ranges,
88            )
89            .ok_or_else(|| {
90                Error::Query(QuerySyntaxError::WhereClauseOnNonIndexedProperty(
91                    "range count requires a `range_countable: true` (or summableOffCountIndex) index whose last \
92                     property matches the range field"
93                        .to_string(),
94                ))
95            })
96        };
97        match mode {
98            DocumentCountMode::RangeProof => Ok(CountProofPlan::Range(range_index()?)),
99            DocumentCountMode::RangeDistinctProof => {
100                // Validate-don't-clamp: the verifier rebuilds the walk's
101                // `SizedQuery::limit` byte for byte, so an over-cap limit is
102                // refused rather than clamped. An unset limit falls back to
103                // the compile-time `DEFAULT_QUERY_LIMIT`, never the
104                // operator-tunable `default_query_limit`, which a verifier
105                // cannot know.
106                let effective_limit = limit.unwrap_or(DEFAULT_QUERY_LIMIT as u32);
107                if let Some(max_query_limit) = max_query_limit {
108                    if effective_limit > max_query_limit as u32 {
109                        return Err(Error::Query(QuerySyntaxError::InvalidLimit(format!(
110                            "limit {} exceeds max_query_limit {} on the prove + \
111                             distinct-walk path (GROUP BY a range field); reduce the \
112                             requested limit or use prove = false",
113                            effective_limit, max_query_limit
114                        ))));
115                    }
116                }
117                // Within a node's `u16` cap this always converts.
118                let limit = u16::try_from(effective_limit).map_err(|_| {
119                    Error::Query(QuerySyntaxError::InvalidLimit(format!(
120                        "limit {effective_limit} exceeds u16::MAX; the prove-distinct path \
121                         query cannot represent it"
122                    )))
123                })?;
124                Ok(CountProofPlan::RangeDistinct {
125                    index: range_index()?,
126                    limit,
127                    left_to_right,
128                })
129            }
130            DocumentCountMode::PointLookupProof => {
131                // An unfiltered count of a `documents_countable` type proves the
132                // primary-key count tree directly, no index involved.
133                if where_clauses.is_empty() && document_type.documents_countable() {
134                    return Ok(CountProofPlan::PrimaryKeyCountTree);
135                }
136                Self::find_countable_index_for_where_clauses(
137                    document_type.indexes(),
138                    where_clauses,
139                    resolved_time_ranges,
140                )
141                .map(CountProofPlan::PointLookup)
142                .ok_or_else(|| {
143                    Error::Query(QuerySyntaxError::WhereClauseOnNonIndexedProperty(
144                        "prove count requires a `countable: true` (or summableOffCountIndex) index whose properties \
145                         exactly match the where clause fields, a `rangeCountable: true` \
146                         index they cover up to its last property, or `documentsCountable: \
147                         true` on the document type for unfiltered total counts — same \
148                         requirement as the no-proof path"
149                            .to_string(),
150                    ))
151                })
152            }
153            DocumentCountMode::RangeAggregateCarrierProof => {
154                let limit = Self::carrier_aggregate_count_limit(where_clauses, limit)?;
155                let index = Self::find_range_countable_index_for_where_clauses(
156                    document_type.indexes(),
157                    where_clauses,
158                    resolved_time_ranges,
159                )
160                .ok_or_else(|| {
161                    Error::Query(QuerySyntaxError::WhereClauseOnNonIndexedProperty(
162                        "carrier-aggregate count requires a `range_countable: true` (or \
163                         summableOffCountIndex) index whose first \
164                         property carries the outer In or range clause and whose last property \
165                         carries the inner ACOR range clause"
166                            .to_string(),
167                    ))
168                })?;
169                Ok(CountProofPlan::RangeAggregateCarrier {
170                    index,
171                    limit,
172                    left_to_right,
173                })
174            }
175            DocumentCountMode::Total
176            | DocumentCountMode::PerInValue
177            | DocumentCountMode::RangeNoProof => {
178                Err(Error::Drive(DriveError::CorruptedCodeExecution(
179                    "a count proof plan is made only for a proof mode; mode detection with \
180                     prove = true never returns a no-proof mode",
181                )))
182            }
183        }
184    }
185}
186
187impl CountProofPlan<'_> {
188    /// The path query a proof of this plan answers. The server proves it
189    /// (`Drive::execute_document_count_proof`), and a
190    /// client builds it from the same plan before sending and before it
191    /// verifies an answer, so a request whose path query cannot be built is
192    /// refused in the server's words. A `summableOffCountIndex` index counts
193    /// its documents through its range sums, so its range proofs read the sum
194    /// surface's path queries.
195    ///
196    /// The other arguments are the request's, as
197    /// [`DriveDocumentCountQuery::proof_plan`] read them.
198    pub fn path_query(
199        &self,
200        contract_id: [u8; 32],
201        document_type: DocumentTypeRef,
202        document_type_name: String,
203        where_clauses: Vec<WhereClause>,
204        platform_version: &PlatformVersion,
205    ) -> Result<PathQuery, Error> {
206        let count_query = |index| DriveDocumentCountQuery {
207            document_type,
208            contract_id,
209            document_type_name,
210            index,
211            where_clauses,
212        };
213        match *self {
214            CountProofPlan::PrimaryKeyCountTree => {
215                Ok(DriveDocumentCountQuery::primary_key_count_tree_path_query(
216                    contract_id,
217                    document_type.name(),
218                ))
219            }
220            CountProofPlan::PointLookup(index) => {
221                count_query(index).point_lookup_count_path_query(platform_version)
222            }
223            CountProofPlan::Range(index) => {
224                let query = count_query(index);
225                match query.counter_sums_query() {
226                    Some(sums) => sums.aggregate_sum_path_query(platform_version),
227                    None => query.aggregate_count_path_query(platform_version),
228                }
229            }
230            CountProofPlan::RangeDistinct {
231                index,
232                limit,
233                left_to_right,
234            } => {
235                let query = count_query(index);
236                match query.counter_sums_query() {
237                    Some(sums) => {
238                        sums.distinct_sum_path_query(Some(limit), left_to_right, platform_version)
239                    }
240                    None => query.distinct_count_path_query(
241                        Some(limit),
242                        left_to_right,
243                        platform_version,
244                    ),
245                }
246            }
247            CountProofPlan::RangeAggregateCarrier {
248                index,
249                limit,
250                left_to_right,
251            } => {
252                let query = count_query(index);
253                match query.counter_sums_query() {
254                    Some(sums) => sums.carrier_aggregate_sum_path_query(
255                        limit,
256                        left_to_right,
257                        platform_version,
258                    ),
259                    None => query.carrier_aggregate_count_path_query(
260                        limit,
261                        left_to_right,
262                        platform_version,
263                    ),
264                }
265            }
266        }
267    }
268}