1use alloc::borrow::ToOwned;
4use alloc::string::String;
5use alloc::vec::Vec;
6use core::fmt;
7
8use heika_core::address::Address;
9use sha3::{Digest, Sha3_256};
10
11use crate::bounded::BoundedVec;
12use crate::mosaic::MosaicId;
13use crate::{DecodeError, Reader};
14
15#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
17pub struct NamespaceId(pub u64);
18
19impl NamespaceId {
20 pub fn generate(parent_id: Option<NamespaceId>, name: &[u8]) -> Self {
23 let parent_id = parent_id.map_or(0, |parent_id| parent_id.0);
24 let hash = Sha3_256::new()
25 .chain_update(parent_id.to_le_bytes())
26 .chain_update(name)
27 .finalize();
28 let id = u64::from_le_bytes(hash[..8].try_into().expect("8 bytes"));
29 Self(id | 1 << 63)
30 }
31
32 pub fn from_full_name(full_name: &str) -> Result<Self, InvalidNamespaceName> {
35 Ok(*Self::path(full_name)?
36 .last()
37 .expect("split yields at least one part"))
38 }
39
40 pub fn path(full_name: &str) -> Result<Vec<Self>, InvalidNamespaceName> {
45 let mut parent = None;
46 full_name
47 .split('.')
48 .map(|name| {
49 if !is_valid_namespace_name(name.as_bytes()) {
50 return Err(InvalidNamespaceName(name.to_owned()));
51 }
52 let id = Self::generate(parent, name.as_bytes());
53 parent = Some(id);
54 Ok(id)
55 })
56 .collect()
57 }
58}
59
60pub fn is_valid_namespace_name(name: &[u8]) -> bool {
63 let is_alphanumeric = |byte: &u8| byte.is_ascii_lowercase() || byte.is_ascii_digit();
64 match name.split_first() {
65 Some((first, rest)) => {
66 is_alphanumeric(first)
67 && rest
68 .iter()
69 .all(|byte| is_alphanumeric(byte) || *byte == b'-' || *byte == b'_')
70 }
71 None => false,
72 }
73}
74
75#[derive(Clone, PartialEq, Eq, Debug)]
77pub struct InvalidNamespaceName(pub String);
78
79impl fmt::Display for InvalidNamespaceName {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 write!(
82 f,
83 "ネームスペースの名前として使えない部分があります: {:?}(英小文字、数字、- と _ だけで、英小文字か数字で始めます)",
84 self.0
85 )
86 }
87}
88
89impl core::error::Error for InvalidNamespaceName {}
90
91#[derive(Clone, Copy, PartialEq, Eq, Debug)]
93pub enum NamespaceRegistrationType {
94 Root { duration: u64 },
96 Child { parent_id: NamespaceId },
98}
99
100#[derive(Clone, PartialEq, Eq, Debug)]
102pub struct NamespaceRegistration {
103 pub registration_type: NamespaceRegistrationType,
104 pub id: NamespaceId,
105 pub name: BoundedVec<u8, { u8::MAX as usize }>,
107}
108
109impl NamespaceRegistration {
110 const FIXED_SIZE: usize = 8 + 8 + 1 + 1;
112
113 pub(crate) fn encode(&self, out: &mut Vec<u8>) {
114 let (duration_or_parent, registration_type) = match self.registration_type {
115 NamespaceRegistrationType::Root { duration } => (duration, 0),
116 NamespaceRegistrationType::Child { parent_id } => (parent_id.0, 1),
117 };
118 out.extend_from_slice(&duration_or_parent.to_le_bytes());
119 out.extend_from_slice(&self.id.0.to_le_bytes());
120 out.push(registration_type);
121 out.push(self.name.len() as u8);
122 out.extend_from_slice(&self.name);
123 }
124
125 pub(crate) fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
126 let mut reader = Reader::at_least(bytes, Self::FIXED_SIZE)?;
127 let duration_or_parent = reader.u64();
129 let id = NamespaceId(reader.u64());
130 let registration_type = match reader.u8() {
131 0 => NamespaceRegistrationType::Root {
132 duration: duration_or_parent,
133 },
134 1 => NamespaceRegistrationType::Child {
135 parent_id: NamespaceId(duration_or_parent),
136 },
137 registration_type => {
138 return Err(DecodeError::InvalidValue {
139 field: "ネームスペースのルートかサブか",
140 value: registration_type.into(),
141 });
142 }
143 };
144 let name_size = reader.u8() as usize;
145 Ok(Self {
146 registration_type,
147 id,
148 name: reader
149 .rest(name_size)?
150 .to_vec()
151 .try_into()
152 .expect("u8 length"),
153 })
154 }
155}
156
157#[derive(Clone, Copy, PartialEq, Eq, Debug)]
158pub enum AliasAction {
159 Unlink,
160 Link,
161}
162
163impl AliasAction {
164 fn to_byte(self) -> u8 {
165 match self {
166 Self::Unlink => 0,
167 Self::Link => 1,
168 }
169 }
170
171 fn from_byte(byte: u8) -> Result<Self, DecodeError> {
172 match byte {
173 0 => Ok(Self::Unlink),
174 1 => Ok(Self::Link),
175 _ => Err(DecodeError::InvalidValue {
176 field: "エイリアスの操作",
177 value: byte.into(),
178 }),
179 }
180 }
181}
182
183#[derive(Clone, Copy, PartialEq, Eq, Debug)]
185pub struct AddressAlias {
186 pub namespace_id: NamespaceId,
187 pub address: Address,
188 pub alias_action: AliasAction,
189}
190
191impl AddressAlias {
192 const SIZE: usize = 8 + 24 + 1;
193
194 pub(crate) fn encode(&self, out: &mut Vec<u8>) {
195 out.extend_from_slice(&self.namespace_id.0.to_le_bytes());
196 out.extend_from_slice(&self.address.0);
197 out.push(self.alias_action.to_byte());
198 }
199
200 pub(crate) fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
201 let mut reader = Reader::exact(bytes, Self::SIZE)?;
202 Ok(Self {
203 namespace_id: NamespaceId(reader.u64()),
204 address: Address(reader.array()),
205 alias_action: AliasAction::from_byte(reader.u8())?,
206 })
207 }
208}
209
210#[derive(Clone, Copy, PartialEq, Eq, Debug)]
212pub struct MosaicAlias {
213 pub namespace_id: NamespaceId,
214 pub mosaic_id: MosaicId,
215 pub alias_action: AliasAction,
216}
217
218impl MosaicAlias {
219 const SIZE: usize = 8 + 8 + 1;
220
221 pub(crate) fn encode(&self, out: &mut Vec<u8>) {
222 out.extend_from_slice(&self.namespace_id.0.to_le_bytes());
223 out.extend_from_slice(&self.mosaic_id.0.to_le_bytes());
224 out.push(self.alias_action.to_byte());
225 }
226
227 pub(crate) fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
228 let mut reader = Reader::exact(bytes, Self::SIZE)?;
229 Ok(Self {
230 namespace_id: NamespaceId(reader.u64()),
231 mosaic_id: MosaicId(reader.u64()),
232 alias_action: AliasAction::from_byte(reader.u8())?,
233 })
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240 use crate::Body;
241 use crate::testing::{decode, round_trip};
242
243 #[test]
244 fn finds_the_currency_namespace_from_its_full_name() {
245 let symbol = NamespaceId::generate(None, b"symbol");
246 let xym = NamespaceId::generate(Some(symbol), b"xym");
247 assert_eq!(xym, NamespaceId(0xE74B_99BA_41F4_AFEE));
249 assert_eq!(NamespaceId::path("symbol.xym"), Ok(vec![symbol, xym]));
250 assert_eq!(NamespaceId::from_full_name("symbol.xym"), Ok(xym));
251 assert_eq!(NamespaceId::from_full_name("symbol"), Ok(symbol));
252 }
253
254 #[test]
255 fn refuses_full_names_with_invalid_parts() {
256 for (full_name, part) in [
257 ("", ""),
258 ("symbol.", ""),
259 (".xym", ""),
260 ("Symbol.xym", "Symbol"),
261 ("symbol._xym", "_xym"),
262 ("symbol.x ym", "x ym"),
263 ] {
264 assert_eq!(
265 NamespaceId::path(full_name),
266 Err(InvalidNamespaceName(part.to_owned())),
267 "{full_name:?}"
268 );
269 }
270 }
271
272 #[test]
273 fn checks_names_like_catapult() {
274 for name in ["a", "0", "a-b_c", "9-", "heika_2026"] {
275 assert!(is_valid_namespace_name(name.as_bytes()), "{name}");
276 }
277 for name in ["", "-a", "_a", "A", "a.b", "a b", "あ"] {
278 assert!(!is_valid_namespace_name(name.as_bytes()), "{name}");
279 }
280 }
281
282 fn registration(registration_type: NamespaceRegistrationType) -> NamespaceRegistration {
283 NamespaceRegistration {
284 registration_type,
285 id: NamespaceId(0x8000_0000_0000_0002),
286 name: b"heika".to_vec().try_into().unwrap(),
287 }
288 }
289
290 #[test]
291 fn generates_the_id_of_symbol_xym() {
292 let symbol = NamespaceId::generate(None, b"symbol");
294 assert_eq!(
295 NamespaceId::generate(Some(symbol), b"xym"),
296 NamespaceId(0xE74B_99BA_41F4_AFEE)
297 );
298 }
299
300 #[test]
301 fn writes_the_duration_or_the_parent_in_the_same_place() {
302 let root = round_trip(Body::NamespaceRegistration(registration(
303 NamespaceRegistrationType::Root { duration: 365 },
304 )));
305 assert_eq!(root[..8], 365_u64.to_le_bytes());
306 assert_eq!(root[16..18], [0, 5]);
307 assert_eq!(root[18..], *b"heika");
308
309 let child = round_trip(Body::NamespaceRegistration(registration(
310 NamespaceRegistrationType::Child {
311 parent_id: NamespaceId(0x8000_0000_0000_0001),
312 },
313 )));
314 assert_eq!(child[..8], 0x8000_0000_0000_0001_u64.to_le_bytes());
315 assert_eq!(child[16], 1);
316 }
317
318 #[test]
319 fn rejects_an_undefined_registration_type() {
320 let mut body = round_trip(Body::NamespaceRegistration(registration(
321 NamespaceRegistrationType::Root { duration: 1 },
322 )));
323 body[16] = 2;
324 assert_eq!(
325 decode(0x414E, &body),
326 Err(DecodeError::InvalidValue {
327 field: "ネームスペースのルートかサブか",
328 value: 2
329 })
330 );
331 }
332
333 #[test]
334 fn round_trips_aliases() {
335 let address = round_trip(Body::AddressAlias(AddressAlias {
336 namespace_id: NamespaceId(0x8000_0000_0000_0001),
337 address: Address([0x98; 24]),
338 alias_action: AliasAction::Link,
339 }));
340 assert_eq!(address[8..32], [0x98; 24]);
341 assert_eq!(address[32], 1);
342
343 let mut mosaic = round_trip(Body::MosaicAlias(MosaicAlias {
344 namespace_id: NamespaceId(0x8000_0000_0000_0001),
345 mosaic_id: MosaicId(7),
346 alias_action: AliasAction::Unlink,
347 }));
348 assert_eq!(mosaic[16], 0);
349 mosaic[16] = 2;
350 assert_eq!(
351 decode(0x434E, &mosaic),
352 Err(DecodeError::InvalidValue {
353 field: "エイリアスの操作",
354 value: 2
355 })
356 );
357 }
358}