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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
//! Wrapper for blockstamp

use crate::*;

#[derive(Clone, Copy, Debug, Error, PartialEq)]
/// Error when converting bytes to Blockstamp
pub enum BlockstampFromBytesError {
    /// Given bytes have invalid length
    #[error("Given bytes have invalid length")]
    InvalidLen,
}

/// Type of errors for [`Blockstamp`] parsing.
///
/// [`Blockstamp`]: struct.Blockstamp.html
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
pub enum BlockstampParseError {
    /// Given bytes have invalid length
    #[error("Given bytes have invalid length")]
    InvalidLen,
    /// Given string have invalid format
    #[error("Given string have invalid format")]
    InvalidFormat,
    /// [`BlockNumber`](struct.BlockHash.html) part is not a valid number.
    #[error("BlockNumber part is not a valid number.")]
    InvalidBlockNumber,
    /// [`BlockHash`](struct.BlockHash.html) part is not a valid hex number.
    #[error("BlockHash part is not a valid hex number.")]
    InvalidBlockHash(BaseConversionError),
}

impl From<BaseConversionError> for BlockstampParseError {
    fn from(e: BaseConversionError) -> Self {
        BlockstampParseError::InvalidBlockHash(e)
    }
}

/// A blockstamp (Unique ID).
///
/// It's composed of the [`BlockNumber`] and
/// the [`BlockHash`] of the block.
///
/// Thanks to blockchain immutability and frequent block production, it can
/// be used to date information.
///
/// [`BlockNumber`]: struct.BlockNumber.html
/// [`BlockHash`]: struct.BlockHash.html

#[derive(Copy, Clone, Default, Deserialize, PartialEq, Eq, Hash, Serialize)]
pub struct Blockstamp {
    /// Block Id.
    pub number: BlockNumber,
    /// Block hash.
    pub hash: BlockHash,
}

/// Previous blockstamp (BlockNumber-1, previous_hash)
pub type PreviousBlockstamp = Blockstamp;

impl Blockstamp {
    /// Blockstamp size (in bytes).
    pub const SIZE_IN_BYTES: usize = 36;
}

impl Into<[u8; Self::SIZE_IN_BYTES]> for Blockstamp {
    fn into(self) -> [u8; Self::SIZE_IN_BYTES] {
        let mut bytes = [0u8; Self::SIZE_IN_BYTES];

        bytes[..4].copy_from_slice(&self.number.0.to_be_bytes());

        unsafe {
            std::ptr::copy_nonoverlapping(
                (self.hash.0).0.as_ptr(),
                bytes[4..].as_mut_ptr(),
                Hash::SIZE_IN_BYTES,
            );
        }

        bytes
    }
}

impl Display for Blockstamp {
    fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
        write!(f, "{}-{}", self.number, self.hash)
    }
}

impl Debug for Blockstamp {
    fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
        write!(f, "Blockstamp({})", self)
    }
}

impl PartialOrd for Blockstamp {
    fn partial_cmp(&self, other: &Blockstamp) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Blockstamp {
    fn cmp(&self, other: &Blockstamp) -> Ordering {
        if self.number == other.number {
            self.hash.cmp(&other.hash)
        } else {
            self.number.cmp(&other.number)
        }
    }
}

impl FromBytes for Blockstamp {
    type Err = BlockstampFromBytesError;

    /// Create a `Blockstamp` from bytes.
    fn from_bytes(src: &[u8]) -> Result<Blockstamp, BlockstampFromBytesError> {
        if src.len() != Blockstamp::SIZE_IN_BYTES {
            Err(BlockstampFromBytesError::InvalidLen)
        } else {
            let mut id_bytes = [0u8; 4];
            id_bytes.copy_from_slice(&src[..4]);
            let mut hash_bytes = [0u8; 32];
            unsafe {
                std::ptr::copy_nonoverlapping(
                    src[4..].as_ptr(),
                    hash_bytes.as_mut_ptr(),
                    Hash::SIZE_IN_BYTES,
                );
            }
            Ok(Blockstamp {
                number: BlockNumber(u32::from_be_bytes(id_bytes)),
                hash: BlockHash(Hash(hash_bytes)),
            })
        }
    }
}

impl FromStr for Blockstamp {
    type Err = BlockstampParseError;

    fn from_str(src: &str) -> Result<Blockstamp, BlockstampParseError> {
        let mut split = src.split('-');

        match (split.next(), split.next(), split.next()) {
            (Some(id), Some(hash), None) => {
                let hash = Hash::from_hex(hash)?;

                if let Ok(id) = id.parse::<u32>() {
                    Ok(Blockstamp {
                        number: BlockNumber(id),
                        hash: BlockHash(hash),
                    })
                } else {
                    Err(BlockstampParseError::InvalidBlockNumber)
                }
            }
            _ => Err(BlockstampParseError::InvalidFormat),
        }
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn blockstamp_default() {
        assert_eq!(
            Blockstamp::default(),
            Blockstamp {
                number: BlockNumber(0),
                hash: BlockHash(Hash([0u8; 32])),
            }
        )
    }

    #[test]
    fn blockstamp_from_bytes() -> Result<(), BlockstampFromBytesError> {
        assert_eq!(
            Blockstamp::from_bytes(&[]),
            Err(BlockstampFromBytesError::InvalidLen)
        );

        assert_eq!(
            Blockstamp::default(),
            Blockstamp::from_bytes(&[
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0
            ])?
        );

        assert_eq!(
            Blockstamp {
                number: BlockNumber(3),
                hash: BlockHash(Hash([2u8; 32])),
            },
            Blockstamp::from_bytes(&[
                0, 0, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
                2, 2, 2, 2, 2, 2, 2, 2,
            ])?
        );

        Ok(())
    }

    #[test]
    fn blockstamp_into_bytes() {
        let bytes: [u8; Blockstamp::SIZE_IN_BYTES] = Blockstamp::default().into();
        assert_eq!(&bytes[..4], &[0, 0, 0, 0,]);
        assert_eq!(
            &bytes[4..],
            &[
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0,
            ]
        );

        let bytes: [u8; Blockstamp::SIZE_IN_BYTES] = Blockstamp {
            number: BlockNumber(3),
            hash: BlockHash(Hash([2u8; 32])),
        }
        .into();
        assert_eq!(&bytes[..4], &[0, 0, 0, 3,]);
        assert_eq!(
            &bytes[4..],
            &[
                2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
                2, 2, 2, 2,
            ]
        );
    }
}