Skip to main content

heika_transaction/
namespace.rs

1//! ネームスペース。catbuffer の `namespace/`。
2
3use 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/// ネームスペースの ID。名前と親の ID から決まる。最上位ビットは1。
16#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
17pub struct NamespaceId(pub u64);
18
19impl NamespaceId {
20    /// 名前と親の ID から ID を求める。catapult の `GenerateNamespaceId` と同じく、
21    /// 親の ID(ルートなら0)と名前を続けた SHA3-256 の先頭8バイトに、モザイクと見分ける最上位ビットを立てて使う。
22    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    /// ドットで区切ったフルネームから ID を求める。公式の SDK の `generate_mosaic_alias_id` と同じく、
33    /// [`NamespaceId::path`] の最後の ID。`symbol.xym` なら、通貨のモザイクに付いているネームスペースになる。
34    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    /// ドットで区切ったフルネームを、ルートから順の ID の並びにする。公式の SDK の `generate_namespace_path`。
41    /// どの部分も [`is_valid_namespace_name`] を満たさなければならない。
42    ///
43    /// 名前の長さと深さの上限はネットワークの設定(`maxNameSize` と `maxNamespaceDepth`)で決まるので、ここでは確かめない。
44    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
60/// ネームスペースの名前として使えるか。catapult の `IsValidName` と同じく、空でなく、
61/// 英小文字と数字と `-` と `_` だけで、最初は英小文字か数字でなければならない。
62pub 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/// フルネームに、ネームスペースの名前として使えない部分がある。
76#[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/// ルートか、どの親の下のサブネームスペースか。
92#[derive(Clone, Copy, PartialEq, Eq, Debug)]
93pub enum NamespaceRegistrationType {
94    /// ルートのネームスペース。持っておく期間(ブロック)を決める
95    Root { duration: u64 },
96    /// サブネームスペース。期間は親と同じ
97    Child { parent_id: NamespaceId },
98}
99
100/// ネームスペースを取る、またはルートのネームスペースを延長する。
101#[derive(Clone, PartialEq, Eq, Debug)]
102pub struct NamespaceRegistration {
103    pub registration_type: NamespaceRegistrationType,
104    pub id: NamespaceId,
105    /// 名前。使える文字はネットワークが確かめる
106    pub name: BoundedVec<u8, { u8::MAX as usize }>,
107}
108
109impl NamespaceRegistration {
110    /// 名前より前の部分。期間か親の ID、ID、ルートかサブか、名前の長さ。
111    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        // 先頭の8バイトが期間か親の ID かは、後ろのルートかサブかで決まる
128        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/// ネームスペースをアドレスの別名にする、または外す。
184#[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/// ネームスペースをモザイクの別名にする、または外す。
211#[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        // 通貨のモザイクに付いているネームスペースの ID は、チェーンに記録されているもの
248        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        // ネットワークの通貨のモザイクに付いている、よく知られたネームスペース
293        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}