secret_toolkit_utils/
padding.rs

1use cosmwasm_std::{Binary, Response};
2
3/// Take a Vec<u8> and pad it up to a multiple of `block_size`, using spaces at the end.
4pub fn space_pad(message: &mut Vec<u8>, block_size: usize) -> &mut Vec<u8> {
5    let len = message.len();
6    let surplus = len % block_size;
7    if surplus == 0 {
8        return message;
9    }
10
11    let missing = block_size - surplus;
12    message.reserve(missing);
13    message.extend(std::iter::repeat(b' ').take(missing));
14    message
15}
16
17/// Pad the data and logs in a `Result<Response, _>` to the block size, with spaces.
18// Users don't need to care about it as the type `T` has a default, and will
19// always be known in the context of the caller.
20pub fn pad_handle_result<T, E>(
21    response: Result<Response<T>, E>,
22    block_size: usize,
23) -> Result<Response<T>, E>
24where
25    T: Clone + std::fmt::Debug + PartialEq + schemars::JsonSchema,
26{
27    response.map(|mut response| {
28        response.data = response.data.map(|mut data| {
29            space_pad(&mut data.0, block_size);
30            data
31        });
32        for attribute in &mut response.attributes {
33            // do not pad plaintext attributes
34            if attribute.encrypted {
35                // Safety: These two are safe because we know the characters that
36                // `space_pad` appends are valid UTF-8
37                unsafe { space_pad(attribute.key.as_mut_vec(), block_size) };
38                unsafe { space_pad(attribute.value.as_mut_vec(), block_size) };
39            }
40        }
41        response
42    })
43}
44
45/// Pad a `QueryResult` with spaces
46pub fn pad_query_result<E>(response: Result<Binary, E>, block_size: usize) -> Result<Binary, E> {
47    response.map(|mut response| {
48        space_pad(&mut response.0, block_size);
49        response
50    })
51}