1#[cfg(feature = "nns-host")]
8use super::NnsProposalHostError;
9use super::{
10 NnsProposalError,
11 model::{NnsProposalListReport, NnsProposalListRequest},
12 source::{
13 NnsProposalSource, build_nns_proposal_list_report_with_source, validate_proposal_page_size,
14 },
15};
16#[cfg(feature = "nns-host")]
17use crate::nns::LiveNnsSource;
18use crate::nns::{
19 MAINNET_GOVERNANCE_CANISTER_ID,
20 governance::{
21 NnsGovernanceCollectionStatus, NnsGovernanceRequest, NnsGovernanceSourceProvenance,
22 NnsGovernanceSourceSelection, validate_governance_collection_identity,
23 validate_governance_collection_page_bounds, validate_governance_continuation_request,
24 validate_governance_request, validate_governance_time_interval, validate_source_provenance,
25 },
26};
27use serde::{Deserialize, Serialize};
28
29pub const NNS_PROPOSAL_COLLECTION_STATE_SCHEMA_VERSION: u32 = 1;
31
32#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
39pub struct NnsProposalCollectionState {
40 schema_version: u32,
41 network: String,
42 governance_canister_id: String,
43 requested_source: NnsGovernanceSourceSelection,
44 source: Option<NnsGovernanceSourceProvenance>,
45 page_size: u32,
46 max_pages: u32,
47 pages_fetched: u32,
48 proposals_fetched: u64,
49 next_before_proposal_id: Option<u64>,
50 started_at: String,
51 updated_at: String,
52 status: NnsGovernanceCollectionStatus,
53}
54
55impl NnsProposalCollectionState {
56 pub fn new(
58 request: &NnsGovernanceRequest,
59 page_size: u32,
60 max_pages: u32,
61 ) -> Result<Self, NnsProposalError> {
62 validate_governance_request(request)?;
63 validate_proposal_page_size(page_size)?;
64 if max_pages == 0 {
65 return Err(NnsProposalError::InvalidCollectionMaxPages);
66 }
67 Ok(Self {
68 schema_version: NNS_PROPOSAL_COLLECTION_STATE_SCHEMA_VERSION,
69 network: request.network.clone(),
70 governance_canister_id: MAINNET_GOVERNANCE_CANISTER_ID.to_string(),
71 requested_source: request.source.clone(),
72 source: None,
73 page_size,
74 max_pages,
75 pages_fetched: 0,
76 proposals_fetched: 0,
77 next_before_proposal_id: None,
78 started_at: request.fetched_at.clone(),
79 updated_at: request.fetched_at.clone(),
80 status: NnsGovernanceCollectionStatus::Ready,
81 })
82 }
83
84 #[must_use]
86 pub const fn schema_version(&self) -> u32 {
87 self.schema_version
88 }
89
90 #[must_use]
92 pub fn network(&self) -> &str {
93 &self.network
94 }
95
96 #[must_use]
98 pub fn governance_canister_id(&self) -> &str {
99 &self.governance_canister_id
100 }
101
102 #[must_use]
104 pub const fn requested_source(&self) -> &NnsGovernanceSourceSelection {
105 &self.requested_source
106 }
107
108 #[must_use]
110 pub const fn source(&self) -> Option<&NnsGovernanceSourceProvenance> {
111 self.source.as_ref()
112 }
113
114 #[must_use]
116 pub const fn page_size(&self) -> u32 {
117 self.page_size
118 }
119
120 #[must_use]
122 pub const fn max_pages(&self) -> u32 {
123 self.max_pages
124 }
125
126 #[must_use]
128 pub const fn pages_fetched(&self) -> u32 {
129 self.pages_fetched
130 }
131
132 #[must_use]
134 pub const fn proposals_fetched(&self) -> u64 {
135 self.proposals_fetched
136 }
137
138 #[must_use]
140 pub const fn next_before_proposal_id(&self) -> Option<u64> {
141 self.next_before_proposal_id
142 }
143
144 #[must_use]
146 pub fn started_at(&self) -> &str {
147 &self.started_at
148 }
149
150 #[must_use]
152 pub fn updated_at(&self) -> &str {
153 &self.updated_at
154 }
155
156 #[must_use]
158 pub const fn status(&self) -> NnsGovernanceCollectionStatus {
159 self.status
160 }
161
162 #[must_use]
164 pub const fn is_complete(&self) -> bool {
165 matches!(self.status, NnsGovernanceCollectionStatus::Complete)
166 }
167}
168
169#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
176pub struct NnsProposalCollectionStep {
177 pub page: NnsProposalListReport,
179 pub state: NnsProposalCollectionState,
181}
182
183#[cfg(feature = "nns-host")]
185pub async fn advance_nns_proposal_collection(
186 request: &NnsGovernanceRequest,
187 state: &NnsProposalCollectionState,
188) -> Result<NnsProposalCollectionStep, NnsProposalHostError> {
189 Ok(
190 advance_nns_proposal_collection_with_source(request, state, &LiveNnsSource::default())
191 .await?,
192 )
193}
194
195pub async fn advance_nns_proposal_collection_with_source(
197 request: &NnsGovernanceRequest,
198 state: &NnsProposalCollectionState,
199 source: &dyn NnsProposalSource,
200) -> Result<NnsProposalCollectionStep, NnsProposalError> {
201 validate_governance_request(request)?;
202 validate_collection_state(state)?;
203 validate_governance_continuation_request(
204 request,
205 &state.network,
206 &state.requested_source,
207 |field, expected, actual| NnsProposalError::CollectionRequestMismatch {
208 field,
209 expected,
210 actual,
211 },
212 )?;
213 validate_governance_time_interval(
214 "updated_at",
215 &state.updated_at,
216 "fetched_at",
217 &request.fetched_at,
218 )?;
219 match state.status {
220 NnsGovernanceCollectionStatus::Complete => {
221 return Err(NnsProposalError::CollectionComplete {
222 pages_fetched: state.pages_fetched,
223 });
224 }
225 NnsGovernanceCollectionStatus::PageLimitReached => {
226 return Err(NnsProposalError::CollectionPageLimitReached {
227 pages_fetched: state.pages_fetched,
228 max_pages: state.max_pages,
229 });
230 }
231 NnsGovernanceCollectionStatus::Ready | NnsGovernanceCollectionStatus::Collecting => {}
232 }
233
234 let mut page_request = NnsProposalListRequest::new(request.clone(), state.page_size);
235 page_request.before_proposal_id = state.next_before_proposal_id;
236 let page = build_nns_proposal_list_report_with_source(&page_request, source).await?;
237 if let Some(expected) = &state.source
238 && *expected != page.context.source
239 {
240 return Err(NnsProposalError::CollectionSourceChanged {
241 expected: expected.clone(),
242 actual: page.context.source,
243 });
244 }
245
246 let page_count = u32::try_from(page.proposal_count)
247 .map_err(|_| NnsProposalError::CollectionAccountingOverflow)?;
248 let (pages_fetched, proposals_fetched) = crate::nns::governance::advance_collection_counts(
249 state.pages_fetched,
250 state.proposals_fetched,
251 u64::from(page_count),
252 )
253 .ok_or(NnsProposalError::CollectionAccountingOverflow)?;
254 let next_before_proposal_id = (page_count == state.page_size)
255 .then(|| {
256 page.proposals
257 .iter()
258 .filter_map(|proposal| proposal.proposal_id)
259 .min()
260 .filter(|proposal_id| *proposal_id > 1)
261 })
262 .flatten();
263 let status = crate::nns::governance::collection_status_after_page(
264 next_before_proposal_id.is_some(),
265 pages_fetched,
266 state.max_pages,
267 );
268 let next_state = NnsProposalCollectionState {
269 source: Some(page.context.source.clone()),
270 pages_fetched,
271 proposals_fetched,
272 next_before_proposal_id,
273 updated_at: request.fetched_at.clone(),
274 status,
275 ..state.clone()
276 };
277 Ok(NnsProposalCollectionStep {
278 page,
279 state: next_state,
280 })
281}
282
283pub(super) fn validate_collection_state(
284 state: &NnsProposalCollectionState,
285) -> Result<(), NnsProposalError> {
286 let invalid = |reason| NnsProposalError::InvalidCollectionState { reason };
287 if state.schema_version != NNS_PROPOSAL_COLLECTION_STATE_SCHEMA_VERSION {
288 return Err(invalid(format!(
289 "schema_version is {}, expected {NNS_PROPOSAL_COLLECTION_STATE_SCHEMA_VERSION}",
290 state.schema_version
291 )));
292 }
293 validate_governance_collection_identity(
294 &state.network,
295 &state.governance_canister_id,
296 &state.requested_source,
297 (&state.started_at, &state.updated_at),
298 invalid,
299 )?;
300 validate_proposal_page_size(state.page_size)?;
301 validate_governance_collection_page_bounds(state.max_pages, state.pages_fetched, invalid)?;
302 if let Some(source) = &state.source {
303 validate_source_provenance(&state.requested_source, source)?;
304 }
305
306 let page_size = u64::from(state.page_size);
307 let pages_fetched = u64::from(state.pages_fetched);
308 let proposals_fetched = state.proposals_fetched;
309 let maximum_rows = pages_fetched * page_size;
311 let minimum_rows = pages_fetched.saturating_sub(1) * page_size;
312 if proposals_fetched < minimum_rows || proposals_fetched > maximum_rows {
313 return Err(invalid(format!(
314 "proposals_fetched {} is outside {}..={} for {} pages of size {}",
315 state.proposals_fetched,
316 minimum_rows,
317 maximum_rows,
318 state.pages_fetched,
319 state.page_size
320 )));
321 }
322 if state
323 .next_before_proposal_id
324 .is_some_and(|cursor| cursor <= 1)
325 {
326 return Err(invalid(
327 "next_before_proposal_id must be greater than one".to_string(),
328 ));
329 }
330
331 let valid_lifecycle = match state.status {
332 NnsGovernanceCollectionStatus::Ready => {
333 state.pages_fetched == 0
334 && state.proposals_fetched == 0
335 && state.next_before_proposal_id.is_none()
336 && state.source.is_none()
337 }
338 NnsGovernanceCollectionStatus::Collecting => {
339 state.pages_fetched > 0
340 && state.pages_fetched < state.max_pages
341 && proposals_fetched == maximum_rows
342 && state.next_before_proposal_id.is_some()
343 && state.source.is_some()
344 }
345 NnsGovernanceCollectionStatus::Complete => {
346 state.pages_fetched > 0
347 && state.next_before_proposal_id.is_none()
348 && state.source.is_some()
349 }
350 NnsGovernanceCollectionStatus::PageLimitReached => {
351 state.pages_fetched == state.max_pages
352 && proposals_fetched == maximum_rows
353 && state.next_before_proposal_id.is_some()
354 && state.source.is_some()
355 }
356 };
357 if !valid_lifecycle {
358 return Err(invalid(format!(
359 "status {} disagrees with cursor, provenance, or counters",
360 state.status
361 )));
362 }
363 Ok(())
364}
365
366#[cfg(test)]
367mod tests {
368 use super::*;
369 use crate::nns::governance::NnsGovernanceError;
370
371 struct UnexpectedSource;
372 impl NnsProposalSource for UnexpectedSource {
373 fn fetch_proposals<'a>(
374 &'a self,
375 _: &'a NnsGovernanceRequest,
376 _: u32,
377 _: Option<u64>,
378 _: crate::nns::proposals::NnsProposalStatusFilter,
379 _: crate::nns::proposals::NnsProposalRewardStatusFilter,
380 ) -> crate::nns::proposals::NnsProposalSourceFuture<
381 'a,
382 Vec<crate::nns::proposals::NnsProposalRow>,
383 > {
384 panic!("unexpected source call")
385 }
386 fn fetch_proposal<'a>(
387 &'a self,
388 _: &'a NnsGovernanceRequest,
389 _: u64,
390 ) -> crate::nns::proposals::NnsProposalSourceFuture<'a, crate::nns::proposals::NnsProposalRow>
391 {
392 panic!("unexpected source call")
393 }
394 }
395
396 #[tokio::test(flavor = "current_thread")]
397 async fn collection_rejects_backward_continuations_and_restored_intervals() {
398 let start = NnsGovernanceRequest::replicated_inter_canister_call_from_unix_secs("ic", 100);
399 let state = NnsProposalCollectionState::new(&start, 2, 3).unwrap();
400 let before = NnsGovernanceRequest::replicated_inter_canister_call_from_unix_secs("ic", 99);
401 let mut future = std::pin::pin!(advance_nns_proposal_collection_with_source(
402 &before,
403 &state,
404 &UnexpectedSource
405 ));
406 let mut context = std::task::Context::from_waker(std::task::Waker::noop());
407 let result = std::future::Future::poll(future.as_mut(), &mut context);
408 assert!(matches!(
409 result,
410 std::task::Poll::Ready(Err(NnsProposalError::Governance(
411 NnsGovernanceError::InvalidTimestampOrder { .. }
412 )))
413 ));
414 let mut value = serde_json::to_value(&state).unwrap();
415 value["updated_at"] = serde_json::json!(before.fetched_at);
416 let restored = serde_json::from_value(value).unwrap();
417 assert!(matches!(
418 validate_collection_state(&restored),
419 Err(NnsProposalError::Governance(
420 NnsGovernanceError::InvalidTimestampOrder { .. }
421 ))
422 ));
423 assert!(
424 validate_governance_time_interval(
425 "updated_at",
426 &state.updated_at,
427 "fetched_at",
428 &start.fetched_at
429 )
430 .is_ok()
431 );
432 }
433
434 #[test]
435 fn collection_validates_request_and_restored_timestamps() {
436 let mut request = NnsGovernanceRequest::replicated_inter_canister_call_from_unix_secs(
437 "ic",
438 1_700_000_000,
439 );
440 let valid_state = NnsProposalCollectionState::new(&request, 2, 3).expect("valid state");
441 for (field, value) in [
442 ("governance_canister_id", serde_json::json!("aaaaa-aa")),
443 ("max_pages", serde_json::json!(0)),
444 ("pages_fetched", serde_json::json!(4)),
445 ] {
446 let mut restored = serde_json::to_value(&valid_state).unwrap();
447 restored[field] = value;
448 let restored = serde_json::from_value(restored).unwrap();
449 assert!(
450 matches!(
451 validate_collection_state(&restored),
452 Err(NnsProposalError::InvalidCollectionState { .. })
453 ),
454 "invalid restored {field}"
455 );
456 }
457 for timestamp in ["not a UTC timestamp", "+2023-11-14T22:13:20Z"] {
458 request.fetched_at = timestamp.to_string();
459 assert!(matches!(
460 NnsProposalCollectionState::new(&request, 2, 3),
461 Err(NnsProposalError::Governance(
462 NnsGovernanceError::InvalidTimestamp {
463 field: "fetched_at",
464 ..
465 }
466 ))
467 ));
468 for field in ["started_at", "updated_at"] {
469 let mut value = serde_json::to_value(&valid_state).expect("serialize state");
470 value[field] = serde_json::json!(timestamp);
471 let state = serde_json::from_value(value).expect("restore caller state");
472 assert!(matches!(
473 validate_collection_state(&state),
474 Err(NnsProposalError::Governance(
475 NnsGovernanceError::InvalidTimestamp { value, .. }
476 )) if value == timestamp
477 ));
478 }
479 }
480 }
481}