heika_block/finalization/
message.rs1use alloc::borrow::ToOwned;
14use alloc::vec::Vec;
15
16use heika_core::hash::Hash256;
17use heika_core::key::PublicKey;
18use heika_core::signature::Signature;
19use sha3::{Digest, Sha3_256};
20
21use super::FinalizationRound;
22use super::proof::ProofError;
23
24pub const SIGNATURE_SIZE: usize = 2 * (32 + 64);
26pub(super) const MESSAGE_HEADER_SIZE: usize = 4 + 4 + SIGNATURE_SIZE;
28const SIGNED_HEADER_SIZE: usize = 4 + 4 + 4 + 4 + 8;
30
31#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct FinalizationMessage {
34 pub round: FinalizationRound,
35 pub is_prevote: bool,
36 pub height: u64,
38 pub hashes: Vec<Hash256>,
40 pub(super) signature: [u8; SIGNATURE_SIZE],
41}
42
43impl FinalizationMessage {
44 pub fn from_bytes(bytes: &[u8]) -> Result<Self, ProofError> {
47 let malformed = |what: &str| ProofError::Malformed(what.to_owned());
48 if bytes.len() < MESSAGE_HEADER_SIZE + SIGNED_HEADER_SIZE {
49 return Err(malformed("メッセージの長さ"));
50 }
51 let size = u32_at(bytes, 0) as usize;
52 let version = u32_at(bytes, MESSAGE_HEADER_SIZE);
53 let hashes_count = u32_at(bytes, MESSAGE_HEADER_SIZE + 4) as usize;
54 if size != bytes.len()
55 || size != MESSAGE_HEADER_SIZE + SIGNED_HEADER_SIZE + hashes_count * 32
56 {
57 return Err(malformed("メッセージの大きさ"));
58 }
59 if u32_at(bytes, 4) != 0 {
60 return Err(malformed("メッセージの予約"));
61 }
62 if version != 1 {
63 return Err(malformed("メッセージの版"));
64 }
65 let point_stage = u32_at(bytes, MESSAGE_HEADER_SIZE + 12);
66 let hashes_at = MESSAGE_HEADER_SIZE + SIGNED_HEADER_SIZE;
67 Ok(Self {
68 round: FinalizationRound {
69 epoch: u32_at(bytes, MESSAGE_HEADER_SIZE + 8),
70 point: point_stage >> 1,
71 },
72 is_prevote: point_stage & 1 == 0,
73 height: u64::from_le_bytes(
74 bytes[MESSAGE_HEADER_SIZE + 16..hashes_at]
75 .try_into()
76 .expect("8 bytes"),
77 ),
78 hashes: bytes[hashes_at..]
79 .as_chunks::<32>()
80 .0
81 .iter()
82 .map(|hash| Hash256(*hash))
83 .collect(),
84 signature: bytes[8..MESSAGE_HEADER_SIZE].try_into().expect("signature"),
85 })
86 }
87
88 pub fn sign(
91 round: FinalizationRound,
92 is_prevote: bool,
93 height: u64,
94 hashes: Vec<Hash256>,
95 sign: impl FnOnce(&[u8]) -> Option<[u8; SIGNATURE_SIZE]>,
96 ) -> Option<Self> {
97 let mut message = Self {
98 round,
99 is_prevote,
100 height,
101 hashes,
102 signature: [0; SIGNATURE_SIZE],
103 };
104 message.signature = sign(&message.signed_part())?;
105 Some(message)
106 }
107
108 pub fn to_bytes(&self) -> Vec<u8> {
110 let signed = self.signed_part();
111 let mut out = Vec::with_capacity(MESSAGE_HEADER_SIZE + signed.len());
112 out.extend_from_slice(&((MESSAGE_HEADER_SIZE + signed.len()) as u32).to_le_bytes());
113 out.extend_from_slice(&0u32.to_le_bytes());
114 out.extend_from_slice(&self.signature);
115 out.extend_from_slice(&signed);
116 out
117 }
118
119 pub fn size(&self) -> usize {
121 MESSAGE_HEADER_SIZE + SIGNED_HEADER_SIZE + self.hashes.len() * 32
122 }
123
124 pub fn root_key(&self) -> [u8; 32] {
126 self.signature[..32].try_into().expect("32 bytes")
127 }
128
129 pub fn last_height(&self) -> u64 {
131 self.height + (self.hashes.len() as u64).saturating_sub(1)
132 }
133
134 pub fn hash(&self) -> [u8; 32] {
136 Sha3_256::digest(self.to_bytes()).into()
137 }
138
139 pub fn short_hash(&self) -> u32 {
141 u32::from_le_bytes(self.hash()[..4].try_into().expect("4 bytes"))
142 }
143
144 pub fn verify_signature(&self) -> bool {
146 let root_key = PublicKey(self.root_key());
147 let root_signature = Signature(self.signature[32..96].try_into().expect("64 bytes"));
148 let bottom_key: [u8; 32] = self.signature[96..128].try_into().expect("32 bytes");
149 let bottom_signature = Signature(self.signature[128..].try_into().expect("64 bytes"));
150 let epoch = u64::from(self.round.epoch).to_le_bytes();
151 root_key.verify(&[&bottom_key, &epoch], &root_signature)
152 && PublicKey(bottom_key).verify(&[&self.signed_part()], &bottom_signature)
153 }
154
155 pub fn signed_part(&self) -> Vec<u8> {
157 let mut out = Vec::with_capacity(SIGNED_HEADER_SIZE + self.hashes.len() * 32);
158 out.extend_from_slice(&1u32.to_le_bytes());
159 out.extend_from_slice(&(self.hashes.len() as u32).to_le_bytes());
160 out.extend_from_slice(&self.round.epoch.to_le_bytes());
161 let point_stage = (self.round.point << 1) | u32::from(!self.is_prevote);
162 out.extend_from_slice(&point_stage.to_le_bytes());
163 out.extend_from_slice(&self.height.to_le_bytes());
164 for hash in &self.hashes {
165 out.extend_from_slice(&hash.0);
166 }
167 out
168 }
169}
170
171pub(super) fn u32_at(bytes: &[u8], offset: usize) -> u32 {
172 u32::from_le_bytes(bytes[offset..offset + 4].try_into().expect("4 bytes"))
173}
174
175#[cfg(test)]
177pub(super) mod testing {
178 use heika_core::key::PrivateKey;
179
180 use super::*;
181
182 pub struct Voter {
184 root: PrivateKey,
185 bottom: PrivateKey,
186 }
187
188 impl Voter {
189 pub fn new(seed: u8) -> Self {
190 Self {
191 root: PrivateKey::from_bytes(&[seed; 32]),
192 bottom: PrivateKey::from_bytes(&[seed ^ 0x80; 32]),
193 }
194 }
195
196 pub fn key(&self) -> [u8; 32] {
197 PublicKey::from_private_key(&self.root).0
198 }
199
200 pub fn sign(&self, round: FinalizationRound, signed: &[u8]) -> [u8; SIGNATURE_SIZE] {
202 let bottom = PublicKey::from_private_key(&self.bottom).0;
203 let epoch = u64::from(round.epoch).to_le_bytes();
204 let mut out = [0; SIGNATURE_SIZE];
205 out[..32].copy_from_slice(&self.key());
206 out[32..96].copy_from_slice(&self.root.sign(&[&bottom, &epoch]).0);
207 out[96..128].copy_from_slice(&bottom);
208 out[128..].copy_from_slice(&self.bottom.sign(&[signed]).0);
209 out
210 }
211
212 pub fn message(
214 &self,
215 round: FinalizationRound,
216 is_prevote: bool,
217 height: u64,
218 hashes: Vec<Hash256>,
219 ) -> FinalizationMessage {
220 let mut message = FinalizationMessage {
221 round,
222 is_prevote,
223 height,
224 hashes,
225 signature: [0; SIGNATURE_SIZE],
226 };
227 message.signature = self.sign(round, &message.signed_part());
228 message
229 }
230 }
231
232 pub fn block_hash(height: u64, fork: u8) -> Hash256 {
234 let mut hash = [fork; 32];
235 hash[..8].copy_from_slice(&height.to_le_bytes());
236 Hash256(hash)
237 }
238
239 pub fn chain(from: u64, through: u64) -> Vec<Hash256> {
241 (from..=through).map(|at| block_hash(at, 0)).collect()
242 }
243}
244
245#[cfg(test)]
246mod tests {
247 use super::testing::*;
248 use super::*;
249
250 const ROUND: FinalizationRound = FinalizationRound { epoch: 3, point: 2 };
251
252 #[test]
253 fn reads_writes_and_verifies_a_message() {
254 let voter = Voter::new(1);
255 let message = voter.message(ROUND, false, 10, chain(10, 12));
256 let bytes = message.to_bytes();
257 assert_eq!(bytes.len(), message.size());
258 let read = FinalizationMessage::from_bytes(&bytes).unwrap();
259 assert_eq!(read, message);
260 assert_eq!(read.round, ROUND);
261 assert!(!read.is_prevote);
262 assert_eq!((read.height, read.last_height()), (10, 12));
263 assert_eq!(read.root_key(), voter.key());
264 assert!(read.verify_signature());
265 assert_eq!(read.hash(), <[u8; 32]>::from(Sha3_256::digest(&bytes)));
266 assert_eq!(
267 read.short_hash(),
268 u32::from_le_bytes(read.hash()[..4].try_into().unwrap())
269 );
270
271 let mut changed = bytes.clone();
273 *changed.last_mut().unwrap() ^= 1;
274 assert!(
275 !FinalizationMessage::from_bytes(&changed)
276 .unwrap()
277 .verify_signature()
278 );
279 let signed = FinalizationMessage::sign(ROUND, false, 10, chain(10, 12), |signed| {
281 Some(voter.sign(ROUND, signed))
282 });
283 assert_eq!(signed.as_ref(), Some(&message));
284 assert!(FinalizationMessage::sign(ROUND, false, 10, chain(10, 12), |_| None).is_none());
285 let mut moved = message.clone();
287 moved.round.epoch += 1;
288 assert!(!moved.verify_signature());
289 }
290
291 #[test]
292 fn refuses_bad_sizes_padding_and_versions() {
293 let bytes = Voter::new(1)
294 .message(ROUND, true, 10, chain(10, 12))
295 .to_bytes();
296 assert!(FinalizationMessage::from_bytes(&bytes[..bytes.len() - 32]).is_err());
297 assert!(FinalizationMessage::from_bytes(&bytes[..100]).is_err());
298 let mut padded = bytes.clone();
299 padded[4] = 1;
300 assert!(FinalizationMessage::from_bytes(&padded).is_err());
301 let mut versioned = bytes.clone();
302 versioned[MESSAGE_HEADER_SIZE] = 2;
303 assert!(FinalizationMessage::from_bytes(&versioned).is_err());
304 }
305}