Skip to main content

heika_rest/
state.rs

1//! 状態。`/accounts/{id}`、`/mosaics/{id}`、`/namespaces`、`/metadata` が返す JSON から、
2//! catapult が状態の木の葉にする状態のバイト列を組み直す。ノードが REST の口で返すために、
3//! 状態のバイト列から JSON にする逆向きもある。
4//!
5//! 葉の値は、状態のバージョン(u16)に続けて、履歴を除いた状態を書いたものの SHA3-256
6//! (catapult の `CacheSerializerAdapter` と、それぞれの `*NonHistoricalSerializer` や `*Serializer`)。
7//! `/accounts/{id}/merkle` などが返す経路の葉と比べれば、REST の状態の JSON が木にあるものと同じだと確かめられる。
8//!
9//! 状態は最新のものしか取れないので、経路の根と比べる9本の根も、同じ時点のブロックのものを使う。
10
11use heika_core::address::Address;
12use heika_core::hash::Hash256;
13use heika_core::patricia;
14use heika_transaction::{MetadataKey, MetadataType};
15use serde::{Deserialize, Serialize};
16use sha3::{Digest, Sha3_256};
17
18use crate::{RestError, hex, hex_array, hex_vec, number};
19
20/// どの状態も、バージョンは 1
21const STATE_VERSION: u16 = 1;
22
23/// 大口のアカウントが持つ、活動の記録の数。catapult の `Activity_Bucket_History_Size - Rollback_Buffer_Size`
24const ACTIVITY_BUCKETS: usize = 5;
25
26/// `AccountInfoDTO`。
27#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
28pub struct AccountInfo {
29    pub account: AccountJson,
30}
31
32/// `AccountDTO`。
33#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
34#[serde(rename_all = "camelCase")]
35pub struct AccountJson {
36    pub version: u16,
37    pub address: String,
38    pub address_height: String,
39    pub public_key: String,
40    pub public_key_height: String,
41    pub account_type: u8,
42    pub supplemental_public_keys: SupplementalPublicKeysJson,
43    /// importance の履歴の先頭。大口のアカウントでなければ "0"
44    pub importance: String,
45    pub importance_height: String,
46    /// 大口のアカウントだけが持つ、活動の記録
47    pub activity_buckets: Vec<ActivityBucketJson>,
48    pub mosaics: Vec<BalanceJson>,
49}
50
51/// `SupplementalPublicKeysDTO`。
52#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
53pub struct SupplementalPublicKeysJson {
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub linked: Option<PublicKeyJson>,
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub node: Option<PublicKeyJson>,
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub vrf: Option<PublicKeyJson>,
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub voting: Option<VotingPublicKeysJson>,
62}
63
64#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
65#[serde(rename_all = "camelCase")]
66pub struct PublicKeyJson {
67    pub public_key: String,
68}
69
70#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
71#[serde(rename_all = "camelCase")]
72pub struct VotingPublicKeysJson {
73    pub public_keys: Vec<VotingPublicKeyJson>,
74}
75
76#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
77#[serde(rename_all = "camelCase")]
78pub struct VotingPublicKeyJson {
79    pub public_key: String,
80    pub start_epoch: u32,
81    pub end_epoch: u32,
82}
83
84/// `ActivityBucketDTO`。
85#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
86#[serde(rename_all = "camelCase")]
87pub struct ActivityBucketJson {
88    pub start_height: String,
89    pub total_fees_paid: String,
90    pub beneficiary_count: u32,
91    pub raw_score: String,
92}
93
94/// 残高。`Mosaic`。
95#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
96pub struct BalanceJson {
97    pub id: String,
98    pub amount: String,
99}
100
101impl AccountJson {
102    /// 状態のバイト列。catapult の `AccountStateNonHistoricalSerializer`。
103    pub fn to_state_bytes(&self) -> Result<Vec<u8>, RestError> {
104        let mut out = header(self.version)?;
105        out.extend_from_slice(&hex_array::<24>(&self.address, "address")?);
106        out.extend_from_slice(&number(&self.address_height, "addressHeight")?.to_le_bytes());
107        out.extend_from_slice(&hex_array::<32>(&self.public_key, "publicKey")?);
108        out.extend_from_slice(&number(&self.public_key_height, "publicKeyHeight")?.to_le_bytes());
109        out.push(self.account_type);
110        // 大口のアカウント(High_Value)だけが、importance と活動の記録を持つ
111        let high_value = !self.activity_buckets.is_empty();
112        out.push(u8::from(high_value));
113
114        let keys = &self.supplemental_public_keys;
115        let voting = keys
116            .voting
117            .as_ref()
118            .map_or(&[][..], |voting| &voting.public_keys[..]);
119        let mut mask = 0;
120        for (key, bit) in [(&keys.linked, 0x01), (&keys.node, 0x02), (&keys.vrf, 0x04)] {
121            if key.is_some() {
122                mask |= bit;
123            }
124        }
125        out.push(mask);
126        out.push(
127            u8::try_from(voting.len()).map_err(|_| RestError::InvalidValue {
128                field: "supplementalPublicKeys.voting",
129            })?,
130        );
131        for (key, field) in [
132            (&keys.linked, "supplementalPublicKeys.linked"),
133            (&keys.node, "supplementalPublicKeys.node"),
134            (&keys.vrf, "supplementalPublicKeys.vrf"),
135        ] {
136            if let Some(key) = key {
137                out.extend_from_slice(&hex_array::<32>(&key.public_key, field)?);
138            }
139        }
140        for key in voting {
141            out.extend_from_slice(&hex_array::<32>(
142                &key.public_key,
143                "supplementalPublicKeys.voting",
144            )?);
145            out.extend_from_slice(&key.start_epoch.to_le_bytes());
146            out.extend_from_slice(&key.end_epoch.to_le_bytes());
147        }
148
149        if high_value {
150            if self.activity_buckets.len() != ACTIVITY_BUCKETS {
151                return Err(RestError::InvalidValue {
152                    field: "activityBuckets",
153                });
154            }
155            out.extend_from_slice(&number(&self.importance, "importance")?.to_le_bytes());
156            out.extend_from_slice(
157                &number(&self.importance_height, "importanceHeight")?.to_le_bytes(),
158            );
159            for bucket in &self.activity_buckets {
160                out.extend_from_slice(
161                    &number(&bucket.start_height, "activityBuckets.startHeight")?.to_le_bytes(),
162                );
163                out.extend_from_slice(
164                    &number(&bucket.total_fees_paid, "activityBuckets.totalFeesPaid")?
165                        .to_le_bytes(),
166                );
167                out.extend_from_slice(&bucket.beneficiary_count.to_le_bytes());
168                out.extend_from_slice(
169                    &number(&bucket.raw_score, "activityBuckets.rawScore")?.to_le_bytes(),
170                );
171            }
172        }
173
174        out.extend_from_slice(
175            &u16::try_from(self.mosaics.len())
176                .map_err(|_| RestError::InvalidValue { field: "mosaics" })?
177                .to_le_bytes(),
178        );
179        for mosaic in &self.mosaics {
180            out.extend_from_slice(&id(&mosaic.id, "mosaics.id")?.to_le_bytes());
181            out.extend_from_slice(&number(&mosaic.amount, "mosaics.amount")?.to_le_bytes());
182        }
183        Ok(out)
184    }
185
186    /// 状態のバイト列から、REST が返す形にする。[`AccountJson::to_state_bytes`] の逆。ノードが REST の口で返すときに使う
187    pub fn from_state_bytes(bytes: &[u8]) -> Result<Self, RestError> {
188        let mut reader = StateReader::new(bytes)?;
189        let address = hex(reader.take(24)?);
190        let address_height = reader.u64()?.to_string();
191        let public_key = hex(reader.take(32)?);
192        let public_key_height = reader.u64()?.to_string();
193        let account_type = reader.u8()?;
194        let high_value = reader.u8()? != 0;
195        let mask = reader.u8()?;
196        let voting_count = reader.u8()?;
197        // linked、node、vrf の順に、ビットが立っているものだけが並ぶ
198        let key = |bit: u8, reader: &mut StateReader| -> Result<Option<PublicKeyJson>, RestError> {
199            if mask & bit == 0 {
200                return Ok(None);
201            }
202            Ok(Some(PublicKeyJson {
203                public_key: hex(reader.take(32)?),
204            }))
205        };
206        let linked = key(0x01, &mut reader)?;
207        let node = key(0x02, &mut reader)?;
208        let vrf = key(0x04, &mut reader)?;
209        let voting: Vec<VotingPublicKeyJson> = (0..voting_count)
210            .map(|_| {
211                Ok(VotingPublicKeyJson {
212                    public_key: hex(reader.take(32)?),
213                    start_epoch: reader.u32()?,
214                    end_epoch: reader.u32()?,
215                })
216            })
217            .collect::<Result<_, RestError>>()?;
218        let (importance, importance_height, activity_buckets) = if high_value {
219            let importance = reader.u64()?.to_string();
220            let importance_height = reader.u64()?.to_string();
221            let buckets = (0..ACTIVITY_BUCKETS)
222                .map(|_| {
223                    Ok(ActivityBucketJson {
224                        start_height: reader.u64()?.to_string(),
225                        total_fees_paid: reader.u64()?.to_string(),
226                        beneficiary_count: reader.u32()?,
227                        raw_score: reader.u64()?.to_string(),
228                    })
229                })
230                .collect::<Result<_, RestError>>()?;
231            (importance, importance_height, buckets)
232        } else {
233            ("0".to_owned(), "0".to_owned(), Vec::new())
234        };
235        let mosaics = (0..reader.u16()?)
236            .map(|_| {
237                Ok(BalanceJson {
238                    id: format!("{:016X}", reader.u64()?),
239                    amount: reader.u64()?.to_string(),
240                })
241            })
242            .collect::<Result<_, RestError>>()?;
243        reader.finish()?;
244        Ok(Self {
245            version: STATE_VERSION,
246            address,
247            address_height,
248            public_key,
249            public_key_height,
250            account_type,
251            supplemental_public_keys: SupplementalPublicKeysJson {
252                linked,
253                node,
254                vrf,
255                voting: (!voting.is_empty()).then_some(VotingPublicKeysJson {
256                    public_keys: voting,
257                }),
258            },
259            importance,
260            importance_height,
261            activity_buckets,
262            mosaics,
263        })
264    }
265
266    /// 状態の木の葉の値。
267    pub fn state_hash(&self) -> Result<Hash256, RestError> {
268        Ok(sha3(&self.to_state_bytes()?))
269    }
270
271    /// 状態の木のキー。アドレスの SHA3-256。
272    pub fn tree_key(&self) -> Result<Hash256, RestError> {
273        Ok(patricia::address_key(&Address(hex_array(
274            &self.address,
275            "address",
276        )?)))
277    }
278}
279
280/// `MosaicInfoDTO`。
281#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
282pub struct MosaicInfo {
283    pub mosaic: MosaicStateJson,
284}
285
286/// `MosaicDTO`。
287#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
288#[serde(rename_all = "camelCase")]
289pub struct MosaicStateJson {
290    pub version: u16,
291    pub id: String,
292    pub supply: String,
293    pub start_height: String,
294    pub owner_address: String,
295    pub revision: u32,
296    pub flags: u8,
297    pub divisibility: u8,
298    pub duration: String,
299}
300
301impl MosaicStateJson {
302    /// 状態のバイト列。catapult の `MosaicEntrySerializer`。
303    pub fn to_state_bytes(&self) -> Result<Vec<u8>, RestError> {
304        let mut out = header(self.version)?;
305        out.extend_from_slice(&id(&self.id, "id")?.to_le_bytes());
306        out.extend_from_slice(&number(&self.supply, "supply")?.to_le_bytes());
307        out.extend_from_slice(&number(&self.start_height, "startHeight")?.to_le_bytes());
308        out.extend_from_slice(&hex_array::<24>(&self.owner_address, "ownerAddress")?);
309        out.extend_from_slice(&self.revision.to_le_bytes());
310        out.push(self.flags);
311        out.push(self.divisibility);
312        out.extend_from_slice(&number(&self.duration, "duration")?.to_le_bytes());
313        Ok(out)
314    }
315
316    /// 状態のバイト列から、REST が返す形にする。[`MosaicStateJson::to_state_bytes`] の逆
317    pub fn from_state_bytes(bytes: &[u8]) -> Result<Self, RestError> {
318        let mut reader = StateReader::new(bytes)?;
319        let mosaic = Self {
320            version: STATE_VERSION,
321            id: format!("{:016X}", reader.u64()?),
322            supply: reader.u64()?.to_string(),
323            start_height: reader.u64()?.to_string(),
324            owner_address: hex(reader.take(24)?),
325            revision: reader.u32()?,
326            flags: reader.u8()?,
327            divisibility: reader.u8()?,
328            duration: reader.u64()?.to_string(),
329        };
330        reader.finish()?;
331        Ok(mosaic)
332    }
333
334    pub fn state_hash(&self) -> Result<Hash256, RestError> {
335        Ok(sha3(&self.to_state_bytes()?))
336    }
337
338    /// 状態の木のキー。モザイクの ID の SHA3-256。
339    pub fn tree_key(&self) -> Result<Hash256, RestError> {
340        Ok(patricia::id_key(id(&self.id, "id")?))
341    }
342}
343
344/// `MultisigAccountInfoDTO`。
345#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
346pub struct MultisigInfo {
347    pub multisig: MultisigJson,
348}
349
350/// `MultisigDTO`。マルチシグのアカウントと、その連署者(`cosignatoryAddresses`)、連署者として入っている
351/// マルチシグ(`multisigAddresses`)。連署者にしかなっていないアカウントにもある
352#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
353#[serde(rename_all = "camelCase")]
354pub struct MultisigJson {
355    pub version: u16,
356    pub account_address: String,
357    pub min_approval: u32,
358    pub min_removal: u32,
359    pub cosignatory_addresses: Vec<String>,
360    pub multisig_addresses: Vec<String>,
361}
362
363/// `MultisigAccountGraphInfoDTO`。マルチシグの木の1段。0 が引いたアカウントで、負は上(入っているマルチシグ)、
364/// 正は下(連署者)
365#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
366#[serde(rename_all = "camelCase")]
367pub struct MultisigGraphLevel {
368    pub level: i32,
369    pub multisig_entries: Vec<MultisigInfo>,
370}
371
372impl MultisigJson {
373    /// 状態のバイト列。catapult の `MultisigEntrySerializer`。
374    pub fn to_state_bytes(&self) -> Result<Vec<u8>, RestError> {
375        let mut out = header(self.version)?;
376        out.extend_from_slice(&self.min_approval.to_le_bytes());
377        out.extend_from_slice(&self.min_removal.to_le_bytes());
378        out.extend_from_slice(&hex_array::<24>(&self.account_address, "accountAddress")?);
379        for (addresses, name) in [
380            (&self.cosignatory_addresses, "cosignatoryAddresses"),
381            (&self.multisig_addresses, "multisigAddresses"),
382        ] {
383            out.extend_from_slice(&(addresses.len() as u64).to_le_bytes());
384            for address in addresses {
385                out.extend_from_slice(&hex_array::<24>(address, name)?);
386            }
387        }
388        Ok(out)
389    }
390
391    /// 状態のバイト列から、REST が返す形にする。[`MultisigJson::to_state_bytes`] の逆
392    pub fn from_state_bytes(bytes: &[u8]) -> Result<Self, RestError> {
393        let mut reader = StateReader::new(bytes)?;
394        let min_approval = reader.u32()?;
395        let min_removal = reader.u32()?;
396        let account_address = hex(reader.take(24)?);
397        let mut addresses = || -> Result<Vec<String>, RestError> {
398            let count = reader.u64()?;
399            (0..count).map(|_| Ok(hex(reader.take(24)?))).collect()
400        };
401        let cosignatory_addresses = addresses()?;
402        let multisig_addresses = addresses()?;
403        reader.finish()?;
404        Ok(Self {
405            version: STATE_VERSION,
406            account_address,
407            min_approval,
408            min_removal,
409            cosignatory_addresses,
410            multisig_addresses,
411        })
412    }
413
414    pub fn state_hash(&self) -> Result<Hash256, RestError> {
415        Ok(sha3(&self.to_state_bytes()?))
416    }
417
418    /// 状態の木のキー。アドレスの SHA3-256。
419    pub fn tree_key(&self) -> Result<Hash256, RestError> {
420        Ok(patricia::address_key(&Address(hex_array(
421            &self.account_address,
422            "accountAddress",
423        )?)))
424    }
425}
426
427/// `HashLockInfoDTO`。
428#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
429pub struct HashLockInfo {
430    pub lock: HashLockJson,
431}
432
433/// `HashLockEntryDTO`。`status` は 0 がまだ使っていない、1 が使った(catapult の `LockStatus`)
434#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
435#[serde(rename_all = "camelCase")]
436pub struct HashLockJson {
437    pub version: u16,
438    pub owner_address: String,
439    pub mosaic_id: String,
440    pub amount: String,
441    pub end_height: String,
442    pub status: u8,
443    pub hash: String,
444}
445
446impl HashLockJson {
447    /// 状態のバイト列。catapult の `HashLockInfoSerializer`。
448    pub fn to_state_bytes(&self) -> Result<Vec<u8>, RestError> {
449        let mut out = header(self.version)?;
450        lock_head(
451            &mut out,
452            &self.owner_address,
453            &self.mosaic_id,
454            &self.amount,
455            &self.end_height,
456            self.status,
457        )?;
458        out.extend_from_slice(&hex_array::<32>(&self.hash, "hash")?);
459        Ok(out)
460    }
461
462    /// 状態のバイト列から、REST が返す形にする。[`HashLockJson::to_state_bytes`] の逆
463    pub fn from_state_bytes(bytes: &[u8]) -> Result<Self, RestError> {
464        let mut reader = StateReader::new(bytes)?;
465        let lock = Self {
466            version: STATE_VERSION,
467            owner_address: hex(reader.take(24)?),
468            mosaic_id: format!("{:016X}", reader.u64()?),
469            amount: reader.u64()?.to_string(),
470            end_height: reader.u64()?.to_string(),
471            status: reader.u8()?,
472            hash: hex(reader.take(32)?),
473        };
474        reader.finish()?;
475        Ok(lock)
476    }
477
478    pub fn state_hash(&self) -> Result<Hash256, RestError> {
479        Ok(sha3(&self.to_state_bytes()?))
480    }
481
482    /// 状態の木のキー。ロックしたアグリゲートのハッシュの SHA3-256。
483    pub fn tree_key(&self) -> Result<Hash256, RestError> {
484        Ok(patricia::hash_key(&Hash256(hex_array(&self.hash, "hash")?)))
485    }
486}
487
488/// `SecretLockInfoDTO`。
489#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
490pub struct SecretLockInfo {
491    pub lock: SecretLockJson,
492}
493
494/// `SecretLockEntryDTO`。`compositeHash` は、シークレットと受取人から求めたハッシュ(木のキーのもと)
495#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
496#[serde(rename_all = "camelCase")]
497pub struct SecretLockJson {
498    pub version: u16,
499    pub owner_address: String,
500    pub mosaic_id: String,
501    pub amount: String,
502    pub end_height: String,
503    pub status: u8,
504    pub hash_algorithm: u8,
505    pub secret: String,
506    pub recipient_address: String,
507    pub composite_hash: String,
508}
509
510impl SecretLockJson {
511    /// 状態のバイト列。catapult の `SecretLockInfoSerializer`。`compositeHash` は入らない
512    pub fn to_state_bytes(&self) -> Result<Vec<u8>, RestError> {
513        let mut out = header(self.version)?;
514        lock_head(
515            &mut out,
516            &self.owner_address,
517            &self.mosaic_id,
518            &self.amount,
519            &self.end_height,
520            self.status,
521        )?;
522        out.push(self.hash_algorithm);
523        out.extend_from_slice(&hex_array::<32>(&self.secret, "secret")?);
524        out.extend_from_slice(&hex_array::<24>(
525            &self.recipient_address,
526            "recipientAddress",
527        )?);
528        Ok(out)
529    }
530
531    /// 状態のバイト列と、木のキーのもとのハッシュから、REST が返す形にする。[`SecretLockJson::to_state_bytes`] の逆
532    pub fn from_state_bytes(bytes: &[u8], composite_hash: &Hash256) -> Result<Self, RestError> {
533        let mut reader = StateReader::new(bytes)?;
534        let lock = Self {
535            version: STATE_VERSION,
536            owner_address: hex(reader.take(24)?),
537            mosaic_id: format!("{:016X}", reader.u64()?),
538            amount: reader.u64()?.to_string(),
539            end_height: reader.u64()?.to_string(),
540            status: reader.u8()?,
541            hash_algorithm: reader.u8()?,
542            secret: hex(reader.take(32)?),
543            recipient_address: hex(reader.take(24)?),
544            composite_hash: hex(&composite_hash.0),
545        };
546        reader.finish()?;
547        Ok(lock)
548    }
549
550    pub fn state_hash(&self) -> Result<Hash256, RestError> {
551        Ok(sha3(&self.to_state_bytes()?))
552    }
553
554    /// 状態の木のキー。`compositeHash` の SHA3-256。
555    pub fn tree_key(&self) -> Result<Hash256, RestError> {
556        Ok(patricia::hash_key(&Hash256(hex_array(
557            &self.composite_hash,
558            "compositeHash",
559        )?)))
560    }
561}
562
563/// ロック2種類に共通の頭
564fn lock_head(
565    out: &mut Vec<u8>,
566    owner_address: &str,
567    mosaic_id: &str,
568    amount: &str,
569    end_height: &str,
570    status: u8,
571) -> Result<(), RestError> {
572    out.extend_from_slice(&hex_array::<24>(owner_address, "ownerAddress")?);
573    out.extend_from_slice(&id(mosaic_id, "mosaicId")?.to_le_bytes());
574    out.extend_from_slice(&number(amount, "amount")?.to_le_bytes());
575    out.extend_from_slice(&number(end_height, "endHeight")?.to_le_bytes());
576    out.push(status);
577    Ok(())
578}
579
580/// `AccountRestrictionsInfoDTO`。
581#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
582#[serde(rename_all = "camelCase")]
583pub struct AccountRestrictionsInfo {
584    pub account_restrictions: AccountRestrictionsJson,
585}
586
587/// `AccountRestrictionsDTO`。値のある種類だけ
588#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
589#[serde(rename_all = "camelCase")]
590pub struct AccountRestrictionsJson {
591    pub version: u16,
592    pub address: String,
593    pub restrictions: Vec<AccountRestrictionJson>,
594}
595
596/// `AccountRestrictionDTO`。`restrictionFlags` は種類(1 アドレス、2 モザイク、4 トランザクションの種類)に、
597/// 向き(0x4000 送るほう)と拒む印(0x8000)を足したもの
598#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
599#[serde(rename_all = "camelCase")]
600pub struct AccountRestrictionJson {
601    pub restriction_flags: u16,
602    pub values: Vec<AccountRestrictionValue>,
603}
604
605/// 制限の値。アドレスは16進、モザイクは ID の16進、トランザクションの種類は数
606#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
607#[serde(untagged)]
608pub enum AccountRestrictionValue {
609    Operation(u16),
610    Text(String),
611}
612
613/// 制限の種類ごとの、値のバイト数
614fn restriction_value_size(flags: u16) -> Result<usize, RestError> {
615    match flags & 0x3FFF {
616        0x0001 => Ok(24),
617        0x0002 => Ok(8),
618        0x0004 => Ok(2),
619        _ => Err(RestError::InvalidValue {
620            field: "restrictionFlags",
621        }),
622    }
623}
624
625impl AccountRestrictionsJson {
626    /// 状態のバイト列。catapult の `AccountRestrictionsSerializer`。
627    pub fn to_state_bytes(&self) -> Result<Vec<u8>, RestError> {
628        let mut out = header(self.version)?;
629        out.extend_from_slice(&hex_array::<24>(&self.address, "address")?);
630        out.extend_from_slice(&(self.restrictions.len() as u64).to_le_bytes());
631        for restriction in &self.restrictions {
632            let flags = restriction.restriction_flags;
633            let size = restriction_value_size(flags)?;
634            out.extend_from_slice(&flags.to_le_bytes());
635            out.extend_from_slice(&(restriction.values.len() as u64).to_le_bytes());
636            for value in &restriction.values {
637                match (size, value) {
638                    (2, AccountRestrictionValue::Operation(kind)) => {
639                        out.extend_from_slice(&kind.to_le_bytes())
640                    }
641                    (8, AccountRestrictionValue::Text(mosaic)) => {
642                        out.extend_from_slice(&id(mosaic, "values")?.to_le_bytes())
643                    }
644                    (24, AccountRestrictionValue::Text(address)) => {
645                        out.extend_from_slice(&hex_array::<24>(address, "values")?)
646                    }
647                    _ => return Err(RestError::InvalidValue { field: "values" }),
648                }
649            }
650        }
651        Ok(out)
652    }
653
654    /// 状態のバイト列から、REST が返す形にする。[`AccountRestrictionsJson::to_state_bytes`] の逆
655    pub fn from_state_bytes(bytes: &[u8]) -> Result<Self, RestError> {
656        let mut reader = StateReader::new(bytes)?;
657        let address = hex(reader.take(24)?);
658        let mut restrictions = Vec::new();
659        for _ in 0..reader.u64()? {
660            let restriction_flags = reader.u16()?;
661            let size = restriction_value_size(restriction_flags)?;
662            let mut values = Vec::new();
663            for _ in 0..reader.u64()? {
664                let value = reader.take(size)?;
665                values.push(match size {
666                    2 => {
667                        AccountRestrictionValue::Operation(u16::from_le_bytes([value[0], value[1]]))
668                    }
669                    8 => AccountRestrictionValue::Text(format!(
670                        "{:016X}",
671                        u64::from_le_bytes(value.try_into().expect("8 バイト"))
672                    )),
673                    _ => AccountRestrictionValue::Text(hex(value)),
674                });
675            }
676            restrictions.push(AccountRestrictionJson {
677                restriction_flags,
678                values,
679            });
680        }
681        reader.finish()?;
682        Ok(Self {
683            version: STATE_VERSION,
684            address,
685            restrictions,
686        })
687    }
688
689    pub fn state_hash(&self) -> Result<Hash256, RestError> {
690        Ok(sha3(&self.to_state_bytes()?))
691    }
692
693    /// 状態の木のキー。アドレスの SHA3-256。
694    pub fn tree_key(&self) -> Result<Hash256, RestError> {
695        Ok(patricia::address_key(&Address(hex_array(
696            &self.address,
697            "address",
698        )?)))
699    }
700}
701
702/// `MosaicRestrictionsInfoDTO`(catapult の REST は `id` も返す)。
703#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
704#[serde(rename_all = "camelCase")]
705pub struct MosaicRestrictionInfo {
706    pub mosaic_restriction_entry: MosaicRestrictionEntryJson,
707}
708
709/// `MosaicAddressRestrictionDTO` か `MosaicGlobalRestrictionDTO`。`entryType` が 0 ならアドレスごとの値で
710/// `targetAddress` があり、1 ならモザイク全体の決まり
711#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
712#[serde(rename_all = "camelCase")]
713pub struct MosaicRestrictionEntryJson {
714    pub version: u16,
715    pub composite_hash: String,
716    pub entry_type: u8,
717    pub mosaic_id: String,
718    #[serde(default, skip_serializing_if = "Option::is_none")]
719    pub target_address: Option<String>,
720    pub restrictions: Vec<MosaicRestrictionJson>,
721}
722
723/// 1つのキーの値(アドレスごと)か決まり(全体)
724#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
725#[serde(rename_all = "camelCase")]
726pub struct MosaicRestrictionJson {
727    pub key: String,
728    #[serde(default, skip_serializing_if = "Option::is_none")]
729    pub value: Option<String>,
730    #[serde(default, skip_serializing_if = "Option::is_none")]
731    pub restriction: Option<MosaicGlobalRuleJson>,
732}
733
734/// モザイク全体の決まり。`referenceMosaicId` の、このキーの値を、`restrictionValue` と `restrictionType` で比べる
735#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
736#[serde(rename_all = "camelCase")]
737pub struct MosaicGlobalRuleJson {
738    pub reference_mosaic_id: String,
739    pub restriction_value: String,
740    pub restriction_type: u8,
741}
742
743impl MosaicRestrictionEntryJson {
744    /// 状態のバイト列。catapult の `MosaicRestrictionEntrySerializer`。`compositeHash` は入らない
745    pub fn to_state_bytes(&self) -> Result<Vec<u8>, RestError> {
746        let mut out = header(self.version)?;
747        out.push(self.entry_type);
748        out.extend_from_slice(&id(&self.mosaic_id, "mosaicId")?.to_le_bytes());
749        let address = self.entry_type == 0;
750        if address {
751            let target = self.target_address.as_deref().ok_or(RestError::Missing {
752                field: "targetAddress",
753            })?;
754            out.extend_from_slice(&hex_array::<24>(target, "targetAddress")?);
755        } else if self.entry_type != 1 {
756            return Err(RestError::InvalidValue { field: "entryType" });
757        }
758        out.push(
759            u8::try_from(self.restrictions.len()).map_err(|_| RestError::InvalidValue {
760                field: "restrictions",
761            })?,
762        );
763        for restriction in &self.restrictions {
764            out.extend_from_slice(&number(&restriction.key, "key")?.to_le_bytes());
765            match (address, &restriction.value, &restriction.restriction) {
766                (true, Some(value), None) => {
767                    out.extend_from_slice(&number(value, "value")?.to_le_bytes())
768                }
769                (false, None, Some(rule)) => {
770                    out.extend_from_slice(
771                        &id(&rule.reference_mosaic_id, "referenceMosaicId")?.to_le_bytes(),
772                    );
773                    out.extend_from_slice(
774                        &number(&rule.restriction_value, "restrictionValue")?.to_le_bytes(),
775                    );
776                    out.push(rule.restriction_type);
777                }
778                _ => {
779                    return Err(RestError::InvalidValue {
780                        field: "restrictions",
781                    });
782                }
783            }
784        }
785        Ok(out)
786    }
787
788    /// 状態のバイト列と、木のキーのもとのハッシュから、REST が返す形にする。
789    /// [`MosaicRestrictionEntryJson::to_state_bytes`] の逆
790    pub fn from_state_bytes(bytes: &[u8], composite_hash: &Hash256) -> Result<Self, RestError> {
791        let mut reader = StateReader::new(bytes)?;
792        let entry_type = reader.u8()?;
793        let mosaic_id = format!("{:016X}", reader.u64()?);
794        let target_address = match entry_type {
795            0 => Some(hex(reader.take(24)?)),
796            1 => None,
797            _ => return Err(RestError::InvalidValue { field: "entryType" }),
798        };
799        let mut restrictions = Vec::new();
800        for _ in 0..reader.u8()? {
801            let key = reader.u64()?.to_string();
802            restrictions.push(if target_address.is_some() {
803                MosaicRestrictionJson {
804                    key,
805                    value: Some(reader.u64()?.to_string()),
806                    restriction: None,
807                }
808            } else {
809                MosaicRestrictionJson {
810                    key,
811                    value: None,
812                    restriction: Some(MosaicGlobalRuleJson {
813                        reference_mosaic_id: format!("{:016X}", reader.u64()?),
814                        restriction_value: reader.u64()?.to_string(),
815                        restriction_type: reader.u8()?,
816                    }),
817                }
818            });
819        }
820        reader.finish()?;
821        Ok(Self {
822            version: STATE_VERSION,
823            composite_hash: hex(&composite_hash.0),
824            entry_type,
825            mosaic_id,
826            target_address,
827            restrictions,
828        })
829    }
830
831    pub fn state_hash(&self) -> Result<Hash256, RestError> {
832        Ok(sha3(&self.to_state_bytes()?))
833    }
834
835    /// 状態の木のキー。`compositeHash` の SHA3-256。
836    pub fn tree_key(&self) -> Result<Hash256, RestError> {
837        Ok(patricia::hash_key(&Hash256(hex_array(
838            &self.composite_hash,
839            "compositeHash",
840        )?)))
841    }
842}
843
844/// `MetadataInfoDTO`。
845#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
846#[serde(rename_all = "camelCase")]
847pub struct MetadataInfo {
848    /// 検索のページ送り(`offset`)に渡す位置。catapult の REST では MongoDB の ID、heika では
849    /// [`MetadataEntryJson::position`]
850    #[serde(default, skip_serializing_if = "Option::is_none")]
851    pub id: Option<String>,
852    pub metadata_entry: MetadataEntryJson,
853}
854
855/// `MetadataEntryDTO`。
856#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
857#[serde(rename_all = "camelCase")]
858pub struct MetadataEntryJson {
859    pub version: u16,
860    /// 1件を指すハッシュ。[`MetadataKey::unique_key`]
861    pub composite_hash: String,
862    pub source_address: String,
863    pub target_address: String,
864    pub scoped_metadata_key: String,
865    pub target_id: String,
866    pub metadata_type: u8,
867    pub value_size: u16,
868    pub value: String,
869}
870
871impl MetadataEntryJson {
872    /// 1件を指すキー。
873    pub fn key(&self) -> Result<MetadataKey, RestError> {
874        Ok(MetadataKey {
875            source_address: Address(hex_array(&self.source_address, "sourceAddress")?),
876            target_address: Address(hex_array(&self.target_address, "targetAddress")?),
877            scoped_metadata_key: id(&self.scoped_metadata_key, "scopedMetadataKey")?,
878            target_id: id(&self.target_id, "targetId")?,
879            metadata_type: metadata_type(self.metadata_type)?,
880        })
881    }
882
883    /// heika の REST の検索で、この件の位置(`id`)。送り主、種類、宛先、対象の ID、キーを16進でつないだもの。
884    /// 検索の `offset` に渡すと、この件の次から返す
885    pub fn position(&self) -> String {
886        format!(
887            "{}{:02X}{}{}{}",
888            self.source_address,
889            self.metadata_type,
890            self.target_address,
891            self.target_id,
892            self.scoped_metadata_key
893        )
894    }
895
896    /// 状態のバイト列から、REST が返す形にする。[`MetadataEntryJson::to_state_bytes`] の逆
897    pub fn from_state_bytes(bytes: &[u8]) -> Result<Self, RestError> {
898        let mut reader = StateReader::new(bytes)?;
899        let key = MetadataKey {
900            source_address: Address(reader.array()?),
901            target_address: Address(reader.array()?),
902            scoped_metadata_key: reader.u64()?,
903            target_id: reader.u64()?,
904            metadata_type: metadata_type(reader.u8()?)?,
905        };
906        let value_size = reader.u16()?;
907        let value = reader.take(usize::from(value_size))?;
908        reader.finish()?;
909        Ok(Self {
910            version: STATE_VERSION,
911            composite_hash: key.unique_key().to_string(),
912            source_address: hex(&key.source_address.0),
913            target_address: hex(&key.target_address.0),
914            scoped_metadata_key: format!("{:016X}", key.scoped_metadata_key),
915            target_id: format!("{:016X}", key.target_id),
916            metadata_type: key.metadata_type as u8,
917            value_size,
918            value: hex(value),
919        })
920    }
921
922    /// 状態のバイト列。catapult の `MetadataEntrySerializer`。
923    pub fn to_state_bytes(&self) -> Result<Vec<u8>, RestError> {
924        let key = self.key()?;
925        let value = hex_vec(&self.value, "value")?;
926        if value.len() != usize::from(self.value_size) {
927            return Err(RestError::Mismatch { field: "valueSize" });
928        }
929        let mut out = header(self.version)?;
930        out.extend_from_slice(&key.source_address.0);
931        out.extend_from_slice(&key.target_address.0);
932        out.extend_from_slice(&key.scoped_metadata_key.to_le_bytes());
933        out.extend_from_slice(&key.target_id.to_le_bytes());
934        out.push(self.metadata_type);
935        out.extend_from_slice(&self.value_size.to_le_bytes());
936        out.extend_from_slice(&value);
937        Ok(out)
938    }
939
940    pub fn state_hash(&self) -> Result<Hash256, RestError> {
941        Ok(sha3(&self.to_state_bytes()?))
942    }
943
944    /// 状態の木のキー。REST の `compositeHash` が中身から求めた1件のハッシュと合うかを確かめてから、その SHA3-256 にする。
945    pub fn tree_key(&self) -> Result<Hash256, RestError> {
946        let unique_key = self.key()?.unique_key();
947        if unique_key != Hash256(hex_array(&self.composite_hash, "compositeHash")?) {
948            return Err(RestError::Mismatch {
949                field: "compositeHash",
950            });
951        }
952        Ok(patricia::hash_key(&unique_key))
953    }
954}
955
956/// `NamespaceInfoDTO`。
957#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
958pub struct NamespaceInfo {
959    /// 検索のページ送り(`offset`)に渡す位置。catapult の REST では MongoDB の ID、heika では検索表のキー
960    #[serde(default, skip_serializing_if = "Option::is_none")]
961    pub id: Option<String>,
962    pub meta: NamespaceMetaJson,
963    pub namespace: NamespaceJson,
964}
965
966/// `NamespaceNameDTO`。`POST /namespaces/names` が返す1件。名前は自分の部分だけ(`xym` など)
967#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
968#[serde(rename_all = "camelCase")]
969pub struct NamespaceNameJson {
970    pub id: String,
971    pub name: String,
972    /// 子のときだけ
973    #[serde(default, skip_serializing_if = "Option::is_none")]
974    pub parent_id: Option<String>,
975}
976
977/// `AccountNamesDTO`。`POST /namespaces/account/names` の1件。名前はルートからつないだもの(`symbol.xym` など)
978#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
979pub struct AccountNamesJson {
980    pub address: String,
981    pub names: Vec<String>,
982}
983
984/// `MosaicNamesDTO`。`POST /namespaces/mosaic/names` の1件
985#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
986#[serde(rename_all = "camelCase")]
987pub struct MosaicNamesJson {
988    pub mosaic_id: String,
989    pub names: Vec<String>,
990}
991
992/// `NamespaceMetaDTO`。
993#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
994pub struct NamespaceMetaJson {
995    /// 期限の高さ(`endHeight`。catapult は猶予の期間を足した高さを持つ)が今の高さより後なら `true`。
996    /// `false` のものは状態には残るが、状態の木からは外れている
997    pub active: bool,
998}
999
1000/// `NamespaceDTO`。ルートも子も、1つずつ別に返る。
1001#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
1002#[serde(rename_all = "camelCase")]
1003pub struct NamespaceJson {
1004    pub version: u16,
1005    pub registration_type: u8,
1006    /// 経路の長さ(1から3)
1007    pub depth: u8,
1008    pub level0: String,
1009    #[serde(skip_serializing_if = "Option::is_none")]
1010    pub level1: Option<String>,
1011    #[serde(skip_serializing_if = "Option::is_none")]
1012    pub level2: Option<String>,
1013    pub alias: AliasJson,
1014    /// 親の ID。ルートは `0000000000000000`
1015    #[serde(default, skip_serializing_if = "Option::is_none")]
1016    pub parent_id: Option<String>,
1017    pub owner_address: String,
1018    pub start_height: String,
1019    pub end_height: String,
1020}
1021
1022/// `AliasDTO`。`type` が 0 なら別名なし、1 ならモザイク、2 ならアドレス。
1023#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
1024#[serde(rename_all = "camelCase")]
1025pub struct AliasJson {
1026    #[serde(rename = "type")]
1027    pub alias_type: u8,
1028    #[serde(skip_serializing_if = "Option::is_none")]
1029    pub mosaic_id: Option<String>,
1030    #[serde(skip_serializing_if = "Option::is_none")]
1031    pub address: Option<String>,
1032}
1033
1034impl NamespaceJson {
1035    /// ルートからの ID の並び。
1036    pub fn path(&self) -> Result<Vec<u64>, RestError> {
1037        let levels = [
1038            Some(&self.level0),
1039            self.level1.as_ref(),
1040            self.level2.as_ref(),
1041        ];
1042        let depth = usize::from(self.depth);
1043        if !(1..=3).contains(&depth) {
1044            return Err(RestError::InvalidValue { field: "depth" });
1045        }
1046        levels[..depth]
1047            .iter()
1048            .map(|level| id(level.ok_or(RestError::Missing { field: "level" })?, "level"))
1049            .collect()
1050    }
1051}
1052
1053impl AliasJson {
1054    fn encode(&self, out: &mut Vec<u8>) -> Result<(), RestError> {
1055        out.push(self.alias_type);
1056        match self.alias_type {
1057            0 => {}
1058            1 => out.extend_from_slice(
1059                &id(
1060                    self.mosaic_id.as_ref().ok_or(RestError::Missing {
1061                        field: "alias.mosaicId",
1062                    })?,
1063                    "alias.mosaicId",
1064                )?
1065                .to_le_bytes(),
1066            ),
1067            2 => out.extend_from_slice(&hex_array::<24>(
1068                self.address.as_ref().ok_or(RestError::Missing {
1069                    field: "alias.address",
1070                })?,
1071                "alias.address",
1072            )?),
1073            _ => {
1074                return Err(RestError::InvalidValue {
1075                    field: "alias.type",
1076                });
1077            }
1078        }
1079        Ok(())
1080    }
1081
1082    fn decode(reader: &mut StateReader) -> Result<Self, RestError> {
1083        let alias_type = reader.u8()?;
1084        let (mosaic_id, address) = match alias_type {
1085            0 => (None, None),
1086            1 => (Some(format!("{:016X}", reader.u64()?)), None),
1087            2 => (None, Some(hex(reader.take(24)?))),
1088            _ => {
1089                return Err(RestError::InvalidValue {
1090                    field: "alias.type",
1091                });
1092            }
1093        };
1094        Ok(Self {
1095            alias_type,
1096            mosaic_id,
1097            address,
1098        })
1099    }
1100}
1101
1102/// ルートのネームスペースの状態。REST はルートと子を1つずつ別に返すので、同じルートのもの
1103/// (`/namespaces?level0=<ルートの ID>` で取れる)を集めて組み直す。
1104#[derive(Clone, PartialEq, Eq, Debug)]
1105pub struct RootNamespaceState {
1106    root_id: u64,
1107    root: NamespaceJson,
1108    /// 経路の辞書順に並べた子
1109    children: Vec<(Vec<u64>, NamespaceJson)>,
1110}
1111
1112impl RootNamespaceState {
1113    /// `root_id` のルートと、その子を集める。期限(猶予を含む)が過ぎたもの(`meta.active` が `false`)は、状態の木に
1114    /// ないので除く。
1115    pub fn collect(root_id: u64, entries: &[NamespaceInfo]) -> Result<Self, RestError> {
1116        let mut root = None;
1117        let mut children = Vec::new();
1118        for entry in entries.iter().filter(|entry| entry.meta.active) {
1119            let path = entry.namespace.path()?;
1120            if path[0] != root_id {
1121                continue;
1122            }
1123            if path.len() == 1 {
1124                if root.replace(entry.namespace.clone()).is_some() {
1125                    return Err(RestError::InvalidValue { field: "level0" });
1126                }
1127            } else {
1128                children.push((path, entry.namespace.clone()));
1129            }
1130        }
1131        // catapult の `RootNamespace::sortedChildPaths` と同じく、経路の ID を辞書順に並べる
1132        children.sort_by(|a, b| a.0.cmp(&b.0));
1133        Ok(Self {
1134            root_id,
1135            root: root.ok_or(RestError::Missing { field: "level0" })?,
1136            children,
1137        })
1138    }
1139
1140    /// 状態のバイト列から組む。[`RootNamespaceState::to_state_bytes`] の逆で、ルートと子を
1141    /// REST が返す形([`NamespaceJson`])にする
1142    pub fn from_state_bytes(bytes: &[u8]) -> Result<Self, RestError> {
1143        let mut reader = StateReader::new(bytes)?;
1144        let root_id = reader.u64()?;
1145        let owner_address = hex(reader.take(24)?);
1146        let start_height = reader.u64()?.to_string();
1147        let end_height = reader.u64()?.to_string();
1148        // 子も、持ち主と期間はルートのもの
1149        let entry = |path: &[u64], alias| {
1150            let level = |depth: usize| path.get(depth).map(|id| format!("{id:016X}"));
1151            let parent = if path.len() > 1 {
1152                path[path.len() - 2]
1153            } else {
1154                0
1155            };
1156            NamespaceJson {
1157                version: STATE_VERSION,
1158                registration_type: u8::from(path.len() > 1),
1159                depth: path.len() as u8,
1160                level0: format!("{:016X}", path[0]),
1161                level1: level(1),
1162                level2: level(2),
1163                alias,
1164                parent_id: Some(format!("{parent:016X}")),
1165                owner_address: owner_address.clone(),
1166                start_height: start_height.clone(),
1167                end_height: end_height.clone(),
1168            }
1169        };
1170        let root = entry(&[root_id], AliasJson::decode(&mut reader)?);
1171        let mut children = Vec::new();
1172        for _ in 0..reader.u64()? {
1173            let depth = reader.u8()?;
1174            if !(1..=2).contains(&depth) {
1175                return Err(RestError::InvalidValue { field: "state" });
1176            }
1177            let mut path = vec![root_id];
1178            for _ in 0..depth {
1179                path.push(reader.u64()?);
1180            }
1181            let child = entry(&path, AliasJson::decode(&mut reader)?);
1182            children.push((path, child));
1183        }
1184        reader.finish()?;
1185        Ok(Self {
1186            root_id,
1187            root,
1188            children,
1189        })
1190    }
1191
1192    /// ルートか子の `id` を、`/namespaces/{id}` の形にする。なければ `None`。
1193    /// `height` は今のチェーンの高さで、catapult の REST と同じく、終わりの高さがそれより後なら `active`
1194    pub fn info(&self, id: u64, height: u64) -> Result<Option<NamespaceInfo>, RestError> {
1195        let namespace = if id == self.root_id {
1196            &self.root
1197        } else {
1198            match self
1199                .children
1200                .iter()
1201                .find(|(path, _)| path.last() == Some(&id))
1202            {
1203                Some((_, child)) => child,
1204                None => return Ok(None),
1205            }
1206        };
1207        Ok(Some(NamespaceInfo {
1208            id: None,
1209            meta: NamespaceMetaJson {
1210                active: number(&self.root.end_height, "endHeight")? > height,
1211            },
1212            namespace: namespace.clone(),
1213        }))
1214    }
1215
1216    /// 状態のバイト列。catapult の `RootNamespaceHistoryNonHistoricalSerializer`。
1217    /// 今のルートだけを、子の経路(ルートの ID を除く)と別名とともに書く。
1218    pub fn to_state_bytes(&self) -> Result<Vec<u8>, RestError> {
1219        let mut out = header(self.root.version)?;
1220        out.extend_from_slice(&self.root_id.to_le_bytes());
1221        out.extend_from_slice(&hex_array::<24>(&self.root.owner_address, "ownerAddress")?);
1222        out.extend_from_slice(&number(&self.root.start_height, "startHeight")?.to_le_bytes());
1223        out.extend_from_slice(&number(&self.root.end_height, "endHeight")?.to_le_bytes());
1224        self.root.alias.encode(&mut out)?;
1225        out.extend_from_slice(&(self.children.len() as u64).to_le_bytes());
1226        for (path, child) in &self.children {
1227            out.push((path.len() - 1) as u8);
1228            for id in &path[1..] {
1229                out.extend_from_slice(&id.to_le_bytes());
1230            }
1231            child.alias.encode(&mut out)?;
1232        }
1233        Ok(out)
1234    }
1235
1236    pub fn state_hash(&self) -> Result<Hash256, RestError> {
1237        Ok(sha3(&self.to_state_bytes()?))
1238    }
1239
1240    /// 状態の木のキー。ルートの ID の SHA3-256。
1241    pub fn tree_key(&self) -> Hash256 {
1242        patricia::id_key(self.root_id)
1243    }
1244}
1245
1246fn metadata_type(value: u8) -> Result<MetadataType, RestError> {
1247    match value {
1248        0 => Ok(MetadataType::Account),
1249        1 => Ok(MetadataType::Mosaic),
1250        2 => Ok(MetadataType::Namespace),
1251        _ => Err(RestError::InvalidValue {
1252            field: "metadataType",
1253        }),
1254    }
1255}
1256
1257/// 状態のバージョンを書く。知らないバージョンは弾く。
1258fn header(version: u16) -> Result<Vec<u8>, RestError> {
1259    if version != STATE_VERSION {
1260        return Err(RestError::InvalidValue { field: "version" });
1261    }
1262    Ok(version.to_le_bytes().to_vec())
1263}
1264
1265/// 状態のバイト列を前から読む。足りなかったり余ったりしたら、`state` が読めないことにする
1266struct StateReader<'a>(&'a [u8]);
1267
1268impl<'a> StateReader<'a> {
1269    /// バージョンを読んで確かめる
1270    fn new(bytes: &'a [u8]) -> Result<Self, RestError> {
1271        let mut reader = Self(bytes);
1272        if reader.u16()? != STATE_VERSION {
1273            return Err(RestError::InvalidValue { field: "version" });
1274        }
1275        Ok(reader)
1276    }
1277
1278    fn take(&mut self, size: usize) -> Result<&'a [u8], RestError> {
1279        let (head, rest) = self
1280            .0
1281            .split_at_checked(size)
1282            .ok_or(RestError::InvalidValue { field: "state" })?;
1283        self.0 = rest;
1284        Ok(head)
1285    }
1286
1287    fn array<const N: usize>(&mut self) -> Result<[u8; N], RestError> {
1288        Ok(self.take(N)?.try_into().expect("N bytes"))
1289    }
1290
1291    fn u8(&mut self) -> Result<u8, RestError> {
1292        Ok(self.take(1)?[0])
1293    }
1294
1295    fn u16(&mut self) -> Result<u16, RestError> {
1296        Ok(u16::from_le_bytes(
1297            self.take(2)?.try_into().expect("2 bytes"),
1298        ))
1299    }
1300
1301    fn u32(&mut self) -> Result<u32, RestError> {
1302        Ok(u32::from_le_bytes(
1303            self.take(4)?.try_into().expect("4 bytes"),
1304        ))
1305    }
1306
1307    fn u64(&mut self) -> Result<u64, RestError> {
1308        Ok(u64::from_le_bytes(
1309            self.take(8)?.try_into().expect("8 bytes"),
1310        ))
1311    }
1312
1313    fn finish(self) -> Result<(), RestError> {
1314        if self.0.is_empty() {
1315            Ok(())
1316        } else {
1317            Err(RestError::InvalidValue { field: "state" })
1318        }
1319    }
1320}
1321
1322fn sha3(bytes: &[u8]) -> Hash256 {
1323    Hash256(Sha3_256::digest(bytes).into())
1324}
1325
1326/// REST は ID を上位から16進で書く
1327pub(crate) fn id(text: &str, field: &'static str) -> Result<u64, RestError> {
1328    hex_array(text, field).map(u64::from_be_bytes)
1329}