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
use std::collections::BTreeSet;
use tiny_keccak::{Hasher, Sha3};
use crate::{DbcContentHash, Hash};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct DbcTransaction {
pub inputs: BTreeSet<DbcContentHash>,
pub outputs: BTreeSet<DbcContentHash>,
}
impl DbcTransaction {
pub fn new(inputs: BTreeSet<DbcContentHash>, outputs: BTreeSet<DbcContentHash>) -> Self {
Self { inputs, outputs }
}
pub fn hash(&self) -> Hash {
let mut sha3 = Sha3::v256();
for input in self.inputs.iter() {
sha3.update(input);
}
for output in self.outputs.iter() {
sha3.update(output);
}
let mut hash = [0; 32];
sha3.finalize(&mut hash);
Hash(hash)
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck_macros::quickcheck;
use crate::sha3_256;
#[quickcheck]
fn prop_hash_is_independent_of_order(inputs: Vec<u64>, outputs: Vec<u64>) {
let input_hashes: Vec<DbcContentHash> = inputs
.iter()
.map(|i| Hash(sha3_256(&i.to_be_bytes())))
.collect();
let output_hashes: Vec<DbcContentHash> = outputs
.iter()
.map(|i| Hash(sha3_256(&i.to_be_bytes())))
.collect();
let forward_hash = DbcTransaction::new(
input_hashes.iter().cloned().collect(),
output_hashes.iter().cloned().collect(),
)
.hash();
let reverse_hash = DbcTransaction::new(
input_hashes.into_iter().rev().collect(),
output_hashes.into_iter().rev().collect(),
)
.hash();
assert_eq!(forward_hash, reverse_hash);
}
}