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
#[cfg(feature = "node")]
use crate::node::Header;

#[cfg(feature = "node")]
use crate::node::Wire;

use crate::blocks::{BlockHash, BlockType};
use crate::bytes::Bytes;
use crate::keys::public::{from_address, to_address};
use crate::units::rai::{deserialize_from_hex, serialize_to_hex};
use crate::{Public, Rai, Signature, Work};

use serde::{Deserialize, Serialize};
use std::convert::TryFrom;

#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct SendBlock {
    /// The hash of the previous block in this account.
    pub previous: BlockHash,

    #[serde(serialize_with = "to_address", deserialize_with = "from_address")]
    pub destination: Public,

    #[serde(
        serialize_with = "serialize_to_hex",
        deserialize_with = "deserialize_from_hex"
    )]
    pub balance: Rai,

    pub work: Option<Work>,
    pub signature: Option<Signature>,
}

impl SendBlock {
    pub const LEN: usize = 152;

    pub fn new(previous: BlockHash, destination: Public, balance: Rai) -> Self {
        Self {
            previous,
            destination,
            balance,
            work: None,
            signature: None,
        }
    }
}

#[cfg(feature = "node")]
impl Wire for SendBlock {
    fn serialize(&self) -> Vec<u8> {
        unimplemented!()
    }

    fn deserialize(_: Option<&Header>, data: &[u8]) -> anyhow::Result<Self>
    where
        Self: Sized,
    {
        let mut data = Bytes::new(data);
        let previous = BlockHash::try_from(data.slice(BlockHash::LEN)?)?;
        let destination = Public::try_from(data.slice(Public::LEN)?)?;
        let balance = Rai::try_from(data.slice(Rai::LEN)?)?;
        let work = Some(Work::try_from(data.slice(Work::LEN)?)?);
        let signature = Some(Signature::try_from(data.slice(Signature::LEN)?)?);

        Ok(Self {
            previous,
            destination,
            balance,
            work,
            signature,
        })
    }

    fn len(header: Option<&Header>) -> anyhow::Result<usize>
    where
        Self: Sized,
    {
        debug_assert!(header.is_some());
        let header = header.unwrap();
        debug_assert_eq!(header.ext().block_type()?, BlockType::Send);

        Ok(SendBlock::LEN)
    }
}