1#![forbid(unsafe_code)]
8
9use alloc::{format, string::String, vec::Vec};
10use core::{fmt, str::FromStr};
11
12pub const MAX_TEXT_BYTES: usize = 256;
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub enum PublicKeyCodec {
20 Ed25519,
21 X25519,
22 P256,
23 P384,
24}
25
26impl PublicKeyCodec {
27 pub fn code(self) -> u64 {
28 match self {
29 Self::Ed25519 => 0xed,
30 Self::X25519 => 0xec,
31 Self::P256 => 0x1200,
32 Self::P384 => 0x1201,
33 }
34 }
35
36 pub fn from_code(code: u64) -> Result<Self, MultikeyError> {
37 match code {
38 0xed => Ok(Self::Ed25519),
39 0xec => Ok(Self::X25519),
40 0x1200 => Ok(Self::P256),
41 0x1201 => Ok(Self::P384),
42 _ => Err(MultikeyError::UnsupportedCodec(code)),
43 }
44 }
45
46 fn public_key_size(self) -> usize {
47 match self {
48 Self::Ed25519 | Self::X25519 => 32,
49 Self::P256 => 33,
50 Self::P384 => 49,
51 }
52 }
53}
54
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub enum MultikeyError {
57 InvalidEncoding,
58 InvalidPublicKey,
59 UnsupportedCodec(u64),
60 UnsupportedSigningCodec(u64),
61}
62
63impl fmt::Display for MultikeyError {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 match self {
66 Self::InvalidEncoding => f.write_str("invalid or oversized public Multikey encoding"),
67 Self::InvalidPublicKey => {
68 f.write_str("invalid public Multikey length or compressed prefix")
69 }
70 Self::UnsupportedCodec(code) => {
71 write!(f, "unsupported public Multikey codec: {code:#x}")
72 }
73 Self::UnsupportedSigningCodec(code) => {
74 write!(f, "unsupported signing Multikey codec: {code:#x}")
75 }
76 }
77 }
78}
79
80#[cfg(feature = "std")]
81impl std::error::Error for MultikeyError {}
82
83#[derive(Clone, Debug, PartialEq, Eq)]
86pub struct Multikey {
87 codec: PublicKeyCodec,
88 bytes: Vec<u8>,
89}
90
91impl Multikey {
92 pub fn new(codec: PublicKeyCodec, bytes: &[u8]) -> Result<Self, MultikeyError> {
93 if bytes.len() != codec.public_key_size()
94 || (matches!(codec, PublicKeyCodec::P256 | PublicKeyCodec::P384)
95 && !matches!(bytes.first(), Some(2 | 3)))
96 {
97 return Err(MultikeyError::InvalidPublicKey);
98 }
99 Ok(Self {
100 codec,
101 bytes: bytes.into(),
102 })
103 }
104
105 pub fn parse(text: &str) -> Result<Self, MultikeyError> {
107 if text.len() > MAX_TEXT_BYTES {
108 return Err(MultikeyError::InvalidEncoding);
109 }
110 let encoded = text
111 .strip_prefix('z')
112 .filter(|s| !s.is_empty())
113 .ok_or(MultikeyError::InvalidEncoding)?;
114 let payload = bs58::decode(encoded)
115 .into_vec()
116 .map_err(|_| MultikeyError::InvalidEncoding)?;
117 let (code, bytes) =
118 unsigned_varint::decode::u64(&payload).map_err(|_| MultikeyError::InvalidEncoding)?;
119 let mut buffer = unsigned_varint::encode::u64_buffer();
120 let prefix = unsigned_varint::encode::u64(code, &mut buffer);
121 if payload.len() - bytes.len() != prefix.len() || !payload.starts_with(prefix) {
122 return Err(MultikeyError::InvalidEncoding);
123 }
124 let key = Self::new(PublicKeyCodec::from_code(code)?, bytes)?;
125 if key.to_multibase() != text {
127 return Err(MultikeyError::InvalidEncoding);
128 }
129 Ok(key)
130 }
131
132 pub fn codec(&self) -> PublicKeyCodec {
133 self.codec
134 }
135 pub fn public_key_bytes(&self) -> &[u8] {
136 &self.bytes
137 }
138
139 pub fn to_multibase(&self) -> String {
140 let mut buffer = unsigned_varint::encode::u64_buffer();
141 let prefix = unsigned_varint::encode::u64(self.codec.code(), &mut buffer);
142 let mut payload = Vec::with_capacity(prefix.len() + self.bytes.len());
143 payload.extend_from_slice(prefix);
144 payload.extend_from_slice(&self.bytes);
145 format!("z{}", bs58::encode(payload).into_string())
146 }
147}
148
149impl FromStr for Multikey {
150 type Err = MultikeyError;
151 fn from_str(text: &str) -> Result<Self, Self::Err> {
152 Self::parse(text)
153 }
154}
155
156impl fmt::Display for Multikey {
157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158 f.write_str(&self.to_multibase())
159 }
160}