cs_mwc_bch/messages/
inv_vect.rs

1use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
2use std::io;
3use std::io::{Read, Write};
4use util::{Hash256, Result, Serializable};
5
6// Inventory vector types
7
8/// May be ignored
9pub const INV_VECT_ERROR: u32 = 0;
10/// Hash of a transaction
11pub const INV_VECT_TX: u32 = 1;
12/// Hash of a block header.
13pub const INV_VECT_BLOCK: u32 = 2;
14/// Hash of a block header. Indicates the reply should be a merkleblock message.
15pub const INV_VECT_FILTERED_BLOCK: u32 = 3;
16/// Hash of a block header. Indicates the reply should be a cmpctblock message.
17pub const INV_VECT_COMPACT_BLOCK: u32 = 4;
18
19/// Inventory vector describing an object being requested or announced
20#[derive(Debug, PartialEq, Eq, Hash, Clone)]
21pub struct InvVect {
22    // Object type linked to this inventory
23    pub obj_type: u32,
24    /// Hash of the object
25    pub hash: Hash256,
26}
27
28impl InvVect {
29    /// Size of the inventory vector in bytes
30    pub const SIZE: usize = 36;
31
32    /// Returns the size of the inventory vector in bytes
33    pub fn size(&self) -> usize {
34        InvVect::SIZE
35    }
36}
37
38impl Serializable<InvVect> for InvVect {
39    fn read(reader: &mut dyn Read) -> Result<InvVect> {
40        let inv_vect = InvVect {
41            obj_type: reader.read_u32::<LittleEndian>()?,
42            hash: Hash256::read(reader)?,
43        };
44        Ok(inv_vect)
45    }
46
47    fn write(&self, writer: &mut dyn Write) -> io::Result<()> {
48        writer.write_u32::<LittleEndian>(self.obj_type as u32)?;
49        self.hash.write(writer)
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56    use std::io::Cursor;
57
58    #[test]
59    fn write_read() {
60        let mut v = Vec::new();
61        let iv = InvVect {
62            obj_type: INV_VECT_TX,
63            hash: Hash256([8; 32]),
64        };
65        iv.write(&mut v).unwrap();
66        assert!(v.len() == iv.size());
67        assert!(InvVect::read(&mut Cursor::new(&v)).unwrap() == iv);
68    }
69}