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
use crate::{dpc::DPCTransactions, BlockHeader};
use snarkos_errors::objects::BlockError;
use snarkos_models::objects::{BlockScheme, Transaction};
use snarkos_utilities::{
bytes::{FromBytes, ToBytes},
to_bytes,
variable_length_integer::variable_length_integer,
};
use std::io::{Read, Result as IoResult, Write};
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Block<T: Transaction> {
pub header: BlockHeader,
pub transactions: DPCTransactions<T>,
}
impl<T: Transaction> BlockScheme for Block<T> {
type BlockHeader = BlockHeader;
type Transaction = T;
fn header(&self) -> &Self::BlockHeader {
&self.header
}
fn transactions(&self) -> &[Self::Transaction] {
self.transactions.as_slice()
}
}
impl<T: Transaction> ToBytes for Block<T> {
#[inline]
fn write<W: Write>(&self, mut writer: W) -> IoResult<()> {
self.header.write(&mut writer)?;
self.transactions.write(&mut writer)
}
}
impl<T: Transaction> FromBytes for Block<T> {
#[inline]
fn read<R: Read>(mut reader: R) -> IoResult<Self> {
let header: BlockHeader = FromBytes::read(&mut reader)?;
let transactions: DPCTransactions<T> = FromBytes::read(&mut reader)?;
Ok(Self { header, transactions })
}
}
impl<T: Transaction> Block<T> {
pub fn serialize(&self) -> Result<Vec<u8>, BlockError> {
let mut serialization = vec![];
serialization.extend(&self.header.serialize().to_vec());
serialization.extend(&variable_length_integer(self.transactions.len() as u64));
for transaction in self.transactions.iter() {
serialization.extend(to_bytes![transaction]?)
}
Ok(serialization)
}
pub fn deserialize(bytes: &Vec<u8>) -> Result<Self, BlockError> {
const HEADER_SIZE: usize = BlockHeader::size();
let (header_bytes, transactions_bytes) = bytes.split_at(HEADER_SIZE);
let mut header_array = [0u8; HEADER_SIZE];
header_array.copy_from_slice(&header_bytes[0..HEADER_SIZE]);
let header = BlockHeader::deserialize(&header_array);
let transactions: DPCTransactions<T> = FromBytes::read(transactions_bytes)?;
Ok(Block { header, transactions })
}
}