1use std_shims::{
2 vec,
3 vec::Vec,
4 io::{self, Read, Write},
5};
6
7use crate::{
8 io::*,
9 primitives::keccak256,
10 merkle::merkle_root,
11 transaction::{Input, Transaction},
12};
13
14const CORRECT_BLOCK_HASH_202612: [u8; 32] =
15 hex_literal::hex!("426d16cff04c71f8b16340b722dc4010a2dd3831c22041431f772547ba6e331a");
16const EXISTING_BLOCK_HASH_202612: [u8; 32] =
17 hex_literal::hex!("bbd604d2ba11ba27935e006ed39c9bfdd99b76bf4a50654bc1e1e61217962698");
18
19#[derive(Clone, PartialEq, Eq, Debug)]
21pub struct BlockHeader {
22 pub hardfork_version: u8,
26 pub hardfork_signal: u8,
30 pub timestamp: u64,
32 pub previous: [u8; 32],
34 pub nonce: u32,
39}
40
41impl BlockHeader {
42 pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
44 write_varint(&self.hardfork_version, w)?;
45 write_varint(&self.hardfork_signal, w)?;
46 write_varint(&self.timestamp, w)?;
47 w.write_all(&self.previous)?;
48 w.write_all(&self.nonce.to_le_bytes())
49 }
50
51 pub fn serialize(&self) -> Vec<u8> {
53 let mut serialized = vec![];
54 self.write(&mut serialized).expect("write failed but <Vec as io::Write> doesn't fail");
55 serialized
56 }
57
58 pub fn read<R: Read>(r: &mut R) -> io::Result<BlockHeader> {
60 Ok(BlockHeader {
61 hardfork_version: read_varint(r)?,
62 hardfork_signal: read_varint(r)?,
63 timestamp: read_varint(r)?,
64 previous: read_bytes(r)?,
65 nonce: read_bytes(r).map(u32::from_le_bytes)?,
66 })
67 }
68}
69
70#[derive(Clone, PartialEq, Eq, Debug)]
72pub struct Block {
73 pub header: BlockHeader,
75 pub miner_transaction: Transaction,
77 pub transactions: Vec<[u8; 32]>,
79}
80
81impl Block {
82 pub fn number(&self) -> Option<usize> {
90 match &self.miner_transaction {
91 Transaction::V1 { prefix, .. } | Transaction::V2 { prefix, .. } => {
92 match prefix.inputs.first() {
93 Some(Input::Gen(number)) => Some(*number),
94 _ => None,
95 }
96 }
97 }
98 }
99
100 pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
102 self.header.write(w)?;
103 self.miner_transaction.write(w)?;
104 write_varint(&self.transactions.len(), w)?;
105 for tx in &self.transactions {
106 w.write_all(tx)?;
107 }
108 Ok(())
109 }
110
111 pub fn serialize(&self) -> Vec<u8> {
113 let mut serialized = vec![];
114 self.write(&mut serialized).expect("write failed but <Vec as io::Write> doesn't fail");
115 serialized
116 }
117
118 pub fn serialize_pow_hash(&self) -> Vec<u8> {
123 let mut blob = self.header.serialize();
124
125 let mut transactions = Vec::with_capacity(self.transactions.len() + 1);
126 transactions.push(self.miner_transaction.hash());
127 transactions.extend_from_slice(&self.transactions);
128
129 blob.extend_from_slice(
130 &merkle_root(transactions)
131 .expect("the tree will not be empty, the miner tx is always present"),
132 );
133 write_varint(&(1 + self.transactions.len()), &mut blob)
134 .expect("write failed but <Vec as io::Write> doesn't fail");
135 blob
136 }
137
138 pub fn hash(&self) -> [u8; 32] {
140 let mut hashable = self.serialize_pow_hash();
141 let mut hashing_blob = Vec::with_capacity(9 + hashable.len());
144 write_varint(
145 &u64::try_from(hashable.len()).expect("length of block hash's preimage exceeded u64::MAX"),
146 &mut hashing_blob,
147 )
148 .expect("write failed but <Vec as io::Write> doesn't fail");
149 hashing_blob.append(&mut hashable);
150
151 let hash = keccak256(hashing_blob);
152 if hash == CORRECT_BLOCK_HASH_202612 {
153 return EXISTING_BLOCK_HASH_202612;
154 };
155 hash
156 }
157
158 pub fn read<R: Read>(r: &mut R) -> io::Result<Block> {
160 Ok(Block {
161 header: BlockHeader::read(r)?,
162 miner_transaction: Transaction::read(r)?,
163 transactions: (0_usize .. read_varint(r)?)
164 .map(|_| read_bytes(r))
165 .collect::<Result<_, _>>()?,
166 })
167 }
168}