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
use crate::u256;
use crate::{Deserializable, DeserializationError, Serializable};
use byteorder::{LittleEndian, ReadBytesExt};
#[derive(Copy, Clone, Debug)]
pub enum InventoryType {
Tx = 1,
Block = 2,
FilteredBlock = 3,
CompactBlock = 4,
WitnessTx = 5,
WitnessBlock = 6,
FilteredWitnessBlock = 7,
}
impl Serializable for InventoryType {
fn serialize<W>(&self, target: &mut W) -> Result<(), std::io::Error>
where
W: std::io::Write,
{
(*self as u32).serialize(target)
}
}
impl Deserializable for InventoryType {
fn deserialize<R>(target: &mut R) -> Result<Self, DeserializationError>
where
R: std::io::Read,
{
let value = target.read_u32::<LittleEndian>()?;
match value {
1 => Ok(InventoryType::Tx),
2 => Ok(InventoryType::Block),
3 => Ok(InventoryType::FilteredBlock),
4 => Ok(InventoryType::CompactBlock),
5 => Ok(InventoryType::WitnessTx),
6 => Ok(InventoryType::WitnessBlock),
7 => Ok(InventoryType::FilteredWitnessBlock),
_ => Err(DeserializationError::Parse(format!(
"Unreadable Inventory Type: {}",
value
))),
}
}
}
#[derive(Debug)]
pub struct InventoryData {
pub inventory_type: InventoryType,
pub hash: u256,
}
impl InventoryData {
pub fn from(inv: InventoryType, hash: u256) -> InventoryData {
InventoryData {
inventory_type: inv,
hash: hash,
}
}
pub fn len(&self) -> usize {
4 + 32
}
}
impl Serializable for InventoryData {
fn serialize<W>(&self, target: &mut W) -> Result<(), std::io::Error>
where
W: std::io::Write,
{
self.inventory_type.serialize(target)?;
self.hash.serialize(target)
}
}
impl Deserializable for InventoryData {
fn deserialize<R>(target: &mut R) -> Result<Self, DeserializationError>
where
R: std::io::Read,
{
Ok(InventoryData {
inventory_type: InventoryType::deserialize(target)?,
hash: u256::deserialize(target)?,
})
}
}