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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
use crate::{
blocks::{BlockDifficulty, BlockHeaderSpec, BlockJustification, Resistable, Verifiable},
BlockNc, BlockTs,
};
use scsys::prelude::{hasher, Hashable, H256};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct BlockHeader {
pub difficulty: BlockDifficulty,
pub justification: BlockJustification,
pub nonce: BlockNc,
pub parent: H256,
pub rand: u128, pub root: H256,
pub timestamp: BlockTs,
}
impl BlockHeader {
pub fn new(
difficulty: BlockDifficulty,
justification: BlockJustification,
nonce: BlockNc,
parent: H256,
rand: u128,
root: H256,
timestamp: i64,
) -> Self {
Self {
difficulty,
justification,
nonce,
parent,
rand,
root,
timestamp,
}
}
}
impl Resistable for BlockHeader {
fn pos_difficulty(&self) -> H256 {
self.difficulty.pos_difficulty()
}
fn pow_difficulty(&self) -> H256 {
self.difficulty.pow_difficulty()
}
}
impl Verifiable for BlockHeader {
fn vrf_hash(&self) -> Vec<u8> {
self.justification.vrf_hash()
}
fn vrf_proof(&self) -> Vec<u8> {
self.justification.vrf_proof()
}
fn vrf_pub_key(&self) -> Vec<u8> {
self.justification.vrf_pub_key()
}
}
impl BlockHeaderSpec for BlockHeader {
fn merkle_root(&self) -> H256 {
self.root
}
fn nonce(&self) -> BlockNc {
self.nonce
}
fn parent(&self) -> H256 {
self.parent
}
fn rand(&self) -> u128 {
self.rand
}
fn timestamp(&self) -> BlockTs {
self.timestamp
}
}
impl Hashable for BlockHeader {
fn hash(&self) -> H256 {
hasher(&serde_json::to_string(&self).unwrap())
.as_slice()
.to_owned()
.into()
}
}
impl std::fmt::Display for BlockHeader {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", serde_json::to_string(&self).unwrap())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
blocks::generate_random_block_header, transactions::generate_random_signed_transaction,
};
#[test]
fn test_default_block_header() {
let a: BlockHeader =
generate_random_block_header(vec![generate_random_signed_transaction()]);
let b = a.clone();
assert_eq!(&a, &b);
}
}