junobuild_shared/assert.rs
1use crate::canister::memory_size;
2use crate::errors::{
3 JUNO_ERROR_MEMORY_HEAP_EXCEEDED, JUNO_ERROR_MEMORY_STABLE_EXCEEDED, JUNO_ERROR_NO_TIMESTAMP,
4 JUNO_ERROR_NO_VERSION, JUNO_ERROR_TIMESTAMP_OUTDATED_OR_FUTURE,
5 JUNO_ERROR_VERSION_OUTDATED_OR_FUTURE,
6};
7use crate::types::config::ConfigMaxMemorySize;
8use crate::types::interface::MemorySize;
9use crate::types::state::Version;
10
11/// Asserts the validity of a given user timestamp against the current timestamp.
12/// e.g. the timestamp of an existing entity persisted in a smart contract.
13///
14/// This function checks if the provided user timestamp matches the current system timestamp.
15/// It is designed to ensure that operations relying on timestamps are executed with current
16/// or synchronized timestamps to prevent replay or outdated requests.
17///
18/// # Parameters
19/// - `user_timestamp`: An `Option<u64>` representing the user-provided timestamp. This can be `None`
20/// if the user did not provide a timestamp, or `Some(u64)` if a timestamp was provided.
21/// - `current_timestamp`: A `u64` representing the current system timestamp. This should be
22/// the accurate current time in a format consistent with `user_timestamp`.
23///
24/// # Returns
25/// - `Ok(())` if the `user_timestamp` matches the `current_timestamp`.
26/// - `Err(String)` if:
27/// - The `user_timestamp` is `None`, indicating no timestamp was provided. The error string
28/// will be `ERROR_NO_TIMESTAMP.to_string()`, where `ERROR_NO_TIMESTAMP` is a constant string
29/// describing the error.
30/// - The `user_timestamp` does not match the `current_timestamp`, indicating either an outdated
31/// or a future timestamp. The error string will format to include the error description
32/// (from a constant `ERROR_TIMESTAMP_OUTDATED_OR_FUTURE`), the current timestamp, and the
33/// provided user timestamp.
34///
35/// # Examples
36/// ```
37/// let current_timestamp = 1625097600; // Example timestamp
38/// let user_timestamp = Some(1625097600);
39/// assert_eq!(assert_timestamp(user_timestamp, current_timestamp), Ok(()));
40///
41/// let wrong_timestamp = Some(1625097601);
42/// assert!(assert_timestamp(wrong_timestamp, current_timestamp).is_err());
43///
44/// let no_timestamp = None;
45/// assert!(assert_timestamp(no_timestamp, current_timestamp).is_err());
46/// ```
47///
48#[deprecated]
49pub fn assert_timestamp(user_timestamp: Option<u64>, current_timestamp: u64) -> Result<(), String> {
50 match user_timestamp {
51 None => {
52 return Err(JUNO_ERROR_NO_TIMESTAMP.to_string());
53 }
54 Some(user_timestamp) => {
55 if current_timestamp != user_timestamp {
56 return Err(format!(
57 "{JUNO_ERROR_TIMESTAMP_OUTDATED_OR_FUTURE} ({current_timestamp} - {user_timestamp})"
58 ));
59 }
60 }
61 }
62
63 Ok(())
64}
65
66/// Asserts the validity of a given user version against the required version.
67/// This function checks if the provided user version matches the current system version.
68/// It is designed to ensure that operations relying on version numbers are executed with the
69/// correct versions to prevent issues with compatibility or outdated requests.
70///
71/// # Parameters
72/// - `user_version`: An `Option<u64>` representing the user-provided version. This can be `None`
73/// if the user did not provide a version, or `Some(u64)` if a version was provided.
74/// - `current_version`: An `Option<u64>` representing the required system version. This can be `None`
75/// which means no specific version requirement is needed.
76///
77/// # Returns
78/// - `Ok(())` if the `user_version` matches the `current_version` or if no specific `current_version` is provided.
79/// - `Err(String)` if:
80/// - The `user_version` is `None`, indicating no version was provided. The error string
81/// will be `ERROR_NO_VERSION.to_string()`, where `ERROR_NO_VERSION` is a constant string
82/// describing the error.
83/// - The `user_version` does not match the `current_version`, indicating either an incorrect
84/// or incompatible version. The error string will format to include the error description
85/// (from a constant `ERROR_VERSION_MISMATCH`), the required version, and the provided user version.
86///
87/// # Examples
88/// ```
89/// let current_version = Some(3); // Example version
90/// let user_version = Some(3);
91/// assert_eq!(assert_version(user_version, current_version), Ok(()));
92///
93/// let wrong_version = Some(2);
94/// assert!(assert_version(wrong_version, current_version).is_err());
95///
96/// let no_version = None;
97/// let no_current_version = None;
98/// assert!(assert_version(no_version, no_current_version).is_ok());
99/// ```
100///
101pub fn assert_version(
102 user_version: Option<Version>,
103 current_version: Option<Version>,
104) -> Result<(), String> {
105 match current_version {
106 None => (),
107 Some(current_version) => match user_version {
108 None => {
109 return Err(JUNO_ERROR_NO_VERSION.to_string());
110 }
111 Some(user_version) => {
112 if current_version != user_version {
113 return Err(format!(
114 "{JUNO_ERROR_VERSION_OUTDATED_OR_FUTURE} ({current_version} - {user_version})"
115 ));
116 }
117 }
118 },
119 }
120
121 Ok(())
122}
123
124/// Validates the length of a description field in entities such as documents or assets.
125///
126/// Ensures that the description does not exceed 1024 characters. If the description exceeds
127/// this limit, the function returns an error message.
128///
129/// # Parameters
130///
131/// - `description`: An optional reference to a `String` that represents the description field
132/// of an entity. If the description is `None`, the function considers it valid and does not
133/// perform any length checks.
134///
135/// # Returns
136///
137/// - `Ok(())`: If the description is valid (either `None` or within the length limit).
138/// - `Err(String)`: If the description exceeds 1024 characters, containing an error message.
139///
140/// # Examples
141///
142/// ```
143/// let valid_description = Some(String::from("This is a valid description."));
144/// assert_eq!(assert_description_length(&valid_description), Ok(()));
145///
146/// let invalid_description = Some(String::from("a".repeat(1025)));
147/// assert_eq!(
148/// assert_description_length(&invalid_description),
149/// Err(String::from("Description field should not contains more than 1024 characters."))
150/// );
151///
152/// let none_description: Option<String> = None;
153/// assert_eq!(assert_description_length(&none_description), Ok(()));
154/// ```
155pub fn assert_description_length(description: &Option<String>) -> Result<(), String> {
156 match description {
157 None => (),
158 Some(description) => {
159 if description.len() > 1024 {
160 return Err(
161 "Description field should not contains more than 1024 characters.".to_string(),
162 );
163 }
164 }
165 }
166
167 Ok(())
168}
169
170pub fn assert_max_memory_size(
171 config_max_memory_size: &Option<ConfigMaxMemorySize>,
172) -> Result<(), String> {
173 if let Some(max_memory_size) = &config_max_memory_size {
174 let MemorySize { heap, stable } = memory_size();
175
176 if let Some(max_heap) = max_memory_size.heap {
177 if heap > max_heap as u64 {
178 return Err(format!(
179 "{JUNO_ERROR_MEMORY_HEAP_EXCEEDED} ({heap} bytes used, {max_heap} bytes allowed)"
180 ));
181 }
182 }
183
184 if let Some(max_stable) = max_memory_size.stable {
185 if stable > max_stable as u64 {
186 return Err(format!(
187 "{JUNO_ERROR_MEMORY_STABLE_EXCEEDED} ({stable} bytes used, {max_stable} bytes allowed)"
188 ));
189 }
190 }
191 }
192
193 Ok(())
194}