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 VarInt::write(&self.hardfork_version, w)?;
45 VarInt::write(&self.hardfork_signal, w)?;
46 VarInt::write(&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: VarInt::read(r)?,
62 hardfork_signal: VarInt::read(r)?,
63 timestamp: VarInt::read(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 miner_transaction: Transaction,
77 pub transactions: Vec<[u8; 32]>,
79}
80
81impl Block {
82 pub const MAX_TRANSACTIONS: usize = 0x10000000;
100
101 pub fn new(
107 header: BlockHeader,
108 miner_transaction: Transaction,
109 transactions: Vec<[u8; 32]>,
110 ) -> Option<Block> {
111 {
115 let inputs = &miner_transaction.prefix().inputs;
116 if inputs.len() != 1 {
117 None?;
118 }
119 match inputs[0] {
120 Input::Gen(_number) => {}
121 _ => None?,
122 }
123 }
124
125 Some(Block { header, miner_transaction, transactions })
126 }
127
128 pub fn number(&self) -> usize {
130 match &self.miner_transaction {
131 Transaction::V1 { prefix, .. } | Transaction::V2 { prefix, .. } => {
132 match prefix.inputs.first() {
133 Some(Input::Gen(number)) => *number,
134 _ => panic!("invalid miner transaction accepted into block"),
135 }
136 }
137 }
138 }
139
140 pub fn miner_transaction(&self) -> &Transaction {
142 &self.miner_transaction
143 }
144
145 pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
147 self.header.write(w)?;
148 self.miner_transaction.write(w)?;
149 VarInt::write(&self.transactions.len(), w)?;
150 for tx in &self.transactions {
151 w.write_all(tx)?;
152 }
153 Ok(())
154 }
155
156 pub fn serialize(&self) -> Vec<u8> {
158 let mut serialized = vec![];
159 self.write(&mut serialized).expect("write failed but <Vec as io::Write> doesn't fail");
160 serialized
161 }
162
163 pub fn serialize_pow_hash(&self) -> Vec<u8> {
168 let mut blob = self.header.serialize();
169
170 let mut transactions = Vec::with_capacity(self.transactions.len() + 1);
171 transactions.push(self.miner_transaction.hash());
172 transactions.extend_from_slice(&self.transactions);
173
174 blob.extend_from_slice(
175 &merkle_root(transactions)
176 .expect("the tree will not be empty, the miner tx is always present"),
177 );
178 VarInt::write(&(1 + self.transactions.len()), &mut blob)
179 .expect("write failed but <Vec as io::Write> doesn't fail");
180 blob
181 }
182
183 pub fn hash(&self) -> [u8; 32] {
185 let mut hashable = self.serialize_pow_hash();
186 let mut hashing_blob = Vec::with_capacity(<usize as VarInt>::UPPER_BOUND + hashable.len());
189 VarInt::write(
190 &u64::try_from(hashable.len()).expect("length of block hash's preimage exceeded u64::MAX"),
191 &mut hashing_blob,
192 )
193 .expect("write failed but <Vec as io::Write> doesn't fail");
194 hashing_blob.append(&mut hashable);
195
196 let hash = keccak256(hashing_blob);
197 if hash == CORRECT_BLOCK_HASH_202612 {
198 return EXISTING_BLOCK_HASH_202612;
199 };
200 hash
201 }
202
203 pub fn read<R: Read>(r: &mut R) -> io::Result<Block> {
209 let header = BlockHeader::read(r)?;
210
211 let miner_transaction = Transaction::read(r)?;
212
213 let transactions: usize = VarInt::read(r)?;
214 if transactions >= Self::MAX_TRANSACTIONS {
215 Err(io::Error::other("amount of transaction exceeds limit"))?;
216 }
217 let transactions = (0 .. transactions).map(|_| read_bytes(r)).collect::<Result<_, _>>()?;
218
219 Block::new(header, miner_transaction, transactions)
220 .ok_or_else(|| io::Error::other("block failed sanity checks"))
221 }
222}