Skip to main content

heika_rest/
node.rs

1//! ノードとチェーンの様子。`/node/info`、`/node/peers`、`/chain/info`、`/node/unlockedaccount`、`/node/server`、`/node/health`、
2//! `/network`、`/network/properties` が返す JSON と、heika だけの
3//! `/heika/delegations`(委任の様子)と、`PUT /transactions` の本文と答え。
4//!
5//! catapult の REST の `NodeInfoDTO`、`ChainInfoDTO`、`UnlockedAccountDTO` に合わせている。64ビットの数は、catapult の
6//! REST と同じく10進の文字列にする。heika の API はこれを返し、クライアントはこれで読む。
7
8use serde::{Deserialize, Serialize};
9
10/// `NodeInfoDTO`。ウォレットは、委任するノードの `nodePublicKey` をここから取る
11#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
12#[serde(rename_all = "camelCase")]
13pub struct NodeInfoJson {
14    pub version: u32,
15    /// ノードを見分ける鍵(CA の公開鍵)。16進
16    pub public_key: String,
17    pub network_generation_hash_seed: String,
18    pub roles: u32,
19    pub port: u16,
20    pub network_identifier: u8,
21    pub host: String,
22    pub friendly_name: String,
23    /// 委任の鍵(NodeKeyLink を向ける鍵)。16進。`/node/peers` のピアにはない
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub node_public_key: Option<String>,
26}
27
28/// `NetworkTypeDTO`(`/network`)。ノードの一覧を作るクローラーは、これでどのネットワークのノードかを見分ける
29#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
30pub struct NetworkJson {
31    /// `mainnet`、`testnet` など
32    pub name: String,
33    pub description: String,
34}
35
36/// `NetworkConfigurationDTO`(`/network/properties`)。catapult の REST は、ノードの `config-network.properties` を
37/// そのまま返す。値は、ファイルに書いてあるとおりの文字列(`6h`、`0x6BED'913F'A202'23F8`、`10'000'000` など)で、
38/// `true` と `false` だけ真偽値にする。読む側は、桁の区切りの `'` を外して読む
39#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
40pub struct NetworkPropertiesJson {
41    pub network: NetworkSectionJson,
42    pub chain: ChainSectionJson,
43    pub plugins: PluginsJson,
44}
45
46/// `[network]`
47#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
48#[serde(rename_all = "camelCase")]
49pub struct NetworkSectionJson {
50    pub identifier: String,
51    pub nemesis_signer_public_key: String,
52    pub node_equality_strategy: String,
53    pub generation_hash_seed: String,
54    pub epoch_adjustment: String,
55}
56
57/// `[chain]`
58#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
59#[serde(rename_all = "camelCase")]
60pub struct ChainSectionJson {
61    pub enable_verifiable_state: bool,
62    pub enable_verifiable_receipts: bool,
63    pub currency_mosaic_id: String,
64    pub harvesting_mosaic_id: String,
65    pub block_generation_target_time: String,
66    pub block_time_smoothing_factor: String,
67    pub importance_grouping: String,
68    pub importance_activity_percentage: String,
69    pub max_difficulty_blocks: String,
70    pub default_dynamic_fee_multiplier: String,
71    pub max_transaction_lifetime: String,
72    pub max_block_future_time: String,
73    pub max_mosaic_atomic_units: String,
74    pub total_chain_importance: String,
75    pub min_harvester_balance: String,
76    pub max_harvester_balance: String,
77    pub min_voter_balance: String,
78    pub voting_set_grouping: String,
79    pub max_voting_keys_per_account: String,
80    pub min_voting_key_lifetime: String,
81    pub max_voting_key_lifetime: String,
82    pub harvest_beneficiary_percentage: String,
83    pub harvest_network_percentage: String,
84    #[serde(rename = "harvestNetworkFeeSinkAddressV1")]
85    pub harvest_network_fee_sink_address_v1: String,
86    pub harvest_network_fee_sink_address: String,
87    pub max_transactions_per_block: String,
88}
89
90/// `[plugin:catapult.plugins.*]`
91#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
92pub struct PluginsJson {
93    pub accountlink: AccountLinkPluginJson,
94    pub aggregate: AggregatePluginJson,
95    pub lockhash: LockHashPluginJson,
96    pub locksecret: LockSecretPluginJson,
97    pub metadata: MetadataPluginJson,
98    pub mosaic: MosaicPluginJson,
99    pub multisig: MultisigPluginJson,
100    pub namespace: NamespacePluginJson,
101    pub restrictionaccount: AccountRestrictionPluginJson,
102    pub restrictionmosaic: MosaicRestrictionPluginJson,
103    pub transfer: TransferPluginJson,
104}
105
106/// 設定のない plugin を読み込ませるための、中身のない値
107#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
108pub struct AccountLinkPluginJson {
109    pub dummy: String,
110}
111
112#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
113#[serde(rename_all = "camelCase")]
114pub struct AggregatePluginJson {
115    pub max_transactions_per_aggregate: String,
116    pub max_cosignatures_per_aggregate: String,
117    pub enable_strict_cosignature_check: bool,
118    pub enable_bonded_aggregate_support: bool,
119    pub max_bonded_transaction_lifetime: String,
120}
121
122#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
123#[serde(rename_all = "camelCase")]
124pub struct LockHashPluginJson {
125    pub locked_funds_per_aggregate: String,
126    pub max_hash_lock_duration: String,
127}
128
129#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
130#[serde(rename_all = "camelCase")]
131pub struct LockSecretPluginJson {
132    pub max_secret_lock_duration: String,
133    pub min_proof_size: String,
134    pub max_proof_size: String,
135}
136
137#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
138#[serde(rename_all = "camelCase")]
139pub struct MetadataPluginJson {
140    pub max_value_size: String,
141}
142
143#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
144#[serde(rename_all = "camelCase")]
145pub struct MosaicPluginJson {
146    pub max_mosaics_per_account: String,
147    pub max_mosaic_duration: String,
148    pub max_mosaic_divisibility: String,
149    #[serde(rename = "mosaicRentalFeeSinkAddressV1")]
150    pub mosaic_rental_fee_sink_address_v1: String,
151    pub mosaic_rental_fee_sink_address: String,
152    pub mosaic_rental_fee: String,
153}
154
155#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
156#[serde(rename_all = "camelCase")]
157pub struct MultisigPluginJson {
158    pub max_multisig_depth: String,
159    pub max_cosignatories_per_account: String,
160    pub max_cosigned_accounts_per_account: String,
161}
162
163#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
164#[serde(rename_all = "camelCase")]
165pub struct NamespacePluginJson {
166    pub max_name_size: String,
167    pub max_child_namespaces: String,
168    pub max_namespace_depth: String,
169    pub min_namespace_duration: String,
170    pub max_namespace_duration: String,
171    pub namespace_grace_period_duration: String,
172    #[serde(rename = "namespaceRentalFeeSinkAddressV1")]
173    pub namespace_rental_fee_sink_address_v1: String,
174    pub namespace_rental_fee_sink_address: String,
175    pub root_namespace_rental_fee_per_block: String,
176    pub child_namespace_rental_fee: String,
177}
178
179#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
180#[serde(rename_all = "camelCase")]
181pub struct AccountRestrictionPluginJson {
182    pub max_account_restriction_values: String,
183}
184
185#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
186#[serde(rename_all = "camelCase")]
187pub struct MosaicRestrictionPluginJson {
188    pub max_mosaic_restriction_values: String,
189}
190
191#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
192#[serde(rename_all = "camelCase")]
193pub struct TransferPluginJson {
194    pub max_message_size: String,
195}
196
197/// `ServerInfoDTO`(`/node/server`)
198#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
199#[serde(rename_all = "camelCase")]
200pub struct ServerInfoJson {
201    pub server_info: ServerJson,
202}
203
204/// [`ServerInfoJson`] の中身。catapult の REST は、わからない値を `N/A` にする
205#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
206#[serde(rename_all = "camelCase")]
207pub struct ServerJson {
208    pub rest_version: String,
209    pub deployment: DeploymentJson,
210}
211
212#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
213#[serde(rename_all = "camelCase")]
214pub struct DeploymentJson {
215    pub deployment_tool: String,
216    pub deployment_tool_version: String,
217    pub last_updated_date: String,
218}
219
220/// `NodeTimeDTO`(`/node/time`)。ノードの時計の、ネットワーク時刻(Nemesis からのミリ秒)
221#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
222#[serde(rename_all = "camelCase")]
223pub struct NodeTimeJson {
224    pub communication_timestamps: CommunicationTimestampsJson,
225}
226
227/// 要求を受け取った時刻と、答えを返した時刻。catapult の REST と同じく、10進の文字列
228#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
229#[serde(rename_all = "camelCase")]
230pub struct CommunicationTimestampsJson {
231    pub send_timestamp: String,
232    pub receive_timestamp: String,
233}
234
235/// `NodeHealthDTO`(`/node/health`)
236#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
237pub struct NodeHealthJson {
238    pub status: HealthStatusJson,
239}
240
241/// `up` か `down`
242#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
243#[serde(rename_all = "camelCase")]
244pub struct HealthStatusJson {
245    pub api_node: String,
246    pub db: String,
247}
248
249/// `FinalizedBlockDTO`
250#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
251#[serde(rename_all = "camelCase")]
252pub struct FinalizedBlockJson {
253    pub finalization_epoch: u32,
254    pub finalization_point: u32,
255    pub height: String,
256    pub hash: String,
257}
258
259/// `ChainInfoDTO`
260#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
261#[serde(rename_all = "camelCase")]
262pub struct ChainInfoJson {
263    pub height: String,
264    pub score_high: String,
265    pub score_low: String,
266    pub latest_finalized_block: FinalizedBlockJson,
267}
268
269impl ChainInfoJson {
270    /// 高さ、スコア、確定したブロックから作る。スコアは上の64ビットと下の64ビットに分ける
271    pub fn new(
272        height: u64,
273        score: u128,
274        epoch: u32,
275        point: u32,
276        finalized: u64,
277        hash: String,
278    ) -> Self {
279        Self {
280            height: height.to_string(),
281            score_high: ((score >> 64) as u64).to_string(),
282            score_low: (score as u64).to_string(),
283            latest_finalized_block: FinalizedBlockJson {
284                finalization_epoch: epoch,
285                finalization_point: point,
286                height: finalized.to_string(),
287                hash,
288            },
289        }
290    }
291}
292
293/// `UnlockedAccountDTO`。ノードがハーベストしている、委任されたリモートの鍵(16進)
294#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
295#[serde(rename_all = "camelCase")]
296pub struct UnlockedAccountJson {
297    pub unlocked_account: Vec<String>,
298}
299
300/// 委任の様子(heika だけ)
301#[derive(Clone, Copy, PartialEq, Eq, Debug, Deserialize, Serialize)]
302#[serde(rename_all = "camelCase")]
303pub enum DelegationStateJson {
304    /// 引き受けて、ハーベストしている
305    Accepted,
306    /// 取り込めるが、上限を超えているので空きを待っている
307    Waiting,
308    /// 引き受けなかった。`reason` にわけがある
309    Rejected,
310}
311
312/// `/heika/delegations` の1件。届いた委任の要求ごとに、引き受けたか、なぜ引き受けなかったか
313#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
314#[serde(rename_all = "camelCase")]
315pub struct DelegationJson {
316    /// メインアカウントの公開鍵(16進)。わからなければ null
317    pub main_public_key: Option<String>,
318    /// 要求に入っていたリモートの鍵(16進)
319    pub remote_public_key: String,
320    /// 要求が入っていたブロックの高さ。わからなければ null
321    pub height: Option<String>,
322    pub state: DelegationStateJson,
323    pub reason: Option<String>,
324}
325
326/// `/network/fees/transaction` が返す `TransactionFeesDTO`。直近のブロックの手数料の倍率と、ノードが受け付ける下限
327#[derive(Clone, Copy, PartialEq, Eq, Debug, Deserialize, Serialize)]
328#[serde(rename_all = "camelCase")]
329pub struct TransactionFeesJson {
330    pub average_fee_multiplier: u32,
331    pub median_fee_multiplier: u32,
332    pub highest_fee_multiplier: u32,
333    pub lowest_fee_multiplier: u32,
334    pub min_fee_multiplier: u32,
335}
336
337impl TransactionFeesJson {
338    /// 直近のブロックの倍率 `multipliers`(並びは問わない)と、ノードの下限から作る。中央値は catapult の REST と同じく、
339    /// 数が偶数なら真ん中の2つの平均(切り捨て)。ブロックがなければ倍率は0
340    pub fn new(mut multipliers: Vec<u32>, min_fee_multiplier: u32) -> Self {
341        multipliers.sort_unstable();
342        let count = multipliers.len();
343        let median = match count {
344            0 => 0,
345            _ if count % 2 == 1 => multipliers[count / 2],
346            _ => {
347                ((u64::from(multipliers[count / 2 - 1]) + u64::from(multipliers[count / 2])) / 2)
348                    as u32
349            }
350        };
351        let sum: u64 = multipliers.iter().map(|&value| u64::from(value)).sum();
352        Self {
353            average_fee_multiplier: if count == 0 {
354                0
355            } else {
356                (sum / count as u64) as u32
357            },
358            median_fee_multiplier: median,
359            highest_fee_multiplier: multipliers.last().copied().unwrap_or(0),
360            lowest_fee_multiplier: multipliers.first().copied().unwrap_or(0),
361            min_fee_multiplier,
362        }
363    }
364}
365
366/// `PUT /transactions` の本文。署名したトランザクション(16進)
367#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
368pub struct AnnounceJson {
369    pub payload: String,
370}
371
372/// `PUT /transactions` が受け付けたときの答え(catapult の REST と同じ文)
373#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
374pub struct AnnounceResultJson {
375    pub message: String,
376}
377
378impl AnnounceResultJson {
379    pub fn pushed() -> Self {
380        Self::pushed_via(9, "/transactions")
381    }
382
383    /// パケットの種類 `packet_type` で、口 `path` から流したとき(catapult の REST と同じ文)
384    pub fn pushed_via(packet_type: u32, path: &str) -> Self {
385        Self {
386            message: format!("packet {packet_type} was pushed to the network via {path}"),
387        }
388    }
389}
390
391/// `PUT /transactions/cosignature` の本体(catapult の `CosignatureDTO`)。16進で、`version` は10進の文字列
392#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
393#[serde(rename_all = "camelCase")]
394pub struct CosignatureJson {
395    #[serde(default)]
396    pub version: Option<String>,
397    pub signer_public_key: String,
398    pub signature: String,
399    pub parent_hash: String,
400}
401
402/// 受け付けなかったときの答え(catapult の REST のエラーと同じ形)
403#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
404pub struct ErrorJson {
405    pub code: String,
406    pub message: String,
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    #[test]
414    fn chain_info_reads_the_catapult_shape() {
415        let text = r#"{"height":"5887045","scoreHigh":"39","scoreLow":"10957368298990008967","latestFinalizedBlock":{"finalizationEpoch":4090,"finalizationPoint":14,"height":"5887020","hash":"AB"}}"#;
416        let info: ChainInfoJson = serde_json::from_str(text).unwrap();
417        let score = (39u128 << 64) | 10957368298990008967;
418        assert_eq!(
419            info,
420            ChainInfoJson::new(5887045, score, 4090, 14, 5887020, "AB".to_owned())
421        );
422        assert_eq!(serde_json::to_string(&info).unwrap(), text);
423    }
424
425    #[test]
426    fn summarizes_fee_multipliers() {
427        let fees = TransactionFeesJson::new(vec![100, 0, 30, 10], 10);
428        assert_eq!(
429            serde_json::to_string(&fees).unwrap(),
430            r#"{"averageFeeMultiplier":35,"medianFeeMultiplier":20,"highestFeeMultiplier":100,"lowestFeeMultiplier":0,"minFeeMultiplier":10}"#
431        );
432        assert_eq!(
433            TransactionFeesJson::new(vec![5, 1, 3], 0).median_fee_multiplier,
434            3
435        );
436        assert_eq!(
437            TransactionFeesJson::new(Vec::new(), 7).median_fee_multiplier,
438            0
439        );
440    }
441
442    #[test]
443    fn delegations_use_camel_case() {
444        let delegation = DelegationJson {
445            main_public_key: None,
446            remote_public_key: "AA".to_owned(),
447            height: Some("7".to_owned()),
448            state: DelegationStateJson::Rejected,
449            reason: Some("わけ".to_owned()),
450        };
451        assert_eq!(
452            serde_json::to_string(&delegation).unwrap(),
453            r#"{"mainPublicKey":null,"remotePublicKey":"AA","height":"7","state":"rejected","reason":"わけ"}"#
454        );
455        let unlocked = UnlockedAccountJson {
456            unlocked_account: vec!["AA".to_owned()],
457        };
458        assert_eq!(
459            serde_json::to_string(&unlocked).unwrap(),
460            r#"{"unlockedAccount":["AA"]}"#
461        );
462    }
463}