multiversx_chain_core/types/
bls_key.rs

1// BLS keys have 96 bytes
2const BLS_KEY_BYTE_LENGTH: usize = 96;
3
4#[derive(Debug, PartialEq, Clone, Copy)]
5pub struct BLSKey([u8; BLS_KEY_BYTE_LENGTH]);
6
7impl From<[u8; BLS_KEY_BYTE_LENGTH]> for BLSKey {
8    #[inline]
9    fn from(value: [u8; BLS_KEY_BYTE_LENGTH]) -> Self {
10        Self(value)
11    }
12}
13
14impl BLSKey {
15    pub const fn len() -> usize {
16        BLS_KEY_BYTE_LENGTH
17    }
18
19    #[inline]
20    pub fn as_bytes(self) -> [u8; BLS_KEY_BYTE_LENGTH] {
21        self.0
22    }
23
24    pub fn to_vec(self) -> Vec<u8> {
25        self.0.to_vec()
26    }
27
28    pub fn from_vec(v: Vec<u8>) -> Option<Self> {
29        match v.try_into() {
30            Ok(arr) => Some(Self(arr)),
31            Err(_) => None,
32        }
33    }
34
35    #[cfg(feature = "std")]
36    pub fn parse_hex(hex_key: &str) -> Option<Self> {
37        let Ok(v) = hex::decode(hex_key) else {
38            return None;
39        };
40        Self::from_vec(v)
41    }
42}
43
44use crate::codec::*;
45
46impl NestedEncode for BLSKey {
47    fn dep_encode_or_handle_err<O, H>(&self, dest: &mut O, h: H) -> Result<(), H::HandledErr>
48    where
49        O: NestedEncodeOutput,
50        H: EncodeErrorHandler,
51    {
52        self.0.dep_encode_or_handle_err(dest, h)
53    }
54}
55
56impl TopEncode for BLSKey {
57    fn top_encode_or_handle_err<O, H>(&self, output: O, h: H) -> Result<(), H::HandledErr>
58    where
59        O: TopEncodeOutput,
60        H: EncodeErrorHandler,
61    {
62        self.0.top_encode_or_handle_err(output, h)
63    }
64}
65
66impl NestedDecode for BLSKey {
67    fn dep_decode_or_handle_err<I, H>(input: &mut I, h: H) -> Result<Self, H::HandledErr>
68    where
69        I: NestedDecodeInput,
70        H: DecodeErrorHandler,
71    {
72        Ok(BLSKey(
73            <[u8; BLS_KEY_BYTE_LENGTH]>::dep_decode_or_handle_err(input, h)?,
74        ))
75    }
76}
77
78impl TopDecode for BLSKey {
79    fn top_decode_or_handle_err<I, H>(input: I, h: H) -> Result<Self, H::HandledErr>
80    where
81        I: TopDecodeInput,
82        H: DecodeErrorHandler,
83    {
84        Ok(BLSKey(
85            <[u8; BLS_KEY_BYTE_LENGTH]>::top_decode_or_handle_err(input, h)?,
86        ))
87    }
88}