Skip to main content

heika_block/
lib.rs

1//! ブロック。catapult の `model/Block.h` と `model/Block.cpp` のレイアウトで読む。
2//!
3//! ```text
4//!   0  u32 Size  u32 Reserved  [64] Signature  [32] SignerPublicKey  u32 Reserved
5//! 108  u8 Version  u8 Network  u16 Type
6//! 112  u64 Height  u64 Timestamp  u64 Difficulty
7//! 136  VrfProof(Gamma 32、VerificationHash 16、Scalar 32)
8//! 216  PreviousBlockHash  TransactionsHash  ReceiptsHash  StateHash(各 32)
9//! 344  BeneficiaryAddress(24)  u32 FeeMultiplier
10//! 372  通常のブロックは u32 のパディング(376 まで)。
11//!      Nemesis と Importance のブロックは u32 VotingEligibleAccountsCount、
12//!      u64 HarvestingEligibleAccountsCount、u64 TotalVotingBalance、[32] PreviousImportanceBlockHash(424 まで)
13//!      この後ろにトランザクションが並ぶ
14//! ```
15//!
16//! ブロックは作らずに読むだけなので、catapult が確かめない予約の部分は確かめない。
17//!
18//! std がなくても、alloc があれば使える(`#![no_std]`)。heika-core は `default-features = false` で使う。
19
20#![cfg_attr(not(test), no_std)]
21
22extern crate alloc;
23
24pub mod finalization;
25pub mod scoring;
26pub mod statement;
27
28use alloc::vec::Vec;
29use core::fmt;
30use core::ops::Range;
31
32use heika_core::address::Address;
33use heika_core::hash::Hash256;
34use heika_core::key::PublicKey;
35use heika_core::merkle;
36use heika_core::network::{GenerationHashSeed, NetworkIdentifier};
37use heika_core::signature::Signature;
38pub use heika_core::vrf::VrfProof;
39use heika_core::vrf::{self, GenerationHash};
40use heika_transaction::{DecodeError, Transaction};
41use sha3::{Digest, Sha3_256};
42
43/// 署名とハッシュの対象から外れる先頭の部分。catapult の `VerifiableEntity::Header_Size`。
44/// サイズ、予約、署名、署名者の公開鍵、予約の順に並ぶ。
45const UNSIGNED_HEADER_SIZE: usize = 4 + 4 + 64 + 32 + 4;
46/// トランザクションのヘッダーの大きさ(catapult の `sizeof(Transaction)`)。ブロックの中のトランザクションはこれより小さくできない
47const TRANSACTION_HEADER_SIZE: usize = UNSIGNED_HEADER_SIZE + 1 + 1 + 2 + 8 + 8;
48
49/// 通常のブロックのヘッダー。末尾の4バイトは8バイト境界に合わせるためのパディング
50const NORMAL_HEADER_SIZE: usize = 376;
51/// Nemesis と Importance のブロックのヘッダー
52const IMPORTANCE_HEADER_SIZE: usize = 424;
53/// ヘッダーのうち、フッターの前まで
54const FOOTER_OFFSET: usize = 372;
55
56/// ブロックの種類。
57#[derive(Clone, Copy, PartialEq, Eq, Debug)]
58pub enum BlockType {
59    Nemesis,
60    Normal,
61    Importance,
62}
63
64impl BlockType {
65    fn from_u16(value: u16) -> Option<Self> {
66        match value {
67            0x8043 => Some(Self::Nemesis),
68            0x8143 => Some(Self::Normal),
69            0x8243 => Some(Self::Importance),
70            _ => None,
71        }
72    }
73
74    fn header_size(self) -> usize {
75        match self {
76            Self::Normal => NORMAL_HEADER_SIZE,
77            Self::Nemesis | Self::Importance => IMPORTANCE_HEADER_SIZE,
78        }
79    }
80}
81
82/// Nemesis と Importance のブロックのフッター。
83#[derive(Clone, PartialEq, Eq, Debug)]
84pub struct ImportanceFooter {
85    pub voting_eligible_accounts_count: u32,
86    pub harvesting_eligible_accounts_count: u64,
87    /// 投票に使える残高の合計。通貨のモザイクの最小単位で数える。
88    pub total_voting_balance: u64,
89    pub previous_importance_block_hash: Hash256,
90}
91
92/// ブロック。
93#[derive(Clone, PartialEq, Eq, Debug)]
94pub struct Block {
95    pub signature: Signature,
96    /// ハーベストしたアカウントの公開鍵。リモートハーベストならリモートアカウントのもの
97    pub signer_public_key: PublicKey,
98    pub version: u8,
99    pub network: NetworkIdentifier,
100    pub block_type: BlockType,
101    pub height: u64,
102    /// ネメシスのブロックからのミリ秒
103    pub timestamp: u64,
104    pub difficulty: u64,
105    pub generation_hash_proof: VrfProof,
106    pub previous_block_hash: Hash256,
107    pub transactions_hash: Hash256,
108    pub receipts_hash: Hash256,
109    pub state_hash: Hash256,
110    pub beneficiary_address: Address,
111    pub fee_multiplier: u32,
112    /// Nemesis と Importance のブロックだけにある
113    pub importance_footer: Option<ImportanceFooter>,
114    bytes: Vec<u8>,
115    transactions: Vec<Range<usize>>,
116}
117
118impl Block {
119    /// バイト列から読む。トランザクションは中身を読まずに、1件ずつの範囲だけを確かめる。
120    pub fn from_bytes(bytes: &[u8]) -> Result<Self, BlockDecodeError> {
121        let type_at = bytes.get(110..112).ok_or(BlockDecodeError::TooShort)?;
122        let raw_type = u16::from_le_bytes(type_at.try_into().expect("2 bytes"));
123        let block_type =
124            BlockType::from_u16(raw_type).ok_or(BlockDecodeError::UnknownType(raw_type))?;
125        let header_size = block_type.header_size();
126        if bytes.len() < header_size {
127            return Err(BlockDecodeError::TooShort);
128        }
129
130        // 長さは確かめたので、ここから先の切り出しは失敗しない
131        let array = |offset: usize| -> [u8; 32] {
132            bytes[offset..offset + 32].try_into().expect("32 bytes")
133        };
134        let u32_at = |offset: usize| {
135            u32::from_le_bytes(bytes[offset..offset + 4].try_into().expect("4 bytes"))
136        };
137        let u64_at = |offset: usize| {
138            u64::from_le_bytes(bytes[offset..offset + 8].try_into().expect("8 bytes"))
139        };
140
141        let size = u32_at(0);
142        if size as usize != bytes.len() {
143            return Err(BlockDecodeError::SizeMismatch {
144                stated: size,
145                actual: bytes.len(),
146            });
147        }
148        let importance_footer = (header_size == IMPORTANCE_HEADER_SIZE).then(|| ImportanceFooter {
149            voting_eligible_accounts_count: u32_at(FOOTER_OFFSET),
150            harvesting_eligible_accounts_count: u64_at(376),
151            total_voting_balance: u64_at(384),
152            previous_importance_block_hash: Hash256(array(392)),
153        });
154        Ok(Self {
155            signature: Signature(bytes[8..72].try_into().expect("64 bytes")),
156            signer_public_key: PublicKey(array(72)),
157            version: bytes[108],
158            network: NetworkIdentifier(bytes[109]),
159            block_type,
160            height: u64_at(112),
161            timestamp: u64_at(120),
162            difficulty: u64_at(128),
163            generation_hash_proof: VrfProof {
164                gamma: array(136),
165                verification_hash: bytes[168..184].try_into().expect("16 bytes"),
166                scalar: array(184),
167            },
168            previous_block_hash: Hash256(array(216)),
169            transactions_hash: Hash256(array(248)),
170            receipts_hash: Hash256(array(280)),
171            state_hash: Hash256(array(312)),
172            beneficiary_address: Address(bytes[344..368].try_into().expect("24 bytes")),
173            fee_multiplier: u32_at(368),
174            importance_footer,
175            transactions: split_transactions(bytes, header_size)?,
176            bytes: bytes.to_vec(),
177        })
178    }
179
180    /// 署名の対象。ヘッダーのうちバージョンから後ろで、通常のブロックでは末尾のパディングを除く
181    /// (catapult の `GetBlockHeaderDataBuffer`)。トランザクションは TransactionsHash を通して間接的に入る。
182    fn signed_data(&self) -> &[u8] {
183        let end = match self.block_type {
184            BlockType::Normal => FOOTER_OFFSET,
185            BlockType::Nemesis | BlockType::Importance => IMPORTANCE_HEADER_SIZE,
186        };
187        &self.bytes[UNSIGNED_HEADER_SIZE..end]
188    }
189
190    /// ハーベストしたアカウントの署名を確かめる。
191    pub fn verify_signature(&self) -> bool {
192        self.signer_public_key
193            .verify(&[self.signed_data()], &self.signature)
194    }
195
196    /// ブロックのハッシュ。catapult の `model::CalculateHash(const Block&)` と同じく、
197    /// 署名、署名者の公開鍵、署名の対象を続けた SHA3-256。トランザクションと違い generation hash seed は入らない。
198    /// 次のブロックの PreviousBlockHash がこれになる。
199    pub fn hash(&self) -> Hash256 {
200        Hash256(
201            Sha3_256::new()
202                .chain_update(self.signature.0)
203                .chain_update(self.signer_public_key.0)
204                .chain_update(self.signed_data())
205                .finalize()
206                .into(),
207        )
208    }
209
210    /// VRF の証明の gamma から、このブロックの generation hash を求める。証明は確かめない。
211    pub fn generation_hash(&self) -> GenerationHash {
212        vrf::proof_hash(&self.generation_hash_proof.gamma).generation_hash()
213    }
214
215    /// VRF の証明を確かめて、通ればこのブロックの generation hash を返す。catapult の `CheckGenerationHash` の前半。
216    ///
217    /// `vrf_public_key` は、ハーベストしたアカウントのメインアカウントにリンクされている VRF の鍵。
218    /// `alpha` は1つ前のブロックの generation hash で、Nemesis のブロックなら generation hash seed、
219    /// 鍵は署名者の公開鍵になる。
220    pub fn verify_generation_hash_proof(
221        &self,
222        vrf_public_key: &PublicKey,
223        alpha: &[u8; 32],
224    ) -> Option<GenerationHash> {
225        vrf::verify(vrf_public_key, alpha, &self.generation_hash_proof)
226            .map(|hash| hash.generation_hash())
227    }
228
229    /// 中のトランザクションのバイト列。パディングは含まない。
230    pub fn transactions(&self) -> impl Iterator<Item = &[u8]> {
231        self.transactions
232            .iter()
233            .map(|range| &self.bytes[range.clone()])
234    }
235
236    /// 中のトランザクションから TransactionsHash を求める。catapult の `CalculateBlockTransactionsHash`。
237    ///
238    /// それぞれの [`Transaction::merkle_component_hash`] を葉にした Merkle ツリーの根。
239    /// トランザクションのハッシュには generation hash seed が入るので、ブロックのネットワークのものを渡す。
240    /// 葉を求めるにはトランザクションを丸ごと読むので、読めないものがあれば、そのエラーを返す。
241    ///
242    /// Nemesis のブロックだけは求め方が違う。nemgen はトランザクションの種類ごとの決まりを使わずに
243    /// (catapult の `BlockExtensions` を `TransactionRegistry` なしで作る)、署名の範囲を種類で切らずに
244    /// ヘッダーの後半から最後までを丸ごとハッシュし、連署者も混ぜない。ノードは Nemesis をファイルから読み、
245    /// 同期してきたブロックにしか TransactionsHash を確かめないので、この違いはそのまま残っている。
246    pub fn calculate_transactions_hash(
247        &self,
248        generation_hash_seed: &GenerationHashSeed,
249    ) -> Result<Hash256, DecodeError> {
250        Ok(merkle::root(&self.merkle_leaves(generation_hash_seed)?))
251    }
252
253    /// `index` 番目(0から)のトランザクションの葉から、TransactionsHash までの Merkle の経路。
254    /// 経路と葉([`Block::merkle_leaves`]。Nemesis 以外は [`Transaction::merkle_component_hash`])があれば、ブロック全体がなくても、
255    /// そのトランザクションがこのブロックに入っていることを [`merkle::verify_path`] で確かめられる。
256    /// `index` がトランザクションの数を超えていれば `None`。
257    pub fn transaction_merkle_path(
258        &self,
259        generation_hash_seed: &GenerationHashSeed,
260        index: usize,
261    ) -> Result<Option<Vec<merkle::MerklePathNode>>, DecodeError> {
262        Ok(merkle::path(
263            &self.merkle_leaves(generation_hash_seed)?,
264            index,
265        ))
266    }
267
268    /// TransactionsHash の葉を、ブロックの中の順に並べたもの。
269    ///
270    /// ふつうは [`Transaction::merkle_component_hash`] で、REST の `meta.merkleComponentHash` と同じ。
271    /// Nemesis だけは求め方が違い([`Block::calculate_transactions_hash`])、アグリゲートの葉が REST の値と合わない。
272    pub fn merkle_leaves(
273        &self,
274        generation_hash_seed: &GenerationHashSeed,
275    ) -> Result<Vec<Hash256>, DecodeError> {
276        if self.block_type == BlockType::Nemesis {
277            return Ok(self
278                .transactions()
279                .map(|bytes| whole_transaction_hash(bytes, generation_hash_seed))
280                .collect());
281        }
282        self.transactions()
283            .map(|bytes| {
284                Transaction::from_bytes(bytes)
285                    .map(|transaction| transaction.merkle_component_hash(generation_hash_seed))
286            })
287            .collect()
288    }
289
290    /// ヘッダーの TransactionsHash が、中のトランザクションと合うか。
291    /// ブロックの署名は TransactionsHash に掛かるので、署名と合わせて確かめれば、中のトランザクションもブロックの署名者が認めたものになる。
292    pub fn verify_transactions_hash(
293        &self,
294        generation_hash_seed: &GenerationHashSeed,
295    ) -> Result<bool, DecodeError> {
296        Ok(self.calculate_transactions_hash(generation_hash_seed)? == self.transactions_hash)
297    }
298
299    /// ヘッダーの ReceiptsHash が、ステートメントから求めた Merkle の根と合うか。
300    /// ステートメントはブロックに入っておらず、ブロックを実行して求めるもの。受け取ったり読み込んだりしたステートメントが、
301    /// ヘッダーと合っているかを確かめる。
302    pub fn verify_receipts_hash(&self, statement: &statement::BlockStatement) -> bool {
303        statement.merkle_hash() == self.receipts_hash
304    }
305
306    /// ブロック全体のバイト列。
307    pub fn as_bytes(&self) -> &[u8] {
308        &self.bytes
309    }
310}
311
312/// トランザクションを、種類を問わずに丸ごとハッシュする。catapult の `model::CalculateHash(const Transaction&, ...)` の
313/// 既定の対象(`TransactionDataBuffer`)で、署名、署名者の公開鍵、generation hash seed、ヘッダーの後半から最後まで。
314/// アグリゲート以外は [`Transaction::hash`] と同じになる。
315fn whole_transaction_hash(bytes: &[u8], generation_hash_seed: &GenerationHashSeed) -> Hash256 {
316    Hash256(
317        Sha3_256::new()
318            .chain_update(&bytes[8..72])
319            .chain_update(&bytes[72..UNSIGNED_HEADER_SIZE - 4])
320            .chain_update(generation_hash_seed.0)
321            .chain_update(&bytes[UNSIGNED_HEADER_SIZE..])
322            .finalize()
323            .into(),
324    )
325}
326
327/// ヘッダーの後ろに並ぶトランザクションを、1件ずつの範囲に分ける。
328///
329/// catapult の `ContiguousEntityContainer` と同じく、最後のもの以外は後ろを8バイト境界までパディングする。
330/// 1件の大きさは、トランザクションのヘッダー以上で、ブロックの中に収まっていなければならない。
331/// 最後のものの後ろにパディングがあっても、ちょうど8バイト境界で終わっていれば catapult と同じく受け付ける。
332fn split_transactions(
333    bytes: &[u8],
334    header_size: usize,
335) -> Result<Vec<Range<usize>>, BlockDecodeError> {
336    let mut transactions = Vec::new();
337    let mut offset = header_size;
338    while offset < bytes.len() {
339        let size = bytes
340            .get(offset..offset + 4)
341            .map(|size| u32::from_le_bytes(size.try_into().expect("4 bytes")) as usize)
342            .ok_or(BlockDecodeError::InvalidTransaction { offset })?;
343        let end = offset
344            .checked_add(size)
345            .filter(|&end| size >= TRANSACTION_HEADER_SIZE && end <= bytes.len())
346            .ok_or(BlockDecodeError::InvalidTransaction { offset })?;
347        transactions.push(offset..end);
348        let next = if end == bytes.len() {
349            end
350        } else {
351            end + (size.next_multiple_of(8) - size)
352        };
353        // パディングの途中で終わっている
354        if next > bytes.len() {
355            return Err(BlockDecodeError::InvalidTransaction { offset: end });
356        }
357        offset = next;
358    }
359    Ok(transactions)
360}
361
362#[derive(Debug, Clone, PartialEq, Eq)]
363pub enum BlockDecodeError {
364    /// ヘッダーの長さに足りない
365    TooShort,
366    /// 先頭のサイズが、実際の長さと合わない
367    SizeMismatch { stated: u32, actual: usize },
368    /// ブロックの種類ではない
369    UnknownType(u16),
370    /// `offset` から始まるトランザクションの大きさが、小さすぎるかブロックからはみ出している
371    InvalidTransaction { offset: usize },
372}
373
374impl fmt::Display for BlockDecodeError {
375    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376        match self {
377            Self::TooShort => f.write_str("ブロックのヘッダーの長さに足りません"),
378            Self::SizeMismatch { stated, actual } => write!(
379                f,
380                "サイズは {stated} バイトとありますが、実際は {actual} バイトでした"
381            ),
382            Self::UnknownType(block_type) => {
383                write!(f, "種類 0x{block_type:04X} はブロックではありません")
384            }
385            Self::InvalidTransaction { offset } => write!(
386                f,
387                "{offset} バイト目からのトランザクションの大きさが、小さすぎるかブロックからはみ出しています"
388            ),
389        }
390    }
391}
392
393impl core::error::Error for BlockDecodeError {}
394
395#[cfg(test)]
396mod tests {
397    use heika_core::key::PrivateKey;
398    use heika_transaction::{Aggregate, Body, EmbeddedTransaction, KeyLink, LinkAction};
399
400    use super::*;
401
402    /// 中身を問わない、大きさ `size` のトランザクションの代わり
403    fn transaction(size: usize, fill: u8) -> Vec<u8> {
404        let mut transaction = vec![fill; size];
405        transaction[..4].copy_from_slice(&(size as u32).to_le_bytes());
406        transaction
407    }
408
409    /// `header_size` のヘッダーに `transactions` を並べ、`private_key` で署名したブロック。
410    fn block(block_type: u16, transactions: &[Vec<u8>], private_key: &PrivateKey) -> Vec<u8> {
411        let header_size = BlockType::from_u16(block_type).unwrap().header_size();
412        let mut bytes = vec![0; header_size];
413        for (index, transaction) in transactions.iter().enumerate() {
414            bytes.extend_from_slice(transaction);
415            if index + 1 < transactions.len() {
416                bytes.resize(bytes.len().next_multiple_of(8), 0);
417            }
418        }
419        let size = bytes.len() as u32;
420        bytes[..4].copy_from_slice(&size.to_le_bytes());
421        bytes[72..104].copy_from_slice(&PublicKey::from_private_key(private_key).0);
422        bytes[108] = 1;
423        bytes[109] = NetworkIdentifier::MAINNET.0;
424        bytes[110..112].copy_from_slice(&block_type.to_le_bytes());
425        bytes[112..120].copy_from_slice(&720_u64.to_le_bytes());
426        bytes[344] = 0x68;
427        let signed_end = if header_size == NORMAL_HEADER_SIZE {
428            FOOTER_OFFSET
429        } else {
430            header_size
431        };
432        let signature = private_key.sign(&[&bytes[UNSIGNED_HEADER_SIZE..signed_end]]);
433        bytes[8..72].copy_from_slice(&signature.0);
434        bytes
435    }
436
437    fn private_key() -> PrivateKey {
438        PrivateKey::from_bytes(&[7; 32])
439    }
440
441    #[test]
442    fn splits_transactions_padded_except_the_last() {
443        let transactions = [
444            transaction(130, 1),
445            transaction(128, 2),
446            transaction(133, 3),
447        ];
448        let block = Block::from_bytes(&block(0x8143, &transactions, &private_key())).unwrap();
449        assert_eq!(block.block_type, BlockType::Normal);
450        assert_eq!(block.height, 720);
451        assert_eq!(block.importance_footer, None);
452        assert!(
453            block
454                .transactions()
455                .eq(transactions.iter().map(Vec::as_slice))
456        );
457        // 130 バイトのものの後ろだけ、6バイトのパディングが入る
458        assert_eq!(block.as_bytes().len(), 376 + 136 + 128 + 133);
459    }
460
461    /// 署名した VrfKeyLink と、連署のあるアグリゲート
462    fn signed_transactions(seed: &GenerationHashSeed) -> Vec<Transaction> {
463        let signer = PublicKey::from_private_key(&private_key());
464        let link = |byte| {
465            Body::VrfKeyLink(KeyLink {
466                linked_public_key: PublicKey([byte; 32]),
467                link_action: LinkAction::Link,
468            })
469        };
470        let mut single = Transaction::new(signer, NetworkIdentifier::MAINNET, 0, 0, link(1));
471        single.sign(&private_key(), seed).unwrap();
472        let aggregate = Aggregate::new(vec![EmbeddedTransaction::new(
473            signer,
474            NetworkIdentifier::MAINNET,
475            link(2),
476        )])
477        .unwrap();
478        let mut aggregate = Transaction::new(
479            signer,
480            NetworkIdentifier::MAINNET,
481            0,
482            0,
483            Body::AggregateComplete(aggregate),
484        );
485        aggregate.sign(&private_key(), seed).unwrap();
486        aggregate
487            .cosign(&PrivateKey::from_bytes(&[8; 32]), seed)
488            .unwrap();
489        vec![single, aggregate]
490    }
491
492    #[test]
493    fn compares_the_receipts_hash_with_the_statement() {
494        use statement::{
495            BlockStatement, Mosaic, Receipt, ReceiptBody, ReceiptSource, TransactionStatement,
496        };
497
498        let statement = BlockStatement {
499            transaction_statements: vec![TransactionStatement {
500                source: ReceiptSource {
501                    primary_id: 0,
502                    secondary_id: 0,
503                },
504                receipts: vec![Receipt {
505                    version: 1,
506                    body: ReceiptBody::Inflation(Mosaic {
507                        mosaic_id: heika_transaction::MosaicId(1),
508                        amount: 2,
509                    }),
510                }],
511            }],
512            ..BlockStatement::default()
513        };
514        let mut bytes = block(0x8143, &[], &private_key());
515        bytes[280..312].copy_from_slice(&statement.merkle_hash().0);
516        let block = Block::from_bytes(&bytes).unwrap();
517        assert!(block.verify_receipts_hash(&statement));
518        assert!(!block.verify_receipts_hash(&BlockStatement::default()));
519    }
520
521    #[test]
522    fn verifies_the_generation_hash_proof_with_the_vrf_key() {
523        let vrf_private_key = PrivateKey::from_bytes(&[9; 32]);
524        let vrf_public_key = PublicKey::from_private_key(&vrf_private_key);
525        let parent = [0x5A; 32];
526        let proof = vrf::prove(&vrf_private_key, &parent).unwrap();
527        let mut bytes = block(0x8143, &[], &private_key());
528        bytes[136..168].copy_from_slice(&proof.gamma);
529        bytes[168..184].copy_from_slice(&proof.verification_hash);
530        bytes[184..216].copy_from_slice(&proof.scalar);
531        let block = Block::from_bytes(&bytes).unwrap();
532        assert_eq!(block.generation_hash_proof, proof);
533        let expected = vrf::verify(&vrf_public_key, &parent, &proof)
534            .unwrap()
535            .generation_hash();
536        assert_eq!(block.generation_hash(), expected);
537        assert_eq!(
538            block.verify_generation_hash_proof(&vrf_public_key, &parent),
539            Some(expected)
540        );
541        // ブロックの署名者の鍵や、別の親では通らない
542        assert_eq!(
543            block.verify_generation_hash_proof(&block.signer_public_key, &parent),
544            None
545        );
546        assert_eq!(
547            block.verify_generation_hash_proof(&vrf_public_key, &[0xA5; 32]),
548            None
549        );
550    }
551
552    #[test]
553    fn proves_that_each_transaction_is_in_the_block() {
554        let seed = GenerationHashSeed::MAINNET;
555        let transactions = signed_transactions(&seed);
556        let bytes: Vec<_> = transactions.iter().map(Transaction::to_bytes).collect();
557        let mut block_bytes = block(0x8143, &bytes, &private_key());
558        let leaves: Vec<_> = transactions
559            .iter()
560            .map(|transaction| transaction.merkle_component_hash(&seed))
561            .collect();
562        block_bytes[248..280].copy_from_slice(&merkle::root(&leaves).0);
563        let block = Block::from_bytes(&block_bytes).unwrap();
564        for (index, leaf) in leaves.iter().enumerate() {
565            let path = block
566                .transaction_merkle_path(&seed, index)
567                .unwrap()
568                .unwrap();
569            assert!(merkle::verify_path(leaf, &path, &block.transactions_hash));
570        }
571        assert_eq!(block.transaction_merkle_path(&seed, leaves.len()), Ok(None));
572    }
573
574    #[test]
575    fn calculates_the_transactions_hash_from_merkle_component_hashes() {
576        let seed = GenerationHashSeed::MAINNET;
577        let transactions = signed_transactions(&seed);
578        let bytes: Vec<_> = transactions.iter().map(Transaction::to_bytes).collect();
579        let mut block_bytes = block(0x8143, &bytes, &private_key());
580        let leaves: Vec<_> = transactions
581            .iter()
582            .map(|transaction| transaction.merkle_component_hash(&seed))
583            .collect();
584        // 連署のあるアグリゲートの葉は、ハッシュそのものではない
585        assert_ne!(leaves[1], transactions[1].hash(&seed));
586        let expected = merkle::root(&leaves);
587        block_bytes[248..280].copy_from_slice(&expected.0);
588
589        let block = Block::from_bytes(&block_bytes).unwrap();
590        assert_eq!(block.calculate_transactions_hash(&seed), Ok(expected));
591        assert_eq!(block.verify_transactions_hash(&seed), Ok(true));
592        assert_eq!(
593            block.verify_transactions_hash(&GenerationHashSeed::TESTNET),
594            Ok(false)
595        );
596
597        let empty = Block::from_bytes(&self::block(0x8143, &[], &private_key())).unwrap();
598        assert_eq!(empty.verify_transactions_hash(&seed), Ok(true));
599
600        let unknown =
601            Block::from_bytes(&self::block(0x8143, &[transaction(128, 0)], &private_key()))
602                .unwrap();
603        assert!(unknown.calculate_transactions_hash(&seed).is_err());
604    }
605
606    #[test]
607    fn hashes_nemesis_transactions_whole() {
608        let seed = GenerationHashSeed::MAINNET;
609        let transactions = signed_transactions(&seed);
610        let bytes: Vec<_> = transactions.iter().map(Transaction::to_bytes).collect();
611        let leaves: Vec<_> = bytes
612            .iter()
613            .map(|bytes| whole_transaction_hash(bytes, &seed))
614            .collect();
615        // アグリゲート以外は、ふつうのハッシュと同じ
616        assert_eq!(leaves[0], transactions[0].hash(&seed));
617        // アグリゲートは、中のトランザクションと連署まで丸ごと入る
618        assert_ne!(leaves[1], transactions[1].hash(&seed));
619        assert_ne!(leaves[1], transactions[1].merkle_component_hash(&seed));
620
621        let mut block_bytes = block(0x8043, &bytes, &private_key());
622        block_bytes[248..280].copy_from_slice(&merkle::root(&leaves).0);
623        let nemesis = Block::from_bytes(&block_bytes).unwrap();
624        assert_eq!(nemesis.verify_transactions_hash(&seed), Ok(true));
625        // 経路も、丸ごとハッシュした葉からつながる
626        assert_eq!(nemesis.merkle_leaves(&seed), Ok(leaves.clone()));
627        let path = nemesis.transaction_merkle_path(&seed, 1).unwrap().unwrap();
628        assert!(merkle::verify_path(
629            &leaves[1],
630            &path,
631            &nemesis.transactions_hash
632        ));
633    }
634
635    #[test]
636    fn verifies_the_signature_and_hashes_like_catapult() {
637        let bytes = block(0x8143, &[transaction(128, 1)], &private_key());
638        let block = Block::from_bytes(&bytes).unwrap();
639        assert!(block.verify_signature());
640        let expected: [u8; 32] = Sha3_256::new()
641            .chain_update(&bytes[8..104])
642            .chain_update(&bytes[108..372])
643            .finalize()
644            .into();
645        assert_eq!(block.hash(), Hash256(expected));
646
647        // 署名の対象はトランザクションを含まず、パディングも含まない
648        let mut changed = bytes.clone();
649        changed[372] = 0xFF;
650        changed[400] ^= 1;
651        let changed = Block::from_bytes(&changed).unwrap();
652        assert!(changed.verify_signature());
653        assert_eq!(changed.hash(), block.hash());
654
655        let mut tampered = bytes;
656        tampered[112] ^= 1;
657        assert!(!Block::from_bytes(&tampered).unwrap().verify_signature());
658    }
659
660    #[test]
661    fn reads_the_importance_footer_and_signs_it() {
662        let mut bytes = block(0x8243, &[], &private_key());
663        let block = Block::from_bytes(&bytes).unwrap();
664        assert_eq!(block.block_type, BlockType::Importance);
665        assert_eq!(block.transactions().count(), 0);
666        assert!(block.verify_signature());
667        assert_eq!(
668            block
669                .importance_footer
670                .as_ref()
671                .unwrap()
672                .voting_eligible_accounts_count,
673            0
674        );
675        // フッターは署名の対象に入る
676        bytes[FOOTER_OFFSET] = 1;
677        let block = Block::from_bytes(&bytes).unwrap();
678        assert_eq!(
679            block
680                .importance_footer
681                .as_ref()
682                .unwrap()
683                .voting_eligible_accounts_count,
684            1
685        );
686        assert!(!block.verify_signature());
687    }
688
689    #[test]
690    fn rejects_broken_blocks() {
691        let bytes = block(
692            0x8143,
693            &[transaction(130, 1), transaction(128, 2)],
694            &private_key(),
695        );
696        assert_eq!(
697            Block::from_bytes(&bytes[..300]),
698            Err(BlockDecodeError::TooShort)
699        );
700        assert_eq!(
701            Block::from_bytes(&bytes[..bytes.len() - 1]),
702            Err(BlockDecodeError::SizeMismatch {
703                stated: bytes.len() as u32,
704                actual: bytes.len() - 1
705            })
706        );
707
708        let mut unknown = bytes.clone();
709        unknown[110..112].copy_from_slice(&0x4154_u16.to_le_bytes());
710        assert_eq!(
711            Block::from_bytes(&unknown),
712            Err(BlockDecodeError::UnknownType(0x4154))
713        );
714
715        // 大きさがトランザクションのヘッダーより小さい
716        let mut small = bytes.clone();
717        small[376..380].copy_from_slice(&127_u32.to_le_bytes());
718        assert_eq!(
719            Block::from_bytes(&small),
720            Err(BlockDecodeError::InvalidTransaction { offset: 376 })
721        );
722
723        // 2件目がブロックからはみ出す
724        let mut overflowing = bytes;
725        overflowing[512..516].copy_from_slice(&129_u32.to_le_bytes());
726        assert_eq!(
727            Block::from_bytes(&overflowing),
728            Err(BlockDecodeError::InvalidTransaction { offset: 512 })
729        );
730    }
731
732    #[test]
733    fn handles_padding_after_the_last_transaction_like_catapult() {
734        let padded = |padding: usize| {
735            let mut bytes = block(0x8143, &[transaction(130, 1)], &private_key());
736            bytes.resize(bytes.len() + padding, 0);
737            let size = bytes.len() as u32;
738            bytes[..4].copy_from_slice(&size.to_le_bytes());
739            Block::from_bytes(&bytes)
740        };
741        // 8バイト境界まで埋まっていれば、パディングを飛ばした先がちょうど終わりになるので受け付ける
742        assert_eq!(padded(6).unwrap().transactions().count(), 1);
743        // 途中で終わっていれば、飛ばした先が終わりを越えるので弾く
744        assert_eq!(
745            padded(3),
746            Err(BlockDecodeError::InvalidTransaction { offset: 506 })
747        );
748        // 8バイト境界を越えて残っていれば、次のトランザクションとして読んで、小さすぎるので弾く
749        assert_eq!(
750            padded(10),
751            Err(BlockDecodeError::InvalidTransaction { offset: 512 })
752        );
753    }
754}