cosmwasm-std 2.2.2

Standard library for Wasm based smart contracts on Cosmos blockchains
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#[cfg(test)]
use alloc::string::String;

/// Grows a big endian signed integer to a bigger size.
/// See <https://en.wikipedia.org/wiki/Sign_extension>
pub const fn grow_be_int<const INPUT_SIZE: usize, const OUTPUT_SIZE: usize>(
    input: [u8; INPUT_SIZE],
) -> [u8; OUTPUT_SIZE] {
    debug_assert!(INPUT_SIZE <= OUTPUT_SIZE);
    // check if sign bit is set
    let mut output = if input[0] & 0b10000000 != 0 {
        // negative number is filled up with 1s
        [0b11111111u8; OUTPUT_SIZE]
    } else {
        [0u8; OUTPUT_SIZE]
    };
    let mut i = 0;

    // copy input to the end of output
    // copy_from_slice is not const, so we have to do this manually
    while i < INPUT_SIZE {
        output[OUTPUT_SIZE - INPUT_SIZE + i] = input[i];
        i += 1;
    }
    output
}

/// Shrinks a big endian signed integer to a smaller size.
/// This is the opposite operation of sign extension.
pub fn shrink_be_int<const INPUT_SIZE: usize, const OUTPUT_SIZE: usize>(
    input: [u8; INPUT_SIZE],
) -> Option<[u8; OUTPUT_SIZE]> {
    debug_assert!(INPUT_SIZE >= OUTPUT_SIZE);

    // check bounds
    if input[0] & 0b10000000 != 0 {
        // a negative number should start with only 1s, otherwise it's too small
        for i in &input[0..(INPUT_SIZE - OUTPUT_SIZE)] {
            if *i != 0b11111111u8 {
                return None;
            }
        }
        // the sign bit also has to be 1
        if input[INPUT_SIZE - OUTPUT_SIZE] & 0b10000000 == 0 {
            return None;
        }
    } else {
        // a positive number should start with only 0s, otherwise it's too large
        for i in &input[0..(INPUT_SIZE - OUTPUT_SIZE)] {
            if *i != 0u8 {
                return None;
            }
        }
        // the sign bit also has to be 0
        if input[INPUT_SIZE - OUTPUT_SIZE] & 0b10000000 != 0 {
            return None;
        }
    }

    // Now, we can just copy the last bytes
    let mut output = [0u8; OUTPUT_SIZE];
    output.copy_from_slice(&input[(INPUT_SIZE - OUTPUT_SIZE)..]);
    Some(output)
}

/// Helper macro to implement `TryFrom` for a type that is just a wrapper around another type.
/// This can be used for all our integer conversions where `bnum` implements `TryFrom`.
macro_rules! forward_try_from {
    ($input: ty, $output: ty) => {
        impl TryFrom<$input> for $output {
            type Error = $crate::ConversionOverflowError;

            fn try_from(value: $input) -> Result<Self, Self::Error> {
                value
                    .0
                    .try_into()
                    .map(Self)
                    .map_err(|_| Self::Error::new(stringify!($input), stringify!($output)))
            }
        }
    };
}
pub(crate) use forward_try_from;

/// Helper macro to implement `From` for a type that is just a wrapper around another type.
/// This can be used for all our integer conversions where `bnum` implements `From`.
macro_rules! wrapped_int_to_primitive {
    ($input: ty, $output: ty) => {
        impl From<$input> for $output {
            fn from(value: $input) -> Self {
                // By convention all our Uint*/Int* types store the value in .0
                value.0.into()
            }
        }
    };
}
pub(crate) use wrapped_int_to_primitive;

/// Helper macro to implement `From` for a type that is just a wrapper around another type.
/// This can be used for all our integer conversions where `bnum` implements `From`.
macro_rules! primitive_to_wrapped_int {
    ($input: ty, $output: ty) => {
        impl From<$input> for $output {
            fn from(value: $input) -> Self {
                // By convention all our Uint*/Int* types store the value in .0
                Self(value.into())
            }
        }
    };
}
pub(crate) use primitive_to_wrapped_int;

/// Helper macro to implement `TryFrom` for a conversion from a bigger signed int to a smaller one.
/// This is needed because `bnum` does not implement `TryFrom` for those conversions
/// because of limitations of const generics.
macro_rules! try_from_int_to_int {
    ($input: ty, $output: ty) => {
        // statically assert that the input is bigger than the output
        static_assertions::const_assert!(
            core::mem::size_of::<$input>() > core::mem::size_of::<$output>()
        );
        impl TryFrom<$input> for $output {
            type Error = $crate::ConversionOverflowError;

            fn try_from(value: $input) -> Result<Self, Self::Error> {
                $crate::math::conversion::shrink_be_int(value.to_be_bytes())
                    .ok_or_else(|| Self::Error::new(stringify!($input), stringify!($output)))
                    .map(Self::from_be_bytes)
            }
        }
    };
}
pub(crate) use try_from_int_to_int;

/// Helper macro to implement `TryFrom` for a conversion from a unsigned int to a smaller or
/// equal sized signed int.
/// This is needed because `bnum` does not implement `TryFrom` for all of those conversions.
macro_rules! try_from_uint_to_int {
    ($input: ty, $output: ty) => {
        // statically assert that...
        // input is unsigned
        static_assertions::const_assert_eq!(stringify!($input).as_bytes()[0], b'U');
        // output is signed
        static_assertions::const_assert_eq!(stringify!($output).as_bytes()[0], b'I');
        // input is bigger than output (otherwise we would not need a `TryFrom` impl)
        static_assertions::const_assert!(
            core::mem::size_of::<$input>() >= core::mem::size_of::<$output>()
        );

        impl TryFrom<$input> for $output {
            type Error = $crate::ConversionOverflowError;

            fn try_from(value: $input) -> Result<Self, Self::Error> {
                use bnum::prelude::As;
                // $input::MAX has to be bigger than $output::MAX, so we can just cast it
                if value.0 > Self::MAX.0.as_() {
                    return Err(Self::Error::new(stringify!($input), stringify!($output)));
                }

                // at this point we know it fits
                Ok(Self(value.0.as_()))
            }
        }
    };
}
pub(crate) use try_from_uint_to_int;

#[cfg(test)]
pub(crate) fn test_try_from_uint_to_int<I, O>(input_type: &'static str, output_type: &'static str)
where
    I: super::num_consts::NumConsts
        + From<u32>
        + Copy
        + TryFrom<O, Error = crate::ConversionOverflowError>
        + core::fmt::Debug
        + core::ops::Add<Output = I>,
    O: TryFrom<I, Error = crate::ConversionOverflowError>
        + From<u32>
        + super::num_consts::NumConsts
        + core::cmp::PartialEq
        + core::fmt::Debug,
    String: From<I>,
{
    let v = I::MAX;
    assert_eq!(
        O::try_from(v),
        Err(crate::ConversionOverflowError::new(input_type, output_type)),
        "input::MAX value should not fit"
    );

    let max = I::try_from(O::MAX).unwrap();
    assert_eq!(O::try_from(max), Ok(O::MAX), "output::MAX value should fit");

    // but $output::MAX + 1 should not fit
    let v = max + I::ONE;
    assert_eq!(
        O::try_from(v),
        Err(crate::ConversionOverflowError::new(input_type, output_type)),
        "output::MAX + 1 should not fit"
    );

    // zero should work
    let v = I::ZERO;
    assert_eq!(O::try_from(v), Ok(O::ZERO), "zero should fit");

    // 42 should work
    assert_eq!(
        O::try_from(I::from(42u32)),
        Ok(O::from(42u32)),
        "42 should fit"
    )
}

#[cfg(test)]
pub(crate) fn test_try_from_int_to_uint<I, O>(input_type: &'static str, output_type: &'static str)
where
    I: super::num_consts::NumConsts
        + From<i32>
        + Copy
        + TryFrom<O>
        + core::fmt::Debug
        + core::ops::Add<Output = I>,
    O: TryFrom<I, Error = crate::ConversionOverflowError>
        + From<u32>
        + super::num_consts::NumConsts
        + core::cmp::PartialEq
        + core::fmt::Debug,
    String: From<I>,
    <I as core::convert::TryFrom<O>>::Error: core::fmt::Debug,
{
    if core::mem::size_of::<I>() <= core::mem::size_of::<O>() {
        // if the input type is smaller than the output type, then `I::MAX` should fit into `O`
        let v = I::MAX;
        assert_eq!(
            O::try_from(v),
            Ok(O::try_from(v).unwrap()),
            "input::MAX value should fit"
        );
    } else {
        // if the input is bigger than the output, then `I::MAX` should not fit into `O`
        let v = I::MAX;
        assert_eq!(
            O::try_from(v),
            Err(crate::ConversionOverflowError::new(input_type, output_type)),
            "input::MAX value should not fit"
        );
        // but `O::MAX` should fit
        let max = I::try_from(O::MAX).unwrap();
        assert_eq!(
            O::try_from(max),
            Ok(O::try_from(max).unwrap()),
            "output::MAX value should fit"
        );
        // while `O::MAX + 1` should not
        let v = max + I::ONE;
        assert_eq!(
            O::try_from(v),
            Err(crate::ConversionOverflowError::new(input_type, output_type)),
            "output::MAX + 1 should not fit"
        );
    }

    // negative numbers should fail
    let v = I::from(-42i32);
    assert_eq!(
        O::try_from(v),
        Err(crate::ConversionOverflowError::new(input_type, output_type,)),
        "negative numbers should not fit"
    );

    // zero should work
    let v = I::ZERO;
    assert_eq!(O::try_from(v), Ok(O::ZERO), "zero should fit");

    // 42 should work
    assert_eq!(
        O::try_from(I::from(42i32)),
        Ok(O::from(42u32)),
        "42 should fit"
    )
}

/// Helper macro to implement `TryFrom` for a conversion from a signed int to an unsigned int.
/// This is needed because `bnum` does not implement `TryFrom` for all of those conversions.
macro_rules! try_from_int_to_uint {
    ($input: ty, $output: ty) => {
        // statically assert that...
        // input is signed
        static_assertions::const_assert_eq!(stringify!($input).as_bytes()[0], b'I');
        // output is unsigned
        static_assertions::const_assert_eq!(stringify!($output).as_bytes()[0], b'U');

        impl TryFrom<$input> for $output {
            type Error = ConversionOverflowError;

            fn try_from(value: $input) -> Result<Self, Self::Error> {
                use bnum::prelude::As;
                // if $input::MAX is smaller than $output::MAX, we only need to check the sign
                if core::mem::size_of::<$input>() <= core::mem::size_of::<$output>() {
                    if value.is_negative() {
                        return Err(ConversionOverflowError::new(
                            stringify!($input),
                            stringify!($output),
                        ));
                    }

                    // otherwise we can just cast it
                    Ok(Self(value.0.as_()))
                } else {
                    // $output::MAX is smaller than $input::MAX.
                    // If it is negative or too big, we error.
                    // We can safely cast $output::MAX to $input size
                    if value.is_negative() || value.0 > <$output>::MAX.0.as_() {
                        return Err(ConversionOverflowError::new(
                            stringify!($input),
                            stringify!($output),
                        ));
                    }

                    // at this point we know it fits
                    Ok(Self(value.0.as_()))
                }
            }
        }
    };
}
pub(crate) use try_from_int_to_uint;

macro_rules! from_and_to_bytes {
    ($inner: ty, $byte_size: literal) => {
        /// Constructs new value from big endian bytes
        #[must_use]
        pub const fn from_be_bytes(data: [u8; $byte_size]) -> Self {
            Self(<$inner>::from_be_bytes(data))
        }

        /// Constructs new value from little endian bytes
        #[must_use]
        pub const fn from_le_bytes(data: [u8; $byte_size]) -> Self {
            Self(<$inner>::from_le_bytes(data))
        }

        /// Returns a copy of the number as big endian bytes.
        #[must_use = "this returns the result of the operation, without modifying the original"]
        pub const fn to_be_bytes(self) -> [u8; $byte_size] {
            self.0.to_be_bytes()
        }

        /// Returns a copy of the number as little endian bytes.
        #[must_use = "this returns the result of the operation, without modifying the original"]
        pub const fn to_le_bytes(self) -> [u8; $byte_size] {
            self.0.to_le_bytes()
        }
    };
}
pub(crate) use from_and_to_bytes;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn grow_be_int_works() {
        // test against rust std's integers
        let i32s = [i32::MIN, -1, 0, 1, 42, i32::MAX];
        for i in i32s {
            assert_eq!(grow_be_int(i.to_be_bytes()), (i as i64).to_be_bytes());
            assert_eq!(grow_be_int(i.to_be_bytes()), (i as i128).to_be_bytes());
        }
        let i8s = [i8::MIN, -1, 0, 1, 42, i8::MAX];
        for i in i8s {
            assert_eq!(grow_be_int(i.to_be_bytes()), (i as i16).to_be_bytes());
            assert_eq!(grow_be_int(i.to_be_bytes()), (i as i32).to_be_bytes());
            assert_eq!(grow_be_int(i.to_be_bytes()), (i as i64).to_be_bytes());
            assert_eq!(grow_be_int(i.to_be_bytes()), (i as i128).to_be_bytes());
        }
    }

    #[test]
    fn shrink_be_int_works() {
        // test against rust std's integers
        let i32s = [-42, -1, 0i32, 1, 42];
        for i in i32s {
            assert_eq!(
                shrink_be_int(i.to_be_bytes()),
                Some((i as i16).to_be_bytes())
            );
            assert_eq!(
                shrink_be_int(i.to_be_bytes()),
                Some((i as i8).to_be_bytes())
            );
        }
        // these should be too big to fit into an i16 or i8
        let oob = [
            i32::MIN,
            i32::MIN + 10,
            i32::MIN + 1234,
            i32::MAX - 1234,
            i32::MAX - 10,
            i32::MAX,
        ];
        for i in oob {
            // 32 -> 16 bit
            assert_eq!(shrink_be_int::<4, 2>(i.to_be_bytes()), None);
            // 32 -> 8 bit
            assert_eq!(shrink_be_int::<4, 1>(i.to_be_bytes()), None);
        }

        // compare against whole i16 range
        for i in i16::MIN..=i16::MAX {
            let cast = i as i8 as i16;
            if i == cast {
                // if the cast is lossless, `shrink_be_int` should get the same result
                assert_eq!(
                    shrink_be_int::<2, 1>(i.to_be_bytes()),
                    Some((i as i8).to_be_bytes())
                );
            } else {
                // otherwise, we should get None
                assert_eq!(shrink_be_int::<2, 1>(i.to_be_bytes()), None);
            }
        }
    }
}