Skip to main content

heika_rest/
transaction.rs

1//! トランザクション。`/transactions/{group}/{id}` と `/transactions/{group}` が返す `TransactionInfoDTO`。
2//!
3//! JSON から catbuffer のバイト列を組み直し、[`Transaction::from_bytes`] で読む。値として正しいか
4//! (列挙の値、並び、長さ)は heika-transaction に任せ、ここでは JSON の形と、組み直したものから求めた値が
5//! REST の `meta` と合うかを確かめる。
6//!
7//! アグリゲートは、ID かハッシュで1件取ったときだけ、中のトランザクションが `transactions` に入って返る。
8
9use heika_core::hash::Hash256;
10use heika_core::key::PublicKey;
11use heika_core::network::{NetworkIdentifier, NetworkParameters};
12use heika_core::signature::Signature;
13use heika_transaction::{
14    AccountRestriction, AliasAction, Body, EmbeddedTransaction, LinkAction, LockHashAlgorithm,
15    MosaicMetadata, MosaicRestrictionType, MosaicSupplyChangeAction, NamespaceMetadata,
16    NamespaceRegistrationType, Transaction, TransactionsHashCalculation,
17};
18use serde::{Deserialize, Serialize};
19use sha3::{Digest, Sha3_256};
20
21use crate::{RestError, hex, hex_array, hex_vec, number};
22
23/// トランザクションのヘッダーのうち、署名と手数料と期限を除いた、中のトランザクションと共通の部分の大きさ
24const EMBEDDED_HEADER_SIZE: usize = 4 + 4 + 32 + 4 + 1 + 1 + 2;
25
26/// `TransactionInfoDTO`。
27#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
28pub struct TransactionInfo {
29    /// 検索のページ送り(`offset`)に渡す位置。catapult の REST では MongoDB の ID、heika では高さとブロックの中の
30    /// 番号と、アグリゲートの中の番号([`transaction_position`])。1件ずつ引く口では返さない
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub id: Option<String>,
33    pub meta: TransactionMeta,
34    pub transaction: TransactionJson,
35}
36
37/// 承認されたトランザクションの位置。高さ(12 桁)、ブロックの中の番号(8 桁)、アグリゲートの中の番号(4 桁。0 が外側で、
38/// 中のものは 1 から)をつないだ16進。MongoDB の ID と同じ 24 桁にする
39pub fn transaction_position(height: u64, index: u32, inner: u16) -> String {
40    format!("{height:012X}{index:08X}{inner:04X}")
41}
42
43/// [`transaction_position`] を読む。読めなければ `None`
44pub fn parse_transaction_position(text: &str) -> Option<(u64, u32, u16)> {
45    if text.len() != 24 || !text.is_ascii() {
46        return None;
47    }
48    let height = u64::from_str_radix(&text[..12], 16).ok()?;
49    let index = u32::from_str_radix(&text[12..20], 16).ok()?;
50    let inner = u16::from_str_radix(&text[20..], 16).ok()?;
51    Some((height, index, inner))
52}
53
54/// `TransactionMetaDTO` と `EmbeddedTransactionMetaDTO`。どちらの形でも読めるように、項目はどれも省けるようにする。
55#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
56#[serde(rename_all = "camelCase")]
57pub struct TransactionMeta {
58    /// 承認される前なら "0"
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub height: Option<String>,
61    /// 中のトランザクションにはない
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub hash: Option<String>,
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub merkle_component_hash: Option<String>,
66    /// ブロックの中か、アグリゲートの中で何番目か(0から)
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub index: Option<u32>,
69    /// 中のトランザクションだけにある、親のアグリゲートのハッシュ
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub aggregate_hash: Option<String>,
72    /// 中のトランザクションだけにある、親のアグリゲートの `id`。catapult の REST では MongoDB の ID、heika では
73    /// [`transaction_position`]
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub aggregate_id: Option<String>,
76    /// 入ったブロックの時刻と、手数料の倍率。catapult の REST が承認されたものに足す
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub timestamp: Option<String>,
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub fee_multiplier: Option<u32>,
81}
82
83/// トランザクションの JSON。種類ごとの本体の項目は、どれか1つの種類のものだけが入る。
84#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
85#[serde(rename_all = "camelCase")]
86pub struct TransactionJson {
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub size: Option<u32>,
89    /// 中のトランザクションにはない
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub signature: Option<String>,
92    pub signer_public_key: String,
93    pub version: u8,
94    pub network: u8,
95    #[serde(rename = "type")]
96    pub transaction_type: u16,
97    /// 中のトランザクションにはない
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub max_fee: Option<String>,
100    /// 中のトランザクションにはない
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub deadline: Option<String>,
103    #[serde(flatten)]
104    pub body: BodyJson,
105}
106
107/// 25種類の本体の項目をまとめたもの。種類によって使う項目が違う。
108#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
109#[serde(rename_all = "camelCase")]
110pub struct BodyJson {
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub linked_public_key: Option<String>,
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub link_action: Option<u8>,
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub start_epoch: Option<u32>,
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub end_epoch: Option<u32>,
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub mosaic_id: Option<String>,
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub amount: Option<String>,
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub duration: Option<String>,
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub hash: Option<String>,
127    #[serde(skip_serializing_if = "Option::is_none")]
128    pub recipient_address: Option<String>,
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub secret: Option<String>,
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub hash_algorithm: Option<u8>,
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub proof: Option<String>,
135    #[serde(skip_serializing_if = "Option::is_none")]
136    pub target_address: Option<String>,
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub scoped_metadata_key: Option<String>,
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub target_mosaic_id: Option<String>,
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub target_namespace_id: Option<String>,
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub value_size_delta: Option<i16>,
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub value_size: Option<u16>,
147    #[serde(skip_serializing_if = "Option::is_none")]
148    pub value: Option<String>,
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub id: Option<String>,
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub nonce: Option<u32>,
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub flags: Option<u8>,
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub divisibility: Option<u8>,
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub delta: Option<String>,
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub action: Option<u8>,
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub source_address: Option<String>,
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub min_removal_delta: Option<i8>,
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub min_approval_delta: Option<i8>,
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub address_additions: Option<Vec<String>>,
169    #[serde(skip_serializing_if = "Option::is_none")]
170    pub address_deletions: Option<Vec<String>>,
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub namespace_id: Option<String>,
173    #[serde(skip_serializing_if = "Option::is_none")]
174    pub address: Option<String>,
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub alias_action: Option<u8>,
177    #[serde(skip_serializing_if = "Option::is_none")]
178    pub parent_id: Option<String>,
179    #[serde(skip_serializing_if = "Option::is_none")]
180    pub registration_type: Option<u8>,
181    /// ネームスペースの名前。16進ではなく、そのままの文字列
182    #[serde(skip_serializing_if = "Option::is_none")]
183    pub name: Option<String>,
184    #[serde(skip_serializing_if = "Option::is_none")]
185    pub restriction_flags: Option<u16>,
186    #[serde(skip_serializing_if = "Option::is_none")]
187    pub restriction_additions: Option<Vec<RestrictionValue>>,
188    #[serde(skip_serializing_if = "Option::is_none")]
189    pub restriction_deletions: Option<Vec<RestrictionValue>>,
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub restriction_key: Option<String>,
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub previous_restriction_value: Option<String>,
194    #[serde(skip_serializing_if = "Option::is_none")]
195    pub new_restriction_value: Option<String>,
196    #[serde(skip_serializing_if = "Option::is_none")]
197    pub reference_mosaic_id: Option<String>,
198    #[serde(skip_serializing_if = "Option::is_none")]
199    pub previous_restriction_type: Option<u8>,
200    #[serde(skip_serializing_if = "Option::is_none")]
201    pub new_restriction_type: Option<u8>,
202    #[serde(skip_serializing_if = "Option::is_none")]
203    pub mosaics: Option<Vec<MosaicJson>>,
204    #[serde(skip_serializing_if = "Option::is_none")]
205    pub message: Option<String>,
206    #[serde(skip_serializing_if = "Option::is_none")]
207    pub transactions_hash: Option<String>,
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub cosignatures: Option<Vec<CosignatureJson>>,
210    /// ID かハッシュで1件取ったときだけ入る、中のトランザクション
211    #[serde(skip_serializing_if = "Option::is_none")]
212    pub transactions: Option<Vec<TransactionInfo>>,
213}
214
215/// アカウントの制限の値。アドレスとモザイクは16進の文字列、トランザクションの種類は数で返る。
216#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
217#[serde(untagged)]
218pub enum RestrictionValue {
219    Text(String),
220    Number(u16),
221}
222
223/// `UnresolvedMosaic`。
224#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
225pub struct MosaicJson {
226    pub id: String,
227    pub amount: String,
228}
229
230/// `CosignatureDTO`。
231#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
232#[serde(rename_all = "camelCase")]
233pub struct CosignatureJson {
234    pub version: String,
235    pub signer_public_key: String,
236    pub signature: String,
237}
238
239impl TransactionJson {
240    /// catbuffer のバイト列を組み直す。アグリゲートは、中のトランザクションが入っていなければ組み直せない。
241    pub fn to_bytes(&self) -> Result<Vec<u8>, RestError> {
242        let signature = required(&self.signature, "signature")?;
243        let mut bytes = vec![0; 8];
244        bytes.extend_from_slice(&hex_array::<64>(signature, "signature")?);
245        bytes.extend_from_slice(&hex_array::<32>(
246            &self.signer_public_key,
247            "signerPublicKey",
248        )?);
249        bytes.extend_from_slice(&[0; 4]);
250        bytes.extend_from_slice(&[self.version, self.network]);
251        bytes.extend_from_slice(&self.transaction_type.to_le_bytes());
252        bytes.extend_from_slice(
253            &number(required(&self.max_fee, "maxFee")?, "maxFee")?.to_le_bytes(),
254        );
255        bytes.extend_from_slice(
256            &number(required(&self.deadline, "deadline")?, "deadline")?.to_le_bytes(),
257        );
258        bytes.extend_from_slice(&self.body.to_bytes(self.transaction_type)?);
259        set_size(&mut bytes);
260        Ok(bytes)
261    }
262
263    /// アグリゲートの中のトランザクションとして、バイト列を組み直す。
264    pub fn to_embedded_bytes(&self) -> Result<Vec<u8>, RestError> {
265        let mut bytes = vec![0; 8];
266        bytes.extend_from_slice(&hex_array::<32>(
267            &self.signer_public_key,
268            "signerPublicKey",
269        )?);
270        bytes.extend_from_slice(&[0; 4]);
271        bytes.extend_from_slice(&[self.version, self.network]);
272        bytes.extend_from_slice(&self.transaction_type.to_le_bytes());
273        debug_assert_eq!(bytes.len(), EMBEDDED_HEADER_SIZE);
274        bytes.extend_from_slice(&self.body.to_bytes(self.transaction_type)?);
275        set_size(&mut bytes);
276        Ok(bytes)
277    }
278}
279
280/// トランザクションに組み直す。
281impl TryFrom<&TransactionJson> for Transaction {
282    type Error = RestError;
283
284    fn try_from(json: &TransactionJson) -> Result<Self, Self::Error> {
285        Transaction::from_bytes(&json.to_bytes()?).map_err(RestError::InvalidTransaction)
286    }
287}
288
289impl TransactionInfo {
290    /// トランザクションを組み直し、REST が一緒に返した値と、組み直したものから求めた値が合うかを確かめる。
291    ///
292    /// 確かめるのは、署名と連署、ハッシュ(`meta.hash`)、承認されていれば Merkle の葉
293    /// (`meta.merkleComponentHash`)。アグリゲートなら、中のトランザクションから求めた TransactionsHash と、
294    /// その高さで使えるバージョンかどうかも確かめる(高さはここにある `meta.height` を信じる)。
295    /// ブロックに入っていることは、Merkle の経路で別に確かめる。
296    pub fn verify(&self) -> Result<Transaction, RestError> {
297        let network =
298            NetworkParameters::from_identifier(NetworkIdentifier(self.transaction.network))
299                .ok_or(RestError::InvalidValue { field: "network" })?;
300        let seed = &network.generation_hash_seed;
301        let transaction = Transaction::try_from(&self.transaction)?;
302        if !transaction.verify(seed) {
303            return Err(RestError::Mismatch { field: "signature" });
304        }
305        if !transaction.verify_cosignatures(seed) {
306            return Err(RestError::Mismatch {
307                field: "cosignatures",
308            });
309        }
310        let hash = transaction.hash(seed);
311        if hash
312            != Hash256(hex_array(
313                required(&self.meta.hash, "meta.hash")?,
314                "meta.hash",
315            )?)
316        {
317            return Err(RestError::Mismatch { field: "meta.hash" });
318        }
319        let height = number(required(&self.meta.height, "meta.height")?, "meta.height")?;
320        // 承認される前は、REST は Merkle の葉にもハッシュを入れる
321        if height > 0 {
322            let leaf = required(&self.meta.merkle_component_hash, "meta.merkleComponentHash")?;
323            if transaction.merkle_component_hash(seed)
324                != Hash256(hex_array(leaf, "meta.merkleComponentHash")?)
325            {
326                return Err(RestError::Mismatch {
327                    field: "meta.merkleComponentHash",
328                });
329            }
330        }
331        if let Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate) =
332            &transaction.body
333        {
334            if height > 0 && aggregate.version().number() != network.aggregate_version(height) {
335                return Err(RestError::Mismatch { field: "version" });
336            }
337            if aggregate.transactions_hash_calculation() == TransactionsHashCalculation::Unknown
338                && !network.is_known_corrupt_aggregate(&hash, &aggregate.transactions_hash())
339            {
340                return Err(RestError::Mismatch {
341                    field: "transactionsHash",
342                });
343            }
344        }
345        Ok(transaction)
346    }
347}
348
349impl BodyJson {
350    /// 種類ごとの本体のバイト列を組み直す。
351    fn to_bytes(&self, transaction_type: u16) -> Result<Vec<u8>, RestError> {
352        let mut out = Vec::new();
353        match transaction_type {
354            // AccountKeyLink、NodeKeyLink、VrfKeyLink
355            0x414C | 0x424C | 0x4243 => {
356                out.extend_from_slice(&self.hex::<32>(&self.linked_public_key, "linkedPublicKey")?);
357                out.push(*required(&self.link_action, "linkAction")?);
358            }
359            // VotingKeyLink
360            0x4143 => {
361                out.extend_from_slice(&self.hex::<32>(&self.linked_public_key, "linkedPublicKey")?);
362                out.extend_from_slice(&required(&self.start_epoch, "startEpoch")?.to_le_bytes());
363                out.extend_from_slice(&required(&self.end_epoch, "endEpoch")?.to_le_bytes());
364                out.push(*required(&self.link_action, "linkAction")?);
365            }
366            // HashLock
367            0x4148 => {
368                out.extend_from_slice(&self.id(&self.mosaic_id, "mosaicId")?);
369                out.extend_from_slice(&self.number(&self.amount, "amount")?);
370                out.extend_from_slice(&self.number(&self.duration, "duration")?);
371                out.extend_from_slice(&self.hex::<32>(&self.hash, "hash")?);
372            }
373            // SecretLock
374            0x4152 => {
375                out.extend_from_slice(
376                    &self.hex::<24>(&self.recipient_address, "recipientAddress")?,
377                );
378                out.extend_from_slice(&self.hex::<32>(&self.secret, "secret")?);
379                out.extend_from_slice(&self.id(&self.mosaic_id, "mosaicId")?);
380                out.extend_from_slice(&self.number(&self.amount, "amount")?);
381                out.extend_from_slice(&self.number(&self.duration, "duration")?);
382                out.push(*required(&self.hash_algorithm, "hashAlgorithm")?);
383            }
384            // SecretProof
385            0x4252 => {
386                let proof = hex_vec(required(&self.proof, "proof")?, "proof")?;
387                out.extend_from_slice(
388                    &self.hex::<24>(&self.recipient_address, "recipientAddress")?,
389                );
390                out.extend_from_slice(&self.hex::<32>(&self.secret, "secret")?);
391                out.extend_from_slice(&length::<u16>(proof.len(), "proof")?.to_le_bytes());
392                out.push(*required(&self.hash_algorithm, "hashAlgorithm")?);
393                out.extend_from_slice(&proof);
394            }
395            // AccountMetadata、MosaicMetadata、NamespaceMetadata
396            0x4144 | 0x4244 | 0x4344 => {
397                out.extend_from_slice(&self.hex::<24>(&self.target_address, "targetAddress")?);
398                out.extend_from_slice(&self.id(&self.scoped_metadata_key, "scopedMetadataKey")?);
399                match transaction_type {
400                    0x4244 => {
401                        out.extend_from_slice(&self.id(&self.target_mosaic_id, "targetMosaicId")?)
402                    }
403                    0x4344 => out.extend_from_slice(
404                        &self.id(&self.target_namespace_id, "targetNamespaceId")?,
405                    ),
406                    _ => {}
407                }
408                let value = hex_vec(required(&self.value, "value")?, "value")?;
409                if self
410                    .value_size
411                    .is_some_and(|size| usize::from(size) != value.len())
412                {
413                    return Err(RestError::Mismatch { field: "valueSize" });
414                }
415                out.extend_from_slice(
416                    &required(&self.value_size_delta, "valueSizeDelta")?.to_le_bytes(),
417                );
418                out.extend_from_slice(&length::<u16>(value.len(), "value")?.to_le_bytes());
419                out.extend_from_slice(&value);
420            }
421            // MosaicDefinition
422            0x414D => {
423                out.extend_from_slice(&self.id(&self.id, "id")?);
424                out.extend_from_slice(&self.number(&self.duration, "duration")?);
425                out.extend_from_slice(&required(&self.nonce, "nonce")?.to_le_bytes());
426                out.push(*required(&self.flags, "flags")?);
427                out.push(*required(&self.divisibility, "divisibility")?);
428            }
429            // MosaicSupplyChange
430            0x424D => {
431                out.extend_from_slice(&self.id(&self.mosaic_id, "mosaicId")?);
432                out.extend_from_slice(&self.number(&self.delta, "delta")?);
433                out.push(*required(&self.action, "action")?);
434            }
435            // MosaicSupplyRevocation
436            0x434D => {
437                out.extend_from_slice(&self.hex::<24>(&self.source_address, "sourceAddress")?);
438                out.extend_from_slice(&self.id(&self.mosaic_id, "mosaicId")?);
439                out.extend_from_slice(&self.number(&self.amount, "amount")?);
440            }
441            // MultisigAccountModification
442            0x4155 => {
443                let additions = addresses(&self.address_additions, "addressAdditions")?;
444                let deletions = addresses(&self.address_deletions, "addressDeletions")?;
445                out.push(*required(&self.min_removal_delta, "minRemovalDelta")? as u8);
446                out.push(*required(&self.min_approval_delta, "minApprovalDelta")? as u8);
447                out.push(length::<u8>(additions.len(), "addressAdditions")?);
448                out.push(length::<u8>(deletions.len(), "addressDeletions")?);
449                out.extend_from_slice(&[0; 4]);
450                for address in additions.iter().chain(&deletions) {
451                    out.extend_from_slice(address);
452                }
453            }
454            // AddressAlias
455            0x424E => {
456                out.extend_from_slice(&self.id(&self.namespace_id, "namespaceId")?);
457                out.extend_from_slice(&self.hex::<24>(&self.address, "address")?);
458                out.push(*required(&self.alias_action, "aliasAction")?);
459            }
460            // MosaicAlias
461            0x434E => {
462                out.extend_from_slice(&self.id(&self.namespace_id, "namespaceId")?);
463                out.extend_from_slice(&self.id(&self.mosaic_id, "mosaicId")?);
464                out.push(*required(&self.alias_action, "aliasAction")?);
465            }
466            // NamespaceRegistration。ルートなら期間、サブなら親の ID を先頭に書く
467            0x414E => {
468                let registration_type = *required(&self.registration_type, "registrationType")?;
469                match registration_type {
470                    0 => out.extend_from_slice(&self.number(&self.duration, "duration")?),
471                    1 => out.extend_from_slice(&self.id(&self.parent_id, "parentId")?),
472                    _ => {
473                        return Err(RestError::InvalidValue {
474                            field: "registrationType",
475                        });
476                    }
477                }
478                let name = required(&self.name, "name")?.as_bytes();
479                out.extend_from_slice(&self.id(&self.id, "id")?);
480                out.push(registration_type);
481                out.push(length::<u8>(name.len(), "name")?);
482                out.extend_from_slice(name);
483            }
484            // AccountAddressRestriction、AccountMosaicRestriction、AccountOperationRestriction
485            0x4150 | 0x4250 | 0x4350 => {
486                let encode = |values: &Option<Vec<RestrictionValue>>, field| {
487                    required(values, field)?
488                        .iter()
489                        .map(|value| restriction_value(transaction_type, value, field))
490                        .collect::<Result<Vec<_>, _>>()
491                };
492                let additions = encode(&self.restriction_additions, "restrictionAdditions")?;
493                let deletions = encode(&self.restriction_deletions, "restrictionDeletions")?;
494                out.extend_from_slice(
495                    &required(&self.restriction_flags, "restrictionFlags")?.to_le_bytes(),
496                );
497                out.push(length::<u8>(additions.len(), "restrictionAdditions")?);
498                out.push(length::<u8>(deletions.len(), "restrictionDeletions")?);
499                out.extend_from_slice(&[0; 4]);
500                for value in additions.iter().chain(&deletions) {
501                    out.extend_from_slice(value);
502                }
503            }
504            // MosaicAddressRestriction
505            0x4251 => {
506                out.extend_from_slice(&self.id(&self.mosaic_id, "mosaicId")?);
507                out.extend_from_slice(&self.id(&self.restriction_key, "restrictionKey")?);
508                out.extend_from_slice(
509                    &self.number(&self.previous_restriction_value, "previousRestrictionValue")?,
510                );
511                out.extend_from_slice(
512                    &self.number(&self.new_restriction_value, "newRestrictionValue")?,
513                );
514                out.extend_from_slice(&self.hex::<24>(&self.target_address, "targetAddress")?);
515            }
516            // MosaicGlobalRestriction
517            0x4151 => {
518                out.extend_from_slice(&self.id(&self.mosaic_id, "mosaicId")?);
519                out.extend_from_slice(&self.id(&self.reference_mosaic_id, "referenceMosaicId")?);
520                out.extend_from_slice(&self.id(&self.restriction_key, "restrictionKey")?);
521                out.extend_from_slice(
522                    &self.number(&self.previous_restriction_value, "previousRestrictionValue")?,
523                );
524                out.extend_from_slice(
525                    &self.number(&self.new_restriction_value, "newRestrictionValue")?,
526                );
527                out.push(*required(
528                    &self.previous_restriction_type,
529                    "previousRestrictionType",
530                )?);
531                out.push(*required(&self.new_restriction_type, "newRestrictionType")?);
532            }
533            // Transfer。メッセージとモザイクは省かれることがある
534            0x4154 => {
535                let message = match &self.message {
536                    Some(message) => hex_vec(message, "message")?,
537                    None => Vec::new(),
538                };
539                let mosaics = self.mosaics.as_deref().unwrap_or_default();
540                out.extend_from_slice(
541                    &self.hex::<24>(&self.recipient_address, "recipientAddress")?,
542                );
543                out.extend_from_slice(&length::<u16>(message.len(), "message")?.to_le_bytes());
544                out.push(length::<u8>(mosaics.len(), "mosaics")?);
545                out.extend_from_slice(&[0; 1 + 4]);
546                for mosaic in mosaics {
547                    out.extend_from_slice(&hex_id(&mosaic.id, "mosaics.id")?);
548                    out.extend_from_slice(&number(&mosaic.amount, "mosaics.amount")?.to_le_bytes());
549                }
550                out.extend_from_slice(&message);
551            }
552            // AggregateComplete、AggregateBonded
553            0x4141 | 0x4241 => {
554                let transactions = required(&self.transactions, "transactions")?;
555                let mut embedded: Vec<_> = transactions.iter().collect();
556                embedded.sort_by_key(|info| info.meta.index);
557                let mut payload = Vec::new();
558                for info in embedded {
559                    payload.extend_from_slice(&info.transaction.to_embedded_bytes()?);
560                    payload.resize(payload.len().next_multiple_of(8), 0);
561                }
562                out.extend_from_slice(
563                    &self.hex::<32>(&self.transactions_hash, "transactionsHash")?,
564                );
565                out.extend_from_slice(&length::<u32>(payload.len(), "transactions")?.to_le_bytes());
566                out.extend_from_slice(&[0; 4]);
567                out.extend_from_slice(&payload);
568                for cosignature in self.cosignatures.as_deref().unwrap_or_default() {
569                    out.extend_from_slice(
570                        &number(&cosignature.version, "cosignatures.version")?.to_le_bytes(),
571                    );
572                    out.extend_from_slice(&hex_array::<32>(
573                        &cosignature.signer_public_key,
574                        "cosignatures.signerPublicKey",
575                    )?);
576                    out.extend_from_slice(&hex_array::<64>(
577                        &cosignature.signature,
578                        "cosignatures.signature",
579                    )?);
580                }
581            }
582            _ => {
583                return Err(RestError::InvalidValue { field: "type" });
584            }
585        }
586        Ok(out)
587    }
588
589    fn hex<const N: usize>(
590        &self,
591        value: &Option<String>,
592        field: &'static str,
593    ) -> Result<[u8; N], RestError> {
594        hex_array(required(value, field)?, field)
595    }
596
597    /// 16進で書かれた u64 の ID を、リトルエンディアンの8バイトにする
598    fn id(&self, value: &Option<String>, field: &'static str) -> Result<[u8; 8], RestError> {
599        hex_id(required(value, field)?, field)
600    }
601
602    /// 10進で書かれた u64 を、リトルエンディアンの8バイトにする
603    fn number(&self, value: &Option<String>, field: &'static str) -> Result<[u8; 8], RestError> {
604        Ok(number(required(value, field)?, field)?.to_le_bytes())
605    }
606}
607
608fn required<'a, T>(value: &'a Option<T>, field: &'static str) -> Result<&'a T, RestError> {
609    value.as_ref().ok_or(RestError::Missing { field })
610}
611
612/// REST は ID を上位から16進で書くので、読んでからリトルエンディアンに並べ直す
613fn hex_id(text: &str, field: &'static str) -> Result<[u8; 8], RestError> {
614    Ok(u64::from_be_bytes(hex_array(text, field)?).to_le_bytes())
615}
616
617fn addresses(
618    values: &Option<Vec<String>>,
619    field: &'static str,
620) -> Result<Vec<[u8; 24]>, RestError> {
621    required(values, field)?
622        .iter()
623        .map(|address| hex_array(address, field))
624        .collect()
625}
626
627/// アカウントの制限の値を、種類ごとの長さのバイト列にする
628fn restriction_value(
629    transaction_type: u16,
630    value: &RestrictionValue,
631    field: &'static str,
632) -> Result<Vec<u8>, RestError> {
633    match (transaction_type, value) {
634        (0x4150, RestrictionValue::Text(address)) => Ok(hex_array::<24>(address, field)?.to_vec()),
635        (0x4250, RestrictionValue::Text(id)) => Ok(hex_id(id, field)?.to_vec()),
636        (0x4350, RestrictionValue::Number(operation)) => Ok(operation.to_le_bytes().to_vec()),
637        _ => Err(RestError::InvalidValue { field }),
638    }
639}
640
641/// 長さを、書く型に収まる数にする
642fn length<T: TryFrom<usize>>(length: usize, field: &'static str) -> Result<T, RestError> {
643    T::try_from(length).map_err(|_| RestError::InvalidValue { field })
644}
645
646/// 先頭のサイズを、組み直したバイト列の長さにする
647fn set_size(bytes: &mut [u8]) {
648    let size = bytes.len() as u32;
649    bytes[..4].copy_from_slice(&size.to_le_bytes());
650}
651
652/// 中のトランザクションなしで確かめた、アグリゲートの外側。
653#[derive(Clone, Copy, PartialEq, Eq, Debug)]
654pub struct AggregateHeader {
655    pub hash: Hash256,
656    pub merkle_component_hash: Hash256,
657    pub transactions_hash: Hash256,
658    pub version: u8,
659}
660
661impl TransactionInfo {
662    /// 検索で返る、中のトランザクションの入っていないアグリゲートを確かめる。
663    ///
664    /// 署名とハッシュは中のトランザクションに掛からず、TransactionsHash(バージョン 3 は中のトランザクションの
665    /// 長さも)までに掛かるので、外側だけで確かめられる。長さは、REST が返す全体の `size` から求める。
666    /// 確かめるのは、署名と連署、`meta.hash`、承認されていれば `meta.merkleComponentHash` とバージョン。
667    /// 中のトランザクションが TransactionsHash と合うかは、集めてから [`TransactionInfo::with_embedded`] で確かめる。
668    pub fn verify_aggregate_header(&self) -> Result<AggregateHeader, RestError> {
669        let json = &self.transaction;
670        if !matches!(json.transaction_type, 0x4141 | 0x4241) {
671            return Err(RestError::InvalidValue { field: "type" });
672        }
673        let network = NetworkParameters::from_identifier(NetworkIdentifier(json.network))
674            .ok_or(RestError::InvalidValue { field: "network" })?;
675        let seed = &network.generation_hash_seed;
676        let signature: [u8; 64] = hex_array(required(&json.signature, "signature")?, "signature")?;
677        let signer: [u8; 32] = hex_array(&json.signer_public_key, "signerPublicKey")?;
678        let transactions_hash: [u8; 32] = json
679            .body
680            .hex(&json.body.transactions_hash, "transactionsHash")?;
681        let cosignatures = json.body.cosignatures.as_deref().unwrap_or_default();
682
683        // 署名の対象。ヘッダーの後半、TransactionsHash、バージョン 3 なら中のトランザクションの長さ
684        let mut signed = vec![json.version, json.network];
685        signed.extend_from_slice(&json.transaction_type.to_le_bytes());
686        signed.extend_from_slice(
687            &number(required(&json.max_fee, "maxFee")?, "maxFee")?.to_le_bytes(),
688        );
689        signed.extend_from_slice(
690            &number(required(&json.deadline, "deadline")?, "deadline")?.to_le_bytes(),
691        );
692        signed.extend_from_slice(&transactions_hash);
693        if json.version >= 3 {
694            let size = *required(&json.size, "size")? as usize;
695            let payload_size = size
696                .checked_sub(
697                    TRANSACTION_HEADER_SIZE
698                        + AGGREGATE_FIXED_SIZE
699                        + COSIGNATURE_SIZE * cosignatures.len(),
700                )
701                .ok_or(RestError::InvalidValue { field: "size" })?;
702            signed.extend_from_slice(&length::<u32>(payload_size, "size")?.to_le_bytes());
703        }
704        if !PublicKey(signer).verify(&[&seed.0, &signed], &Signature(signature)) {
705            return Err(RestError::Mismatch { field: "signature" });
706        }
707        let hash = Hash256(
708            Sha3_256::new()
709                .chain_update(signature)
710                .chain_update(signer)
711                .chain_update(seed.0)
712                .chain_update(&signed)
713                .finalize()
714                .into(),
715        );
716        if hash
717            != Hash256(hex_array(
718                required(&self.meta.hash, "meta.hash")?,
719                "meta.hash",
720            )?)
721        {
722            return Err(RestError::Mismatch { field: "meta.hash" });
723        }
724
725        let mut leaf = Sha3_256::new().chain_update(hash.0);
726        for cosignature in cosignatures {
727            if number(&cosignature.version, "cosignatures.version")? != 0 {
728                return Err(RestError::InvalidValue {
729                    field: "cosignatures.version",
730                });
731            }
732            let key = PublicKey(hex_array(
733                &cosignature.signer_public_key,
734                "cosignatures.signerPublicKey",
735            )?);
736            let signature = Signature(hex_array(&cosignature.signature, "cosignatures.signature")?);
737            if !key.verify(&[&hash.0], &signature) {
738                return Err(RestError::Mismatch {
739                    field: "cosignatures",
740                });
741            }
742            leaf.update(key.0);
743        }
744        let merkle_component_hash = if cosignatures.is_empty() {
745            hash
746        } else {
747            Hash256(leaf.finalize().into())
748        };
749        let height = number(required(&self.meta.height, "meta.height")?, "meta.height")?;
750        if height > 0 {
751            let expected = required(&self.meta.merkle_component_hash, "meta.merkleComponentHash")?;
752            if merkle_component_hash != Hash256(hex_array(expected, "meta.merkleComponentHash")?) {
753                return Err(RestError::Mismatch {
754                    field: "meta.merkleComponentHash",
755                });
756            }
757            if json.version != network.aggregate_version(height) {
758                return Err(RestError::Mismatch { field: "version" });
759            }
760        }
761        Ok(AggregateHeader {
762            hash,
763            merkle_component_hash,
764            transactions_hash: Hash256(transactions_hash),
765            version: json.version,
766        })
767    }
768
769    /// `embedded=true` の検索で平たく並んで返った中のトランザクションから、このアグリゲートのものを
770    /// (`meta.aggregateHash` で)集め、`meta.index` の順に `transactions` に入れたものを返す。
771    /// 返したものを [`TransactionInfo::verify`] にかければ、中のトランザクションまで確かめられる。
772    ///
773    /// 集めたものの `meta.index` が0から抜けなく続いていなければ弾く。
774    pub fn with_embedded(&self, entries: &[TransactionInfo]) -> Result<TransactionInfo, RestError> {
775        let hash = Hash256(hex_array(
776            required(&self.meta.hash, "meta.hash")?,
777            "meta.hash",
778        )?);
779        let mut embedded = Vec::new();
780        for entry in entries {
781            let Some(parent) = &entry.meta.aggregate_hash else {
782                continue;
783            };
784            if Hash256(hex_array(parent, "meta.aggregateHash")?) == hash {
785                embedded.push(entry.clone());
786            }
787        }
788        embedded.sort_by_key(|entry| entry.meta.index);
789        if embedded
790            .iter()
791            .enumerate()
792            .any(|(index, entry)| entry.meta.index != Some(index as u32))
793        {
794            return Err(RestError::InvalidValue {
795                field: "meta.index",
796            });
797        }
798        let mut aggregate = self.clone();
799        aggregate.transaction.body.transactions = Some(embedded);
800        Ok(aggregate)
801    }
802}
803
804/// 署名と手数料と期限を含めた、トランザクションのヘッダーの大きさ
805const TRANSACTION_HEADER_SIZE: usize = 4 + 4 + 64 + 32 + 4 + 1 + 1 + 2 + 8 + 8;
806/// アグリゲートの、中のトランザクションより前の部分。TransactionsHash、中のトランザクションの長さ、予約
807const AGGREGATE_FIXED_SIZE: usize = 32 + 4 + 4;
808/// 連署1つの大きさ。バージョン、公開鍵、署名
809const COSIGNATURE_SIZE: usize = 8 + 32 + 64;
810
811/// トランザクションを、REST が返す形にする。アグリゲートなら、ID かハッシュで1件取ったときと同じく、
812/// 中のトランザクションを `transactions` に入れ、`meta` には何番目かだけを書く。
813impl From<&Transaction> for TransactionJson {
814    fn from(transaction: &Transaction) -> Self {
815        Self {
816            size: Some(transaction.size() as u32),
817            signature: Some(transaction.signature.to_string()),
818            signer_public_key: transaction.signer_public_key.to_string(),
819            version: transaction.body.version(),
820            network: transaction.network.0,
821            transaction_type: transaction.body.transaction_type(),
822            max_fee: Some(transaction.fee.to_string()),
823            deadline: Some(transaction.deadline.to_string()),
824            body: body_json(&transaction.body),
825        }
826    }
827}
828
829/// アグリゲートの中のトランザクションを、REST が返す形にする。署名、手数料、期限、大きさはない。
830impl From<&EmbeddedTransaction> for TransactionJson {
831    fn from(embedded: &EmbeddedTransaction) -> Self {
832        Self {
833            size: None,
834            signature: None,
835            signer_public_key: embedded.signer_public_key.to_string(),
836            version: embedded.body.version(),
837            network: embedded.network.0,
838            transaction_type: embedded.body.transaction_type(),
839            max_fee: None,
840            deadline: None,
841            body: body_json(&embedded.body),
842        }
843    }
844}
845
846/// 種類ごとの本体の項目を、catapult-rest と同じ書き方で埋める。
847fn body_json(body: &Body) -> BodyJson {
848    let mut json = BodyJson::default();
849    let id = |value: u64| Some(format!("{value:016X}"));
850    let decimal = |value: u64| Some(value.to_string());
851    let address = |bytes: &[u8; 24]| Some(hex(bytes));
852    match body {
853        Body::AccountKeyLink(link) | Body::NodeKeyLink(link) | Body::VrfKeyLink(link) => {
854            json.linked_public_key = Some(link.linked_public_key.to_string());
855            json.link_action = Some(link_action(link.link_action));
856        }
857        Body::VotingKeyLink(link) => {
858            json.linked_public_key = Some(link.linked_public_key.to_string());
859            json.start_epoch = Some(link.start_epoch);
860            json.end_epoch = Some(link.end_epoch);
861            json.link_action = Some(link_action(link.link_action));
862        }
863        Body::HashLock(lock) => {
864            json.mosaic_id = id(lock.mosaic.mosaic_id.0);
865            json.amount = decimal(lock.mosaic.amount);
866            json.duration = decimal(lock.duration);
867            json.hash = Some(lock.hash.to_string());
868        }
869        Body::SecretLock(lock) => {
870            json.recipient_address = address(&lock.recipient_address.0);
871            json.secret = Some(lock.secret.to_string());
872            json.mosaic_id = id(lock.mosaic.mosaic_id.0);
873            json.amount = decimal(lock.mosaic.amount);
874            json.duration = decimal(lock.duration);
875            json.hash_algorithm = Some(hash_algorithm(lock.hash_algorithm));
876        }
877        Body::SecretProof(proof) => {
878            json.recipient_address = address(&proof.recipient_address.0);
879            json.secret = Some(proof.secret.to_string());
880            json.hash_algorithm = Some(hash_algorithm(proof.hash_algorithm));
881            json.proof = Some(hex(&proof.proof));
882        }
883        Body::AccountMetadata(metadata)
884        | Body::MosaicMetadata(MosaicMetadata { metadata, .. })
885        | Body::NamespaceMetadata(NamespaceMetadata { metadata, .. }) => {
886            json.target_address = address(&metadata.target_address.0);
887            json.scoped_metadata_key = id(metadata.scoped_metadata_key);
888            json.value_size_delta = Some(metadata.value_size_delta);
889            json.value_size = Some(metadata.value.len() as u16);
890            json.value = Some(hex(&metadata.value));
891            match body {
892                Body::MosaicMetadata(mosaic) => {
893                    json.target_mosaic_id = id(mosaic.target_mosaic_id.0)
894                }
895                Body::NamespaceMetadata(namespace) => {
896                    json.target_namespace_id = id(namespace.target_namespace_id.0)
897                }
898                _ => {}
899            }
900        }
901        Body::MosaicDefinition(definition) => {
902            json.id = id(definition.id.0);
903            json.duration = decimal(definition.duration);
904            json.nonce = Some(definition.nonce);
905            json.flags = Some(definition.flags.bits());
906            json.divisibility = Some(definition.divisibility);
907        }
908        Body::MosaicSupplyChange(change) => {
909            json.mosaic_id = id(change.mosaic_id.0);
910            json.delta = decimal(change.delta);
911            json.action = Some(match change.action {
912                MosaicSupplyChangeAction::Decrease => 0,
913                MosaicSupplyChangeAction::Increase => 1,
914            });
915        }
916        Body::MosaicSupplyRevocation(revocation) => {
917            json.source_address = address(&revocation.source_address.0);
918            json.mosaic_id = id(revocation.mosaic.mosaic_id.0);
919            json.amount = decimal(revocation.mosaic.amount);
920        }
921        Body::MultisigAccountModification(modification) => {
922            json.min_removal_delta = Some(modification.min_removal_delta);
923            json.min_approval_delta = Some(modification.min_approval_delta);
924            json.address_additions = Some(
925                modification
926                    .address_additions
927                    .iter()
928                    .map(|address| hex(&address.0))
929                    .collect(),
930            );
931            json.address_deletions = Some(
932                modification
933                    .address_deletions
934                    .iter()
935                    .map(|address| hex(&address.0))
936                    .collect(),
937            );
938        }
939        Body::AddressAlias(alias) => {
940            json.namespace_id = id(alias.namespace_id.0);
941            json.address = address(&alias.address.0);
942            json.alias_action = Some(alias_action(alias.alias_action));
943        }
944        Body::MosaicAlias(alias) => {
945            json.namespace_id = id(alias.namespace_id.0);
946            json.mosaic_id = id(alias.mosaic_id.0);
947            json.alias_action = Some(alias_action(alias.alias_action));
948        }
949        Body::NamespaceRegistration(registration) => {
950            match registration.registration_type {
951                NamespaceRegistrationType::Root { duration } => {
952                    json.registration_type = Some(0);
953                    json.duration = decimal(duration);
954                }
955                NamespaceRegistrationType::Child { parent_id } => {
956                    json.registration_type = Some(1);
957                    json.parent_id = id(parent_id.0);
958                }
959            }
960            json.id = id(registration.id.0);
961            json.name = Some(String::from_utf8_lossy(&registration.name).into_owned());
962        }
963        Body::AccountAddressRestriction(restriction) => {
964            account_restriction(&mut json, restriction, |address| {
965                RestrictionValue::Text(hex(&address.0))
966            })
967        }
968        Body::AccountMosaicRestriction(restriction) => {
969            account_restriction(&mut json, restriction, |mosaic| {
970                RestrictionValue::Text(format!("{:016X}", mosaic.0))
971            })
972        }
973        Body::AccountOperationRestriction(restriction) => {
974            account_restriction(&mut json, restriction, |operation| {
975                RestrictionValue::Number(operation.0)
976            })
977        }
978        Body::MosaicAddressRestriction(restriction) => {
979            json.mosaic_id = id(restriction.mosaic_id.0);
980            json.restriction_key = id(restriction.restriction_key);
981            json.previous_restriction_value = decimal(restriction.previous_restriction_value);
982            json.new_restriction_value = decimal(restriction.new_restriction_value);
983            json.target_address = address(&restriction.target_address.0);
984        }
985        Body::MosaicGlobalRestriction(restriction) => {
986            json.mosaic_id = id(restriction.mosaic_id.0);
987            json.reference_mosaic_id = id(restriction.reference_mosaic_id.0);
988            json.restriction_key = id(restriction.restriction_key);
989            json.previous_restriction_value = decimal(restriction.previous_restriction_value);
990            json.new_restriction_value = decimal(restriction.new_restriction_value);
991            json.previous_restriction_type = Some(mosaic_restriction_type(
992                restriction.previous_restriction_type,
993            ));
994            json.new_restriction_type =
995                Some(mosaic_restriction_type(restriction.new_restriction_type));
996        }
997        Body::Transfer(transfer) => {
998            json.recipient_address = address(&transfer.recipient_address().0);
999            json.mosaics = Some(
1000                transfer
1001                    .mosaics()
1002                    .iter()
1003                    .map(|(mosaic, amount)| MosaicJson {
1004                        id: format!("{:016X}", mosaic.0),
1005                        amount: amount.to_string(),
1006                    })
1007                    .collect(),
1008            );
1009            // catapult-rest は、空のメッセージを書かない
1010            if !transfer.message().is_empty() {
1011                json.message = Some(hex(transfer.message()));
1012            }
1013        }
1014        Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate) => {
1015            json.transactions_hash = Some(aggregate.transactions_hash().to_string());
1016            json.cosignatures = Some(
1017                aggregate
1018                    .cosignatures()
1019                    .iter()
1020                    .map(|cosignature| CosignatureJson {
1021                        version: "0".to_owned(),
1022                        signer_public_key: cosignature.signer_public_key.to_string(),
1023                        signature: cosignature.signature.to_string(),
1024                    })
1025                    .collect(),
1026            );
1027            json.transactions = Some(
1028                aggregate
1029                    .transactions()
1030                    .iter()
1031                    .enumerate()
1032                    .map(|(index, embedded)| TransactionInfo {
1033                        id: None,
1034                        meta: TransactionMeta {
1035                            height: None,
1036                            hash: None,
1037                            merkle_component_hash: None,
1038                            index: Some(index as u32),
1039                            aggregate_hash: None,
1040                            aggregate_id: None,
1041                            timestamp: None,
1042                            fee_multiplier: None,
1043                        },
1044                        transaction: TransactionJson::from(embedded),
1045                    })
1046                    .collect(),
1047            );
1048        }
1049    }
1050    json
1051}
1052
1053fn account_restriction<T>(
1054    json: &mut BodyJson,
1055    restriction: &AccountRestriction<T>,
1056    value: impl Fn(&T) -> RestrictionValue,
1057) {
1058    json.restriction_flags = Some(restriction.restriction_flags.bits());
1059    json.restriction_additions = Some(
1060        restriction
1061            .restriction_additions
1062            .iter()
1063            .map(&value)
1064            .collect(),
1065    );
1066    json.restriction_deletions = Some(
1067        restriction
1068            .restriction_deletions
1069            .iter()
1070            .map(&value)
1071            .collect(),
1072    );
1073}
1074
1075fn link_action(action: LinkAction) -> u8 {
1076    match action {
1077        LinkAction::Unlink => 0,
1078        LinkAction::Link => 1,
1079    }
1080}
1081
1082fn alias_action(action: AliasAction) -> u8 {
1083    match action {
1084        AliasAction::Unlink => 0,
1085        AliasAction::Link => 1,
1086    }
1087}
1088
1089fn hash_algorithm(algorithm: LockHashAlgorithm) -> u8 {
1090    match algorithm {
1091        LockHashAlgorithm::Sha3_256 => 0,
1092        LockHashAlgorithm::Hash160 => 1,
1093        LockHashAlgorithm::Hash256 => 2,
1094    }
1095}
1096
1097fn mosaic_restriction_type(value: MosaicRestrictionType) -> u8 {
1098    match value {
1099        MosaicRestrictionType::None => 0,
1100        MosaicRestrictionType::Eq => 1,
1101        MosaicRestrictionType::Ne => 2,
1102        MosaicRestrictionType::Lt => 3,
1103        MosaicRestrictionType::Le => 4,
1104        MosaicRestrictionType::Gt => 5,
1105        MosaicRestrictionType::Ge => 6,
1106    }
1107}