#[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 {
pub fn default() -> Self {
UserTransactionData {
cycle: 0,
data: vec![],
timestamp: 0,
}
}
pub fn new(data: Vec<u8>, cycle: u64, timestamp: u64) -> Self {
UserTransactionData {
data,
cycle,
timestamp,
}
}
pub fn new_with_current_time(data: Vec<u8>, cycle: u64) -> Self {
let timestamp = ic_timestamp();
UserTransactionData {
data,
cycle,
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()..], ×tamp.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());
}
}
}