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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
use crate::error::ModelsError;
use crate::prehash::PreHashed;
use crate::secure_share::Id;
use massa_hash::{Hash, HashDeserializer};
use massa_serialization::{
    DeserializeError, Deserializer, SerializeError, Serializer, U64VarIntDeserializer,
    U64VarIntSerializer,
};
use nom::{
    error::{context, ContextError, ErrorKind, ParseError},
    IResult,
};
use serde_with::{DeserializeFromStr, SerializeDisplay};
use std::collections::Bound::Included;
use std::str::FromStr;
use transition::Versioned;

/// block id
#[allow(missing_docs)]
#[transition::versioned(versions("0"))]
#[derive(
    Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, SerializeDisplay, DeserializeFromStr,
)]
pub struct BlockId(pub Hash);

impl PreHashed for BlockId {}

impl Id for BlockId {
    fn new(hash: Hash) -> Self {
        BlockId::BlockIdV0(BlockIdV0(hash))
    }

    fn get_hash(&self) -> &Hash {
        match self {
            BlockId::BlockIdV0(block_id) => block_id.get_hash(),
        }
    }
}

impl BlockId {
    /// first bit of the hashed block id
    pub fn get_first_bit(&self) -> bool {
        match self {
            BlockId::BlockIdV0(block_id) => block_id.get_first_bit(),
        }
    }

    /// version of the block id
    pub fn get_version(&self) -> u64 {
        match self {
            BlockId::BlockIdV0(block_id) => block_id.get_version(),
        }
    }

    /// Generate a version 0 block id from an hash used only for tests
    #[cfg(any(test, feature = "test-exports"))]
    pub fn generate_from_hash(hash: Hash) -> BlockId {
        BlockId::BlockIdV0(BlockIdV0(hash))
    }
}

#[transition::impl_version(versions("0"))]
impl BlockId {
    fn get_hash(&self) -> &Hash {
        &self.0
    }

    /// first bit of the hashed block id
    pub fn get_first_bit(&self) -> bool {
        self.0.to_bytes()[0] >> 7 == 1
    }

    /// version of the block id
    pub fn get_version(&self) -> u64 {
        Self::VERSION
    }
}

const BLOCKID_PREFIX: char = 'B';

impl std::fmt::Display for BlockId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BlockId::BlockIdV0(block_id) => write!(f, "{}", block_id),
        }
    }
}

#[transition::impl_version(versions("0"))]
impl std::fmt::Display for BlockId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let u64_serializer = U64VarIntSerializer::new();
        // might want to allocate the vector with capacity in order to avoid re-allocation
        let mut bytes: Vec<u8> = Vec::new();
        u64_serializer
            .serialize(&Self::VERSION, &mut bytes)
            .map_err(|_| std::fmt::Error)?;
        bytes.extend(self.0.to_bytes());
        write!(
            f,
            "{}{}",
            BLOCKID_PREFIX,
            bs58::encode(bytes).with_check().into_string()
        )
    }
}

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

impl FromStr for BlockId {
    type Err = ModelsError;
    /// ## Example
    /// ```rust
    /// # use massa_hash::Hash;
    /// # use std::str::FromStr;
    /// # use massa_models::block_id::BlockId;
    /// # use crate::massa_models::secure_share::Id;
    /// # let hash = Hash::compute_from(b"test");
    /// # let block_id = BlockId::new(hash);
    /// let ser = block_id.to_string();
    /// let res_block_id = BlockId::from_str(&ser).unwrap();
    /// assert_eq!(block_id, res_block_id);
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut chars = s.chars();
        match chars.next() {
            Some(prefix) if prefix == BLOCKID_PREFIX => {
                let data = chars.collect::<String>();
                let decoded_bs58_check = bs58::decode(data)
                    .with_check(None)
                    .into_vec()
                    .map_err(|_| ModelsError::BlockIdParseError)?;
                let block_id_deserializer = BlockIdDeserializer::new();
                let (rest, block_id) = block_id_deserializer
                    .deserialize::<DeserializeError>(&decoded_bs58_check[..])
                    .map_err(|_| ModelsError::OperationIdParseError)?;
                if rest.is_empty() {
                    Ok(block_id)
                } else {
                    Err(ModelsError::OperationIdParseError)
                }
            }
            _ => Err(ModelsError::BlockIdParseError),
        }
    }
}

#[transition::impl_version(versions("0"))]
impl FromStr for BlockId {
    type Err = ModelsError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut chars = s.chars();
        match chars.next() {
            Some(prefix) if prefix == BLOCKID_PREFIX => {
                let data = chars.collect::<String>();
                let decoded_bs58_check = bs58::decode(data)
                    .with_check(None)
                    .into_vec()
                    .map_err(|_| ModelsError::BlockIdParseError)?;
                let block_id_deserializer = BlockIdDeserializer::new();
                let (rest, block_id) = block_id_deserializer
                    .deserialize::<DeserializeError>(&decoded_bs58_check[..])
                    .map_err(|_| ModelsError::OperationIdParseError)?;
                if rest.is_empty() {
                    Ok(block_id)
                } else {
                    Err(ModelsError::OperationIdParseError)
                }
            }
            _ => Err(ModelsError::BlockIdParseError),
        }
    }
}

/// Serializer for `BlockId`
#[derive(Default, Clone)]
pub struct BlockIdSerializer {
    version_serializer: U64VarIntSerializer,
}

impl BlockIdSerializer {
    /// Creates a new serializer for `BlockId`
    pub fn new() -> Self {
        Self {
            version_serializer: U64VarIntSerializer::new(),
        }
    }
}

impl Serializer<BlockId> for BlockIdSerializer {
    fn serialize(&self, value: &BlockId, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        self.version_serializer
            .serialize(&value.get_version(), buffer)?;
        match value {
            BlockId::BlockIdV0(block_id) => self.serialize(block_id, buffer),
        }
    }
}

#[transition::impl_version(versions("0"), structures("BlockId"))]
impl Serializer<BlockId> for BlockIdSerializer {
    fn serialize(&self, value: &BlockId, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        buffer.extend(value.0.to_bytes());
        Ok(())
    }
}

/// Deserializer for `BlockId`
#[derive(Clone)]
pub struct BlockIdDeserializer {
    hash_deserializer: HashDeserializer,
    version_deserializer: U64VarIntDeserializer,
}

impl Default for BlockIdDeserializer {
    fn default() -> Self {
        Self::new()
    }
}

impl BlockIdDeserializer {
    /// Creates a new deserializer for `BlockId`
    pub fn new() -> Self {
        Self {
            hash_deserializer: HashDeserializer::new(),
            version_deserializer: U64VarIntDeserializer::new(Included(0), Included(u64::MAX)),
        }
    }
}

impl Deserializer<BlockId> for BlockIdDeserializer {
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], BlockId, E> {
        // Verify that we at least have a version and something else
        if buffer.len() < 2 {
            return Err(nom::Err::Error(E::from_error_kind(buffer, ErrorKind::Eof)));
        }
        let (rest, op_id_version) =
            self.version_deserializer
                .deserialize(buffer)
                .map_err(|_: nom::Err<E>| {
                    nom::Err::Error(E::from_error_kind(buffer, ErrorKind::Eof))
                })?;
        match op_id_version {
            <BlockId!["0"]>::VERSION => {
                let (rest, op_id) = self.deserialize(rest)?;
                Ok((rest, BlockIdVariant!["0"](op_id)))
            }
            _ => Err(nom::Err::Error(E::from_error_kind(buffer, ErrorKind::Eof))),
        }
    }
}

#[transition::impl_version(versions("0"), structures("BlockId"))]
impl Deserializer<BlockId> for BlockIdDeserializer {
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], BlockId, E> {
        context("Failed BlockId deserialization", |input| {
            let (rest, hash) = self.hash_deserializer.deserialize(input)?;
            Ok((rest, BlockId(hash)))
        })(buffer)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_block_id() {
        let expected_block_id =
            BlockId::from_str("B12iL52kye2CraMXdkdKDxjZJXF9it6E4hz8KEj656QnhvwocvBX").unwrap();
        let actual_block_id = BlockId::generate_from_hash(Hash::compute_from("blk".as_bytes()));

        assert_eq!(actual_block_id, expected_block_id);
    }

    #[test]
    fn test_block_id_errors() {
        let actual_error = BlockId::from_str("SomeInvalidBlockId")
            .unwrap_err()
            .to_string();
        let expected_error = "block id parsing error".to_string();

        assert_eq!(actual_error, expected_error);
    }

    #[test]
    fn test_block_id_serde() {
        let expected_block_id =
            BlockId::from_str("B12DvrcQkzF1Wi8BVoNfc4n93CD3E2qhCNe7nVhnEQGWHZ24fEmg").unwrap();

        let serialized = serde_json::to_string(&expected_block_id).unwrap();
        let actual_block_id: BlockId = serde_json::from_str(&serialized).unwrap();

        assert_eq!(actual_block_id, expected_block_id);
    }
}