Skip to main content

heika_rest/
finalization.rs

1//! ファイナライズの証明。`/finalization/proof/epoch/{epoch}` と `/finalization/proof/height/{height}` が返す
2//! `FinalizationProofDTO`。
3//!
4//! catapult の REST は、ノードから受け取ったバイナリの証明を、並びを変えずに項目に分けて返す。なので、項目を同じ順に
5//! 並べ直せば、ノードが返すものと同じバイト列に戻る。ここでは並べ直すだけで、投票の署名と重みは確かめない。
6//! 確かめるのは、そのエポックの投票者を知っている側(heika-block の `verify_proof`)。
7
8use serde::{Deserialize, Serialize};
9
10use crate::{RestError, hex, hex_array, number};
11
12/// `FinalizationProofDTO`。
13#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
14#[serde(rename_all = "camelCase")]
15pub struct FinalizationProof {
16    pub version: u32,
17    pub finalization_epoch: u32,
18    pub finalization_point: u32,
19    pub height: String,
20    pub hash: String,
21    pub message_groups: Vec<MessageGroup>,
22}
23
24/// `MessageGroup`。同じ段階、高さ、ハッシュに投じた票の署名をまとめたもの
25#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
26#[serde(rename_all = "camelCase")]
27pub struct MessageGroup {
28    pub stage: u32,
29    pub height: String,
30    pub hashes: Vec<String>,
31    pub signatures: Vec<BmTreeSignature>,
32}
33
34/// `BmTreeSignature`。2段の鍵の木の署名
35#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
36pub struct BmTreeSignature {
37    pub root: ParentPublicKeySignaturePair,
38    pub bottom: ParentPublicKeySignaturePair,
39}
40
41#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
42#[serde(rename_all = "camelCase")]
43pub struct ParentPublicKeySignaturePair {
44    pub parent_public_key: String,
45    pub signature: String,
46}
47
48impl FinalizationProof {
49    /// ノードが返すものと同じバイナリの証明に戻す
50    pub fn to_bytes(&self) -> Result<Vec<u8>, RestError> {
51        let mut body = Vec::new();
52        for group in &self.message_groups {
53            let start = body.len();
54            body.extend_from_slice(&[0; 4]);
55            body.extend_from_slice(&(group.hashes.len() as u32).to_le_bytes());
56            body.extend_from_slice(&(group.signatures.len() as u32).to_le_bytes());
57            body.extend_from_slice(&group.stage.to_le_bytes());
58            body.extend_from_slice(&number(&group.height, "messageGroups.height")?.to_le_bytes());
59            for hash in &group.hashes {
60                body.extend_from_slice(&hex_array::<32>(hash, "messageGroups.hashes")?);
61            }
62            for signature in &group.signatures {
63                for pair in [&signature.root, &signature.bottom] {
64                    body.extend_from_slice(&hex_array::<32>(
65                        &pair.parent_public_key,
66                        "messageGroups.signatures.parentPublicKey",
67                    )?);
68                    body.extend_from_slice(&hex_array::<64>(
69                        &pair.signature,
70                        "messageGroups.signatures.signature",
71                    )?);
72                }
73            }
74            let size = (body.len() - start) as u32;
75            body[start..start + 4].copy_from_slice(&size.to_le_bytes());
76        }
77        let size = 8 + 4 + 4 + 8 + 32 + body.len();
78        let mut proof = Vec::with_capacity(size);
79        proof.extend_from_slice(&(size as u32).to_le_bytes());
80        proof.extend_from_slice(&self.version.to_le_bytes());
81        proof.extend_from_slice(&self.finalization_epoch.to_le_bytes());
82        proof.extend_from_slice(&self.finalization_point.to_le_bytes());
83        proof.extend_from_slice(&number(&self.height, "height")?.to_le_bytes());
84        proof.extend_from_slice(&hex_array::<32>(&self.hash, "hash")?);
85        proof.extend_from_slice(&body);
86        Ok(proof)
87    }
88
89    /// ノードが持つバイナリの証明を、REST の形にする([`to_bytes`](Self::to_bytes) の逆)。
90    /// 長さが合わなければ `None`。署名と重みは確かめない
91    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
92        let mut reader = Reader(bytes);
93        let size = reader.u32()? as usize;
94        if size != bytes.len() {
95            return None;
96        }
97        let version = reader.u32()?;
98        let finalization_epoch = reader.u32()?;
99        let finalization_point = reader.u32()?;
100        let height = reader.u64()?.to_string();
101        let hash = hex(reader.take(32)?);
102        let mut message_groups = Vec::new();
103        while !reader.0.is_empty() {
104            let size = reader.u32()? as usize;
105            let mut group = Reader(reader.take(size.checked_sub(4)?)?);
106            let hashes = group.u32()?;
107            let signatures = group.u32()?;
108            let stage = group.u32()?;
109            let height = group.u64()?.to_string();
110            let hashes = (0..hashes)
111                .map(|_| group.take(32).map(hex))
112                .collect::<Option<_>>()?;
113            let mut pair = || {
114                Some(ParentPublicKeySignaturePair {
115                    parent_public_key: hex(group.take(32)?),
116                    signature: hex(group.take(64)?),
117                })
118            };
119            let signatures = (0..signatures)
120                .map(|_| {
121                    Some(BmTreeSignature {
122                        root: pair()?,
123                        bottom: pair()?,
124                    })
125                })
126                .collect::<Option<_>>()?;
127            if !group.0.is_empty() {
128                return None;
129            }
130            message_groups.push(MessageGroup {
131                stage,
132                height,
133                hashes,
134                signatures,
135            });
136        }
137        Some(Self {
138            version,
139            finalization_epoch,
140            finalization_point,
141            height,
142            hash,
143            message_groups,
144        })
145    }
146}
147
148/// 頭から順に読む
149struct Reader<'a>(&'a [u8]);
150
151impl<'a> Reader<'a> {
152    fn take(&mut self, size: usize) -> Option<&'a [u8]> {
153        let (head, rest) = self.0.split_at_checked(size)?;
154        self.0 = rest;
155        Some(head)
156    }
157
158    fn u32(&mut self) -> Option<u32> {
159        Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
160    }
161
162    fn u64(&mut self) -> Option<u64> {
163        Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?))
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use heika_block::finalization::proof::proof_header;
170    use serde_json::json;
171
172    use super::*;
173
174    #[test]
175    fn rebuilds_the_binary_proof() {
176        let hex = |byte: u8, len: usize| format!("{byte:02X}").repeat(len);
177        let pair = || json!({ "parentPublicKey": hex(0x11, 32), "signature": hex(0x22, 64) });
178        let proof: FinalizationProof = serde_json::from_value(json!({
179            "version": 1,
180            "finalizationEpoch": 7,
181            "finalizationPoint": 3,
182            "height": "8640",
183            "hash": hex(0xAB, 32),
184            "messageGroups": [{
185                "stage": 1,
186                "height": "8640",
187                "hashes": [hex(0xAB, 32)],
188                "signatures": [{ "root": pair(), "bottom": pair() }],
189            }],
190        }))
191        .unwrap();
192        let bytes = proof.to_bytes().unwrap();
193        // 見出し 56、組の見出し 24、ハッシュ 32、署名 192
194        assert_eq!(bytes.len(), 56 + 24 + 32 + 192);
195        let header = proof_header(&bytes).unwrap();
196        assert_eq!((header.round.epoch, header.round.point), (7, 3));
197        assert_eq!(header.height, 8640);
198        assert_eq!(header.hash.0, [0xAB; 32]);
199        let group = &bytes[56..];
200        assert_eq!(
201            u32::from_le_bytes(group[..4].try_into().unwrap()),
202            24 + 32 + 192
203        );
204        assert_eq!(&group[8..12], &1u32.to_le_bytes());
205        assert_eq!(&group[56..88], &[0x11; 32]);
206        assert_eq!(&group[88..152], &[0x22; 64]);
207        // バイナリから戻すと、同じ JSON になる
208        assert_eq!(FinalizationProof::from_bytes(&bytes), Some(proof));
209        assert_eq!(
210            FinalizationProof::from_bytes(&bytes[..bytes.len() - 1]),
211            None
212        );
213    }
214}