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 proposals_fetched = state.proposals_fetched;
307 let maximum_rows = crate::nns::governance::validate_governance_collection_row_bounds(
308 "proposals_fetched",
309 proposals_fetched,
310 state.pages_fetched,
311 state.page_size,
312 invalid,
313 )?;
314
315 if state
316 .next_before_proposal_id
317 .is_some_and(|cursor| cursor <= 1)
318 {
319 return Err(invalid(
320 "next_before_proposal_id must be greater than one".to_string(),
321 ));
322 }
323
324 let valid_lifecycle = match state.status {
325 NnsGovernanceCollectionStatus::Ready => {
326 state.pages_fetched == 0
327 && state.proposals_fetched == 0
328 && state.next_before_proposal_id.is_none()
329 && state.source.is_none()
330 }
331 NnsGovernanceCollectionStatus::Collecting => {
332 state.pages_fetched > 0
333 && state.pages_fetched < state.max_pages
334 && proposals_fetched == maximum_rows
335 && state.next_before_proposal_id.is_some()
336 && state.source.is_some()
337 }
338 NnsGovernanceCollectionStatus::Complete => {
339 state.pages_fetched > 0
340 && state.next_before_proposal_id.is_none()
341 && state.source.is_some()
342 }
343 NnsGovernanceCollectionStatus::PageLimitReached => {
344 state.pages_fetched == state.max_pages
345 && proposals_fetched == maximum_rows
346 && state.next_before_proposal_id.is_some()
347 && state.source.is_some()
348 }
349 };
350 if !valid_lifecycle {
351 return Err(invalid(format!(
352 "status {} disagrees with cursor, provenance, or counters",
353 state.status
354 )));
355 }
356 Ok(())
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362 use crate::nns::governance::NnsGovernanceError;
363
364 struct UnexpectedSource;
365 impl NnsProposalSource for UnexpectedSource {
366 fn fetch_proposals<'a>(
367 &'a self,
368 _: &'a NnsGovernanceRequest,
369 _: u32,
370 _: Option<u64>,
371 _: crate::nns::proposals::NnsProposalStatusFilter,
372 _: crate::nns::proposals::NnsProposalRewardStatusFilter,
373 ) -> crate::nns::proposals::NnsProposalSourceFuture<
374 'a,
375 Vec<crate::nns::proposals::NnsProposalRow>,
376 > {
377 panic!("unexpected source call")
378 }
379 fn fetch_proposal<'a>(
380 &'a self,
381 _: &'a NnsGovernanceRequest,
382 _: u64,
383 ) -> crate::nns::proposals::NnsProposalSourceFuture<'a, crate::nns::proposals::NnsProposalRow>
384 {
385 panic!("unexpected source call")
386 }
387 }
388
389 #[tokio::test(flavor = "current_thread")]
390 async fn collection_rejects_backward_continuations_and_restored_intervals() {
391 let start = NnsGovernanceRequest::replicated_inter_canister_call_from_unix_secs("ic", 100);
392 let state = NnsProposalCollectionState::new(&start, 2, 3).unwrap();
393 let before = NnsGovernanceRequest::replicated_inter_canister_call_from_unix_secs("ic", 99);
394 let mut future = std::pin::pin!(advance_nns_proposal_collection_with_source(
395 &before,
396 &state,
397 &UnexpectedSource
398 ));
399 let mut context = std::task::Context::from_waker(std::task::Waker::noop());
400 let result = std::future::Future::poll(future.as_mut(), &mut context);
401 assert!(matches!(
402 result,
403 std::task::Poll::Ready(Err(NnsProposalError::Governance(
404 NnsGovernanceError::InvalidTimestampOrder { .. }
405 )))
406 ));
407 let mut value = serde_json::to_value(&state).unwrap();
408 value["updated_at"] = serde_json::json!(before.fetched_at);
409 let restored = serde_json::from_value(value).unwrap();
410 assert!(matches!(
411 validate_collection_state(&restored),
412 Err(NnsProposalError::Governance(
413 NnsGovernanceError::InvalidTimestampOrder { .. }
414 ))
415 ));
416 assert!(
417 validate_governance_time_interval(
418 "updated_at",
419 &state.updated_at,
420 "fetched_at",
421 &start.fetched_at
422 )
423 .is_ok()
424 );
425 }
426
427 #[test]
428 fn collection_validates_request_and_restored_timestamps() {
429 let mut request = NnsGovernanceRequest::replicated_inter_canister_call_from_unix_secs(
430 "ic",
431 1_700_000_000,
432 );
433 let valid_state = NnsProposalCollectionState::new(&request, 2, 3).expect("valid state");
434 for (field, value) in [
435 ("governance_canister_id", serde_json::json!("aaaaa-aa")),
436 ("max_pages", serde_json::json!(0)),
437 ("pages_fetched", serde_json::json!(4)),
438 ] {
439 let mut restored = serde_json::to_value(&valid_state).unwrap();
440 restored[field] = value;
441 let restored = serde_json::from_value(restored).unwrap();
442 assert!(
443 matches!(
444 validate_collection_state(&restored),
445 Err(NnsProposalError::InvalidCollectionState { .. })
446 ),
447 "invalid restored {field}"
448 );
449 }
450 for timestamp in ["not a UTC timestamp", "+2023-11-14T22:13:20Z"] {
451 request.fetched_at = timestamp.to_string();
452 assert!(matches!(
453 NnsProposalCollectionState::new(&request, 2, 3),
454 Err(NnsProposalError::Governance(
455 NnsGovernanceError::InvalidTimestamp {
456 field: "fetched_at",
457 ..
458 }
459 ))
460 ));
461 for field in ["started_at", "updated_at"] {
462 let mut value = serde_json::to_value(&valid_state).expect("serialize state");
463 value[field] = serde_json::json!(timestamp);
464 let state = serde_json::from_value(value).expect("restore caller state");
465 assert!(matches!(
466 validate_collection_state(&state),
467 Err(NnsProposalError::Governance(
468 NnsGovernanceError::InvalidTimestamp { value, .. }
469 )) if value == timestamp
470 ));
471 }
472 }
473 }
474}