hyperhasher/
blockchain.rs1use std::fmt::{
5 Formatter,
6 Display,
7 Result
8};
9pub use blake3;
10pub const IBD: &'static str = "INITIAL.BLOCK.DATA";
11
12
13
14
15
16
17
18
19#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
20pub struct HashString([u8;32]);
21impl HashString {
22 pub fn new(bytes: [u8;32]) -> Self {
23 Self(bytes)
24 }
25 fn to_blakehash(&self) -> blake3::Hash {
26 blake3::Hash::from(self.0)
27 }
28}
29impl From<[u8;32]> for HashString {
30 fn from(bytes: [u8;32]) -> Self {
31 Self(bytes)
32 }
33}
34impl From<&[u8;32]> for HashString {
35 fn from(bytes: &[u8;32]) -> Self {
36 Self(*bytes)
37 }
38}
39impl From<blake3::Hash> for HashString {
40 fn from(hash: blake3::Hash) -> Self {
41 HashString::from(hash.as_bytes())
42 }
43}
44impl From<HashString> for [u8;32] {
45 fn from(hash: HashString) -> Self {
46 hash.0
47 }
48}
49impl Display for HashString {
50 fn fmt(&self, f: &mut Formatter) -> Result {
51 let hex = self.to_blakehash().to_hex();
52 let hex: &str = hex.as_str();
53 f.write_str(hex)
54 }
55}
56
57
58
59
60
61
62#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
63pub struct Block <T: Copy + Display> {
64 pub previos_hash: HashString,
65 pub data: T
66}
67impl<T: Copy + Display> Display for Block<T> {
68 fn fmt(&self, f: &mut Formatter) -> Result {
69 write!(
70 f,
71 "{}+{}",
72 self.previos_hash,
73 self.data
74 )
75 }
76}
77impl<T: Copy + Display> Block<T> {
78 pub fn new(data: T, chain: &Chain) -> Block<T> {
79 Block {
80 previos_hash: chain.hash,
81 data: data
82 }
83 }
84 pub(crate) fn initial(data: T) -> Block<T> {
85 Block {
86 previos_hash: HashString::from(crate::consts::INITIAL_BLOCK_PREVIOS_HASH),
87 data
88 }
89 }
90}
91
92
93
94
95
96#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
97pub struct Chain {
98 pub hash: HashString
99}
100impl Chain {
101 pub fn new<T: Copy + Display>(initial_block_data: T) -> Self {
102 Self {
103 hash: crate::hash!(Block::initial(initial_block_data))
104 }
105 }
106 pub fn push<T: Copy + Display>(&mut self, block: Block<T>) -> HashString {
107 self.hash = crate::hash!(block);
108 self.hash
109 }
110}
111impl Display for Chain {
112 fn fmt(&self, f: &mut Formatter) -> Result {
113 write!(
114 f,
115 "{}",
116 self.hash
117 )
118 }
119}