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
#[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());
        }
    }
}