b3-users 0.1.4

A simple user management system for the Internet Computer
Documentation
#[cfg(test)]
use crate::mocks::ic_timestamp;

#[cfg(not(test))]
use ic_cdk::api::time as ic_timestamp;

use ic_cdk::export::{candid::CandidType, serde::Deserialize};

#[derive(CandidType, Debug, Deserialize, Clone, PartialEq)]
pub struct UserTransactionData {
    pub data: Vec<u8>,
    pub cycle: u64,
    pub timestamp: u64,
}

impl UserTransactionData {
    /// Creates a default TransactionData with empty data and a timestamp of 0.
    pub fn default() -> Self {
        UserTransactionData {
            cycle: 0,
            data: vec![],
            timestamp: 0,
        }
    }

    /// Creates a new TransactionData with the given data and timestamp.
    pub fn new(data: Vec<u8>, cycle: u64, timestamp: u64) -> Self {
        UserTransactionData {
            data,
            cycle,
            timestamp,
        }
    }

    /// Creates a new TransactionData with the given data and the current timestamp.
    pub fn new_with_current_time(data: Vec<u8>, cycle: u64) -> Self {
        let timestamp = ic_timestamp();

        UserTransactionData {
            data,
            cycle,
            timestamp,
        }
    }

    /// Computes the hash of the transaction by concatenating the data and the timestamp.
    pub fn get_hash(&self) -> Vec<u8> {
        let mut hash = vec![];
        hash.extend_from_slice(&self.data);
        hash.extend_from_slice(&self.timestamp.to_be_bytes());

        hash
    }
}

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

    proptest! {
        #[test]
        fn test_transaction_hash(data: Vec<u8>,cycle: u64, timestamp: u64) {
            let transaction = UserTransactionData::new(data.clone(), cycle, timestamp);
            let hash = transaction.get_hash();

            assert_eq!(hash.len(), data.len() + 8);
            assert_eq!(&hash[0..data.len()], data.as_slice());
            assert_eq!(&hash[data.len()..], &timestamp.to_be_bytes());
        }

        #[test]
        fn test_transaction_hash_with_current_time(data: Vec<u8>, cycle: u64) {
            let transaction = UserTransactionData::new_with_current_time(data.clone(), cycle);
            let hash = transaction.get_hash();

            assert_eq!(hash.len(), data.len() + 8);
            assert_eq!(&hash[0..data.len()], data.as_slice());
            assert_eq!(&hash[data.len()..], &transaction.timestamp.to_be_bytes());
        }
    }
}