multiversx_sdk/crypto/
public_key.rs1use std::fmt::Display;
2
3use super::private_key::PrivateKey;
4use anyhow::Result;
5use multiversx_chain_core::types::Address;
6use serde::{
7 de::{Deserialize, Deserializer},
8 ser::{Serialize, Serializer},
9};
10
11pub const PUBLIC_KEY_LENGTH: usize = 32;
12
13#[derive(Copy, Clone, Debug)]
14pub struct PublicKey([u8; PUBLIC_KEY_LENGTH]);
15
16impl PublicKey {
17 pub fn to_bytes(&self) -> [u8; PUBLIC_KEY_LENGTH] {
18 self.0
19 }
20
21 pub fn as_bytes(&self) -> &[u8; PUBLIC_KEY_LENGTH] {
22 &self.0
23 }
24
25 pub fn to_address(&self) -> Address {
26 self.0.into()
27 }
28
29 pub fn from_hex_str(pk: &str) -> Result<Self> {
30 let bytes = hex::decode(pk)?;
31 let mut bits: [u8; 32] = [0u8; 32];
32 bits.copy_from_slice(&bytes[32..]);
33 Ok(Self(bits))
34 }
35}
36
37impl From<&PrivateKey> for PublicKey {
38 fn from(private_key: &PrivateKey) -> PublicKey {
39 let bytes = private_key.to_bytes();
40
41 let mut bits: [u8; 32] = [0u8; 32];
42 bits.copy_from_slice(&bytes[32..]);
43
44 PublicKey(bits)
45 }
46}
47
48impl Display for PublicKey {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 hex::encode(self.0).fmt(f)
51 }
52}
53
54impl Serialize for PublicKey {
55 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
56 where
57 S: Serializer,
58 {
59 serializer.serialize_str(self.to_string().as_str())
60 }
61}
62
63impl<'de> Deserialize<'de> for PublicKey {
64 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
65 where
66 D: Deserializer<'de>,
67 {
68 let s = String::deserialize(deserializer)?;
69 Ok(Self::from_hex_str(s.as_str()).unwrap())
70 }
71}