Skip to main content

heika_transaction/
lib.rs

1//! Symbol のトランザクション。catbuffer の `schemas/symbol` のレイアウトで読み書きし、
2//! catapult と同じ範囲に署名して、同じ方法でハッシュを取る。
3//!
4//! std がなくても、alloc があれば使える(`#![no_std]`)。heika-core は `default-features = false` で使う。
5
6#![cfg_attr(not(test), no_std)]
7
8extern crate alloc;
9
10use alloc::vec::Vec;
11use core::fmt;
12
13use heika_core::hash::Hash256;
14use heika_core::key::{PrivateKey, PublicKey};
15use heika_core::network::{GenerationHashSeed, NetworkIdentifier};
16use heika_core::signature::Signature;
17use sha3::{Digest, Sha3_256};
18
19mod aggregate;
20mod bounded;
21mod lock;
22mod metadata;
23mod mosaic;
24mod multisig;
25mod namespace;
26mod restriction;
27mod scan;
28mod transfer;
29mod validate;
30
31pub use aggregate::{
32    Aggregate, AggregateVersion, Cosignature, DetachedCosignature, EmbeddedTransaction,
33    NestedAggregate, TransactionsHashCalculation,
34};
35pub use bounded::{BoundedVec, TooLong};
36pub use lock::{HashLock, LockHashAlgorithm, SecretLock, SecretProof, secret_lock_key};
37pub use metadata::{
38    Metadata, MetadataKey, MetadataType, MosaicMetadata, NamespaceMetadata, metadata_value_update,
39    scoped_metadata_key,
40};
41pub use mosaic::{
42    MosaicDefinition, MosaicFlags, MosaicId, MosaicSupplyChange, MosaicSupplyChangeAction,
43    MosaicSupplyRevocation, UnresolvedMosaic,
44};
45pub use multisig::MultisigAccountModification;
46pub use namespace::{
47    AddressAlias, AliasAction, InvalidNamespaceName, MosaicAlias, NamespaceId,
48    NamespaceRegistration, NamespaceRegistrationType, is_valid_namespace_name,
49};
50pub use restriction::{
51    AccountRestriction, AccountRestrictionFlags, MosaicAddressRestriction, MosaicGlobalRestriction,
52    MosaicRestrictionType, TransactionType, mosaic_restriction_entry_key, mosaic_restriction_key,
53};
54pub use scan::{ScanError, Scanned, scan};
55pub use transfer::{Transfer, TransferError, UnresolvedAddress, UnresolvedMosaicId};
56pub use validate::{Failure, Location, Problem};
57
58/// 署名とハッシュの対象から外れる先頭の部分。catapult の `VerifiableEntity::Header_Size`。
59/// サイズ、予約、署名、署名者の公開鍵、予約の順に並ぶ。
60const UNSIGNED_HEADER_SIZE: usize = 4 + 4 + 64 + 32 + 4;
61
62/// 署名の対象になるヘッダーの部分。バージョン、ネットワーク、種類、手数料、期限。
63const SIGNED_HEADER_SIZE: usize = 1 + 1 + 2 + 8 + 8;
64
65const HEADER_SIZE: usize = UNSIGNED_HEADER_SIZE + SIGNED_HEADER_SIZE;
66
67/// トランザクション。catbuffer の `Transaction` に、種類ごとの本体が続く。
68#[derive(Clone, PartialEq, Eq, Debug)]
69pub struct Transaction {
70    /// 署名者の署名。署名する前は、catapult の SDK と同じく0で埋めておく。
71    pub signature: Signature,
72    pub signer_public_key: PublicKey,
73    pub network: NetworkIdentifier,
74    /// 手数料。通貨のモザイクの最小単位で数える。
75    pub fee: u64,
76    /// 期限。ネットワークのエポックからのミリ秒。
77    pub deadline: u64,
78    pub body: Body,
79    /// ヘッダーの2つの予約の部分。catapult は確かめず、署名にもハッシュにも入らないので、0 でなくてもブロックに
80    /// 入りうる。書き戻して同じバイト列になるように、読んだ値を持っておく
81    reserved: [u32; 2],
82}
83
84/// 種類ごとの本体。catbuffer の `schemas/symbol` にある25種類。
85#[derive(Clone, PartialEq, Eq, Debug)]
86pub enum Body {
87    /// 重要度を預けるリモートアカウントの公開鍵を紐づける。リモートハーベストと委任ハーベストに使う。
88    AccountKeyLink(KeyLink),
89    /// TLS の接続に使うノードの公開鍵を紐づける。委任ハーベストに使う。
90    NodeKeyLink(KeyLink),
91    /// ファイナライズの投票に使う公開鍵を、エポックの範囲を決めて紐づける。
92    VotingKeyLink(VotingKeyLink),
93    /// ハーベストで使う VRF の公開鍵を紐づける。
94    VrfKeyLink(KeyLink),
95    HashLock(HashLock),
96    SecretLock(SecretLock),
97    SecretProof(SecretProof),
98    AccountMetadata(Metadata),
99    MosaicMetadata(MosaicMetadata),
100    NamespaceMetadata(NamespaceMetadata),
101    MosaicDefinition(MosaicDefinition),
102    MosaicSupplyChange(MosaicSupplyChange),
103    MosaicSupplyRevocation(MosaicSupplyRevocation),
104    MultisigAccountModification(MultisigAccountModification),
105    AddressAlias(AddressAlias),
106    MosaicAlias(MosaicAlias),
107    NamespaceRegistration(NamespaceRegistration),
108    /// 送受信できる相手のアドレスを制限する。
109    AccountAddressRestriction(AccountRestriction<UnresolvedAddress>),
110    /// 受け取れるモザイクを制限する。
111    AccountMosaicRestriction(AccountRestriction<UnresolvedMosaicId>),
112    /// 送れるトランザクションの種類を制限する。
113    AccountOperationRestriction(AccountRestriction<TransactionType>),
114    MosaicAddressRestriction(MosaicAddressRestriction),
115    MosaicGlobalRestriction(MosaicGlobalRestriction),
116    /// モザイクとメッセージを送る。
117    Transfer(Transfer),
118    /// 必要な署名がそろっているアグリゲート。
119    AggregateComplete(Aggregate),
120    /// 連署を後から集めるアグリゲート。送る前に HashLock が要る。
121    AggregateBonded(Aggregate),
122}
123
124/// 公開鍵を紐づける、または紐づけを外すトランザクションに共通の本体。
125#[derive(Clone, Copy, PartialEq, Eq, Debug)]
126pub struct KeyLink {
127    pub linked_public_key: PublicKey,
128    pub link_action: LinkAction,
129}
130
131/// 投票の公開鍵を紐づける、または紐づけを外す本体。
132#[derive(Clone, Copy, PartialEq, Eq, Debug)]
133pub struct VotingKeyLink {
134    pub linked_public_key: PublicKey,
135    /// 投票に使う最初のエポック
136    pub start_epoch: u32,
137    /// 投票に使う最後のエポック
138    pub end_epoch: u32,
139    pub link_action: LinkAction,
140}
141
142#[derive(Clone, Copy, PartialEq, Eq, Debug)]
143pub enum LinkAction {
144    Unlink,
145    Link,
146}
147
148impl LinkAction {
149    fn to_byte(self) -> u8 {
150        match self {
151            Self::Unlink => 0,
152            Self::Link => 1,
153        }
154    }
155
156    fn from_byte(byte: u8) -> Result<Self, DecodeError> {
157        match byte {
158            0 => Ok(Self::Unlink),
159            1 => Ok(Self::Link),
160            action => Err(DecodeError::InvalidLinkAction(action)),
161        }
162    }
163}
164
165impl Transaction {
166    /// 署名していないトランザクションを作る。署名は0で埋める。
167    pub fn new(
168        signer_public_key: PublicKey,
169        network: NetworkIdentifier,
170        fee: u64,
171        deadline: u64,
172        body: Body,
173    ) -> Self {
174        Self {
175            signature: Signature([0; 64]),
176            signer_public_key,
177            network,
178            fee,
179            deadline,
180            body,
181            reserved: [0; 2],
182        }
183    }
184
185    /// バイト数。アグリゲートなら、今付いている連署も数える。
186    pub fn size(&self) -> usize {
187        self.to_bytes().len()
188    }
189
190    /// 手数料の倍率 `fee_multiplier` で、ブロックに入れてもらうのに要る手数料。
191    /// catapult の `CalculateTransactionFee` と同じく、バイト数に倍率を掛けたもの。
192    ///
193    /// アグリゲートにこれから連署が付くなら、その数を `cosignature_count` に渡す。連署1つで104バイト増え、
194    /// ノードは連署の付いたあとのバイト数で手数料を確かめる。公式の SDK の `calculate_transaction_fee` と同じ。
195    pub fn fee_for(&self, fee_multiplier: u32, cosignature_count: usize) -> u64 {
196        let size =
197            self.size() as u64 + aggregate::COSIGNATURE_SIZE as u64 * cosignature_count as u64;
198        size.saturating_mul(fee_multiplier.into())
199    }
200
201    /// 手数料から、ブロックに入れてもらえる倍率の上限を求める。catapult の `CalculateTransactionMaxFeeMultiplier`。
202    /// ハーベストする人は、ブロックの倍率がこれ以下のときだけ、このトランザクションを入れられる。
203    pub fn max_fee_multiplier(&self) -> u32 {
204        u32::try_from(self.fee / self.size() as u64).unwrap_or(u32::MAX)
205    }
206
207    pub fn to_bytes(&self) -> Vec<u8> {
208        let mut body = Vec::new();
209        self.body.encode(&mut body);
210        let size = HEADER_SIZE + body.len();
211        let mut bytes = Vec::with_capacity(size);
212        bytes.extend_from_slice(&(size as u32).to_le_bytes());
213        bytes.extend_from_slice(&self.reserved[0].to_le_bytes());
214        bytes.extend_from_slice(&self.signature.0);
215        bytes.extend_from_slice(&self.signer_public_key.0);
216        bytes.extend_from_slice(&self.reserved[1].to_le_bytes());
217        bytes.push(self.body.version());
218        bytes.push(self.network.0);
219        bytes.extend_from_slice(&self.body.transaction_type().to_le_bytes());
220        bytes.extend_from_slice(&self.fee.to_le_bytes());
221        bytes.extend_from_slice(&self.deadline.to_le_bytes());
222        bytes.extend_from_slice(&body);
223        bytes
224    }
225
226    /// バイト列から読む。書き戻したときに同じバイト列にならないものは弾く。
227    /// catapult が確かめない予約の部分は、0 でなくても読み、その値のまま書き戻す。
228    pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
229        if bytes.len() < HEADER_SIZE {
230            return Err(DecodeError::TooShort);
231        }
232        let mut reader = Reader(bytes);
233        let size = reader.u32();
234        if size as usize != bytes.len() {
235            return Err(DecodeError::SizeMismatch {
236                stated: size,
237                actual: bytes.len(),
238            });
239        }
240        let reserved_before = reader.u32();
241        let signature = Signature(reader.array());
242        let signer_public_key = PublicKey(reader.array());
243        let reserved = [reserved_before, reader.u32()];
244        let version = reader.u8();
245        let network = NetworkIdentifier(reader.u8());
246        let transaction_type = reader.u16();
247        let fee = reader.u64();
248        let deadline = reader.u64();
249        let body = Body::decode(transaction_type, version, reader.0)?;
250        Ok(Self {
251            signature,
252            signer_public_key,
253            network,
254            fee,
255            deadline,
256            body,
257            reserved,
258        })
259    }
260
261    /// 署名する。署名者の公開鍵は署名の対象に含まれるので、秘密鍵と合っていなければ弾く。
262    pub fn sign(
263        &mut self,
264        private_key: &PrivateKey,
265        generation_hash_seed: &GenerationHashSeed,
266    ) -> Result<(), SignError> {
267        if PublicKey::from_private_key(private_key) != self.signer_public_key {
268            return Err(SignError::KeyMismatch);
269        }
270        let bytes = self.to_bytes();
271        self.signature = private_key.sign(&[&generation_hash_seed.0, self.signed_part(&bytes)]);
272        Ok(())
273    }
274
275    /// 署名するバイト列。generation hash seed に、署名の対象の部分を続けたもの。公式の SDK の `extract_signing_payload`。
276    /// 秘密鍵を別の場所(ハードウェアや別のプロセス)に置いて署名するときは、これを Ed25519 で署名して
277    /// [`Transaction::attach_signature`] で付ける。
278    pub fn signing_payload(&self, generation_hash_seed: &GenerationHashSeed) -> Vec<u8> {
279        let bytes = self.to_bytes();
280        [&generation_hash_seed.0[..], self.signed_part(&bytes)].concat()
281    }
282
283    /// 別の場所で作った署名を付ける。公式の SDK の `attach_signature` と違い、署名者の公開鍵で
284    /// 検証できない署名は付けない。
285    pub fn attach_signature(
286        &mut self,
287        signature: Signature,
288        generation_hash_seed: &GenerationHashSeed,
289    ) -> Result<(), SignError> {
290        let mut signed = self.clone();
291        signed.signature = signature;
292        if !signed.verify(generation_hash_seed) {
293            return Err(SignError::InvalidSignature);
294        }
295        self.signature = signature;
296        Ok(())
297    }
298
299    /// 署名を検証する。catapult の `SignatureValidator` と同じく、
300    /// generation hash seed に続けて、署名の対象の部分に署名されていることを確かめる。
301    pub fn verify(&self, generation_hash_seed: &GenerationHashSeed) -> bool {
302        let bytes = self.to_bytes();
303        self.signer_public_key.verify(
304            &[&generation_hash_seed.0, self.signed_part(&bytes)],
305            &self.signature,
306        )
307    }
308
309    /// 署名とハッシュの対象。catapult の `TransactionPlugin::dataBuffer`。
310    ///
311    /// ふつうはヘッダーの後半から最後まで。アグリゲートは、中のトランザクションのハッシュまでか
312    /// (バージョン 2 まで)、それらの長さまで(バージョン 3)で、後ろの予約など(catapult の `Footer_Size`)と、
313    /// 中のトランザクションと連署は含まない。中のトランザクションは、そのハッシュを通して署名される。
314    fn signed_part<'a>(&self, bytes: &'a [u8]) -> &'a [u8] {
315        match &self.body {
316            Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate) => {
317                let end = HEADER_SIZE + aggregate::FIXED_SIZE - aggregate.version().footer_size();
318                &bytes[UNSIGNED_HEADER_SIZE..end]
319            }
320            _ => &bytes[UNSIGNED_HEADER_SIZE..],
321        }
322    }
323
324    /// ハッシュ。catapult の `model/EntityHasher.cpp` と同じく、署名を丸ごとと署名者の公開鍵、
325    /// generation hash seed、署名の対象の部分を続けた SHA3-256。
326    pub fn hash(&self, generation_hash_seed: &GenerationHashSeed) -> Hash256 {
327        let bytes = self.to_bytes();
328        let mut hasher = Sha3_256::new();
329        hasher.update(self.signature.0);
330        hasher.update(self.signer_public_key.0);
331        hasher.update(generation_hash_seed.0);
332        hasher.update(self.signed_part(&bytes));
333        Hash256(hasher.finalize().into())
334    }
335
336    /// ブロックの TransactionsHash の葉。catapult の `CalculateMerkleComponentHash`。
337    ///
338    /// ふつうはハッシュそのもの。アグリゲートは、ハッシュに連署者の公開鍵を並んだ順に続けた SHA3-256
339    /// (aggregate プラグインの `merkleSupplementaryBuffers`)。連署はハッシュに入らないので、
340    /// ブロックはこちらで連署の取り違えを防ぐ。
341    ///
342    /// Nemesis のブロックだけは、ヘッダーの TransactionsHash をこの値ではなく、トランザクションを丸ごとハッシュした葉で作っている。
343    /// Nemesis では heika-block の `Block::merkle_leaves` を使う。
344    pub fn merkle_component_hash(&self, generation_hash_seed: &GenerationHashSeed) -> Hash256 {
345        let hash = self.hash(generation_hash_seed);
346        let (Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate)) = &self.body
347        else {
348            return hash;
349        };
350        if aggregate.cosignatures().is_empty() {
351            return hash;
352        }
353        let mut hasher = Sha3_256::new();
354        hasher.update(hash.0);
355        for cosignature in aggregate.cosignatures() {
356            hasher.update(cosignature.signer_public_key.0);
357        }
358        Hash256(hasher.finalize().into())
359    }
360
361    /// アグリゲートに `private_key` の連署を足す。
362    ///
363    /// 連署するのは外側の署名を含むハッシュなので、先に署名されていなければならない。
364    /// catapult の `BasicAggregateCosignaturesValidator` と同じく、外側の署名者やすでに連署した鍵の連署は弾く。
365    /// 誰の連署が要るかはマルチシグの設定で決まるので、ここでは確かめない。
366    pub fn cosign(
367        &mut self,
368        private_key: &PrivateKey,
369        generation_hash_seed: &GenerationHashSeed,
370    ) -> Result<(), CosignError> {
371        let hash = self.hash_to_cosign(generation_hash_seed)?;
372        self.add_cosignature(Cosignature::sign(private_key, &hash))
373    }
374
375    /// 切り離して集めた連署を、アグリゲートに付ける。[`Transaction::cosign`] と同じものを弾くほか、
376    /// 連署したアグリゲートがこれでないものと、署名が正しくないものも弾く。
377    pub fn attach_cosignature(
378        &mut self,
379        detached: &DetachedCosignature,
380        generation_hash_seed: &GenerationHashSeed,
381    ) -> Result<(), CosignError> {
382        let hash = self.hash_to_cosign(generation_hash_seed)?;
383        if detached.parent_hash != hash {
384            return Err(CosignError::OtherParent);
385        }
386        if !detached.verify() {
387            return Err(CosignError::InvalidSignature);
388        }
389        self.add_cosignature(detached.cosignature)
390    }
391
392    /// 連署の対象になるハッシュ。署名したアグリゲートでなければ連署できない
393    fn hash_to_cosign(
394        &self,
395        generation_hash_seed: &GenerationHashSeed,
396    ) -> Result<Hash256, CosignError> {
397        if !Body::is_aggregate_type(self.body.transaction_type()) {
398            return Err(CosignError::NotAggregate);
399        }
400        if self.signature == Signature([0; 64]) {
401            return Err(CosignError::NotSigned);
402        }
403        Ok(self.hash(generation_hash_seed))
404    }
405
406    /// 外側の署名者やすでに連署した鍵でなければ、連署を足す
407    fn add_cosignature(&mut self, cosignature: Cosignature) -> Result<(), CosignError> {
408        let signer_public_key = self.signer_public_key;
409        let (Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate)) =
410            &mut self.body
411        else {
412            unreachable!("checked by hash_to_cosign");
413        };
414        if cosignature.signer_public_key == signer_public_key
415            || aggregate
416                .cosignatures()
417                .iter()
418                .any(|existing| existing.signer_public_key == cosignature.signer_public_key)
419        {
420            return Err(CosignError::Redundant);
421        }
422        aggregate.add_cosignature(cosignature);
423        Ok(())
424    }
425
426    /// 連署を外して返す。アグリゲートでなければ空
427    pub fn take_cosignatures(&mut self) -> Vec<Cosignature> {
428        match &mut self.body {
429            Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate) => {
430                aggregate.take_cosignatures()
431            }
432            _ => Vec::new(),
433        }
434    }
435
436    /// 連署をすべて検証する。アグリゲートでなければ連署はないので `true`。
437    pub fn verify_cosignatures(&self, generation_hash_seed: &GenerationHashSeed) -> bool {
438        let (Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate)) = &self.body
439        else {
440            return true;
441        };
442        let hash = self.hash(generation_hash_seed);
443        aggregate
444            .cosignatures()
445            .iter()
446            .all(|cosignature| cosignature.verify(&hash))
447    }
448}
449
450impl Body {
451    /// catbuffer の `TransactionType`。
452    pub fn transaction_type(&self) -> u16 {
453        match self {
454            Self::AccountKeyLink(_) => 0x414C,
455            Self::NodeKeyLink(_) => 0x424C,
456            Self::VotingKeyLink(_) => 0x4143,
457            Self::VrfKeyLink(_) => 0x4243,
458            Self::HashLock(_) => 0x4148,
459            Self::SecretLock(_) => 0x4152,
460            Self::SecretProof(_) => 0x4252,
461            Self::AccountMetadata(_) => 0x4144,
462            Self::MosaicMetadata(_) => 0x4244,
463            Self::NamespaceMetadata(_) => 0x4344,
464            Self::MosaicDefinition(_) => 0x414D,
465            Self::MosaicSupplyChange(_) => 0x424D,
466            Self::MosaicSupplyRevocation(_) => 0x434D,
467            Self::MultisigAccountModification(_) => 0x4155,
468            Self::AddressAlias(_) => 0x424E,
469            Self::MosaicAlias(_) => 0x434E,
470            Self::NamespaceRegistration(_) => 0x414E,
471            Self::AccountAddressRestriction(_) => 0x4150,
472            Self::AccountMosaicRestriction(_) => 0x4250,
473            Self::AccountOperationRestriction(_) => 0x4350,
474            Self::MosaicAddressRestriction(_) => 0x4251,
475            Self::MosaicGlobalRestriction(_) => 0x4151,
476            Self::Transfer(_) => 0x4154,
477            Self::AggregateComplete(_) => 0x4141,
478            Self::AggregateBonded(_) => 0x4241,
479        }
480    }
481
482    /// 種類ごとの構造のバージョン。アグリゲートは [`AggregateVersion`] のとおりで、新しく作ればバージョン 3。
483    /// ほかの種類は、どれもバージョン 1 しかない。
484    pub fn version(&self) -> u8 {
485        match self {
486            Self::AggregateComplete(aggregate) | Self::AggregateBonded(aggregate) => {
487                aggregate.version().number()
488            }
489            _ => 1,
490        }
491    }
492
493    fn encode(&self, out: &mut Vec<u8>) {
494        match self {
495            Self::AccountKeyLink(link) | Self::NodeKeyLink(link) | Self::VrfKeyLink(link) => {
496                link.encode(out)
497            }
498            Self::VotingKeyLink(link) => link.encode(out),
499            Self::HashLock(lock) => lock.encode(out),
500            Self::SecretLock(lock) => lock.encode(out),
501            Self::SecretProof(proof) => proof.encode(out),
502            Self::AccountMetadata(metadata) => metadata.encode(None, out),
503            Self::MosaicMetadata(metadata) => metadata.encode(out),
504            Self::NamespaceMetadata(metadata) => metadata.encode(out),
505            Self::MosaicDefinition(definition) => definition.encode(out),
506            Self::MosaicSupplyChange(change) => change.encode(out),
507            Self::MosaicSupplyRevocation(revocation) => revocation.encode(out),
508            Self::MultisigAccountModification(modification) => modification.encode(out),
509            Self::AddressAlias(alias) => alias.encode(out),
510            Self::MosaicAlias(alias) => alias.encode(out),
511            Self::NamespaceRegistration(registration) => registration.encode(out),
512            Self::AccountAddressRestriction(restriction) => restriction.encode(out),
513            Self::AccountMosaicRestriction(restriction) => restriction.encode(out),
514            Self::AccountOperationRestriction(restriction) => restriction.encode(out),
515            Self::MosaicAddressRestriction(restriction) => restriction.encode(out),
516            Self::MosaicGlobalRestriction(restriction) => restriction.encode(out),
517            Self::Transfer(transfer) => transfer.encode(out),
518            Self::AggregateComplete(aggregate) | Self::AggregateBonded(aggregate) => {
519                aggregate.encode(out)
520            }
521        }
522    }
523
524    /// 種類とバージョンの組が catbuffer にあるか。
525    pub(crate) fn is_known(transaction_type: u16, version: u8) -> bool {
526        if Self::is_aggregate_type(transaction_type) {
527            (1..=3).contains(&version)
528        } else {
529            version == 1 && Self::is_version_1_type(transaction_type)
530        }
531    }
532
533    /// アグリゲート以外の23種類。どれもバージョン 1 だけがある。
534    /// catbuffer の `schemas/symbol/transaction_type.cats` と、各スキーマの `TRANSACTION_VERSION` から書き起こした
535    /// (symbol/symbol のコミット dbff03b4096622d1bc1fce611358e05cfa7b0296)
536    fn is_version_1_type(transaction_type: u16) -> bool {
537        matches!(
538            transaction_type,
539            0x414C
540                | 0x424C
541                | 0x4143
542                | 0x4243
543                | 0x4148
544                | 0x4152
545                | 0x4252
546                | 0x4144
547                | 0x4244
548                | 0x4344
549                | 0x414D
550                | 0x424D
551                | 0x434D
552                | 0x4155
553                | 0x424E
554                | 0x434E
555                | 0x414E
556                | 0x4150
557                | 0x4250
558                | 0x4350
559                | 0x4251
560                | 0x4151
561                | 0x4154
562        )
563    }
564
565    fn decode(transaction_type: u16, version: u8, bytes: &[u8]) -> Result<Self, DecodeError> {
566        if !Self::is_aggregate_type(transaction_type) && !Self::is_version_1_type(transaction_type)
567        {
568            return Err(DecodeError::UnknownType(transaction_type));
569        }
570        if !Self::is_known(transaction_type, version) {
571            return Err(DecodeError::UnsupportedVersion {
572                transaction_type,
573                version,
574            });
575        }
576        Ok(match transaction_type {
577            0x414C => Self::AccountKeyLink(KeyLink::decode(bytes)?),
578            0x424C => Self::NodeKeyLink(KeyLink::decode(bytes)?),
579            0x4143 => Self::VotingKeyLink(VotingKeyLink::decode(bytes)?),
580            0x4243 => Self::VrfKeyLink(KeyLink::decode(bytes)?),
581            0x4148 => Self::HashLock(HashLock::decode(bytes)?),
582            0x4152 => Self::SecretLock(SecretLock::decode(bytes)?),
583            0x4252 => Self::SecretProof(SecretProof::decode(bytes)?),
584            0x4144 => Self::AccountMetadata(Metadata::decode(bytes, false)?.0),
585            0x4244 => Self::MosaicMetadata(MosaicMetadata::decode(bytes)?),
586            0x4344 => Self::NamespaceMetadata(NamespaceMetadata::decode(bytes)?),
587            0x414D => Self::MosaicDefinition(MosaicDefinition::decode(bytes)?),
588            0x424D => Self::MosaicSupplyChange(MosaicSupplyChange::decode(bytes)?),
589            0x434D => Self::MosaicSupplyRevocation(MosaicSupplyRevocation::decode(bytes)?),
590            0x4155 => {
591                Self::MultisigAccountModification(MultisigAccountModification::decode(bytes)?)
592            }
593            0x424E => Self::AddressAlias(AddressAlias::decode(bytes)?),
594            0x434E => Self::MosaicAlias(MosaicAlias::decode(bytes)?),
595            0x414E => Self::NamespaceRegistration(NamespaceRegistration::decode(bytes)?),
596            0x4150 => Self::AccountAddressRestriction(AccountRestriction::decode(bytes)?),
597            0x4250 => Self::AccountMosaicRestriction(AccountRestriction::decode(bytes)?),
598            0x4350 => Self::AccountOperationRestriction(AccountRestriction::decode(bytes)?),
599            0x4251 => Self::MosaicAddressRestriction(MosaicAddressRestriction::decode(bytes)?),
600            0x4151 => Self::MosaicGlobalRestriction(MosaicGlobalRestriction::decode(bytes)?),
601            0x4154 => Self::Transfer(Transfer::decode(bytes)?),
602            0x4141 => Self::AggregateComplete(Aggregate::decode(version, bytes)?),
603            _ => Self::AggregateBonded(Aggregate::decode(version, bytes)?),
604        })
605    }
606
607    fn is_aggregate_type(transaction_type: u16) -> bool {
608        matches!(transaction_type, 0x4141 | 0x4241)
609    }
610
611    /// 単独で送れるか。メタデータの3種類とマルチシグの変更は、アグリゲートの中でしか使えない
612    /// (catapult の `Only_Embeddable`)。単独で送ると、ノードは理由を返さずに捨てる。
613    pub fn supports_top_level(&self) -> bool {
614        !matches!(
615            self,
616            Self::AccountMetadata(_)
617                | Self::MosaicMetadata(_)
618                | Self::NamespaceMetadata(_)
619                | Self::MultisigAccountModification(_)
620        )
621    }
622}
623
624impl KeyLink {
625    const SIZE: usize = 32 + 1;
626
627    fn encode(&self, out: &mut Vec<u8>) {
628        out.extend_from_slice(&self.linked_public_key.0);
629        out.push(self.link_action.to_byte());
630    }
631
632    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
633        let mut reader = Reader::exact(bytes, Self::SIZE)?;
634        Ok(Self {
635            linked_public_key: PublicKey(reader.array()),
636            link_action: LinkAction::from_byte(reader.u8())?,
637        })
638    }
639}
640
641impl VotingKeyLink {
642    const SIZE: usize = 32 + 4 + 4 + 1;
643
644    fn encode(&self, out: &mut Vec<u8>) {
645        out.extend_from_slice(&self.linked_public_key.0);
646        out.extend_from_slice(&self.start_epoch.to_le_bytes());
647        out.extend_from_slice(&self.end_epoch.to_le_bytes());
648        out.push(self.link_action.to_byte());
649    }
650
651    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
652        let mut reader = Reader::exact(bytes, Self::SIZE)?;
653        Ok(Self {
654            linked_public_key: PublicKey(reader.array()),
655            start_epoch: reader.u32(),
656            end_epoch: reader.u32(),
657            link_action: LinkAction::from_byte(reader.u8())?,
658        })
659    }
660}
661
662/// 長さを確かめ終えたバイト列を、先頭から順に読む。
663struct Reader<'a>(&'a [u8]);
664
665impl<'a> Reader<'a> {
666    /// 長さがちょうど `size` のときだけ読む
667    fn exact(bytes: &'a [u8], size: usize) -> Result<Self, DecodeError> {
668        if bytes.len() != size {
669            return Err(DecodeError::InvalidBodySize);
670        }
671        Ok(Self(bytes))
672    }
673
674    /// 長さが `size` 以上のときだけ読む。残りは [`Reader::rest`] か [`Reader::expect_remaining`] で確かめる
675    fn at_least(bytes: &'a [u8], size: usize) -> Result<Self, DecodeError> {
676        if bytes.len() < size {
677            return Err(DecodeError::InvalidBodySize);
678        }
679        Ok(Self(bytes))
680    }
681
682    /// 残りがちょうど `size` か
683    fn expect_remaining(&self, size: usize) -> Result<(), DecodeError> {
684        if self.0.len() != size {
685            return Err(DecodeError::InvalidBodySize);
686        }
687        Ok(())
688    }
689
690    /// 残りがちょうど `size` なら、残りを全部返す
691    fn rest(&mut self, size: usize) -> Result<&'a [u8], DecodeError> {
692        self.expect_remaining(size)?;
693        Ok(core::mem::take(&mut self.0))
694    }
695
696    fn array<const N: usize>(&mut self) -> [u8; N] {
697        let (head, rest) = self.0.split_first_chunk().expect("length checked");
698        self.0 = rest;
699        *head
700    }
701
702    fn u8(&mut self) -> u8 {
703        u8::from_le_bytes(self.array())
704    }
705
706    fn u16(&mut self) -> u16 {
707        u16::from_le_bytes(self.array())
708    }
709
710    fn i16(&mut self) -> i16 {
711        i16::from_le_bytes(self.array())
712    }
713
714    fn u32(&mut self) -> u32 {
715        u32::from_le_bytes(self.array())
716    }
717
718    fn u64(&mut self) -> u64 {
719        u64::from_le_bytes(self.array())
720    }
721}
722
723#[derive(Debug, Clone, PartialEq, Eq)]
724pub enum DecodeError {
725    /// ヘッダーの長さに足りない
726    TooShort,
727    /// 先頭のサイズが、実際の長さと合わない
728    SizeMismatch { stated: u32, actual: usize },
729    /// 予約の部分が0ではない
730    NonZeroReserved,
731    /// 扱えない種類
732    UnknownType(u16),
733    /// 扱えないバージョン
734    UnsupportedVersion { transaction_type: u16, version: u8 },
735    /// 本体の長さが、種類に合わない
736    InvalidBodySize,
737    /// 紐づけの操作が、紐づけるか外すかのどちらでもない
738    InvalidLinkAction(u8),
739    /// 列挙型かフラグの値が、定義されていない
740    InvalidValue { field: &'static str, value: u64 },
741    /// モザイクが ID の昇順に並んでいない。同じ ID が2回出てくるものも含む
742    UnsortedMosaics,
743    /// アグリゲートの中にアグリゲートが入っている
744    NestedAggregate,
745    /// アグリゲートの中のトランザクションのハッシュが、中身と合わない
746    TransactionsHashMismatch,
747}
748
749impl fmt::Display for DecodeError {
750    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
751        match self {
752            Self::TooShort => f.write_str("トランザクションのヘッダーの長さに足りません"),
753            Self::SizeMismatch { stated, actual } => write!(
754                f,
755                "サイズは {stated} バイトとありますが、実際は {actual} バイトでした"
756            ),
757            Self::NonZeroReserved => f.write_str("予約の部分が0ではありません"),
758            Self::UnknownType(transaction_type) => {
759                write!(
760                    f,
761                    "種類 0x{transaction_type:04X} のトランザクションは扱えません"
762                )
763            }
764            Self::UnsupportedVersion {
765                transaction_type,
766                version,
767            } => write!(
768                f,
769                "種類 0x{transaction_type:04X} のバージョン {version} は扱えません"
770            ),
771            Self::InvalidBodySize => f.write_str("本体の長さが種類に合いません"),
772            Self::InvalidLinkAction(action) => {
773                write!(
774                    f,
775                    "紐づけの操作 {action} は、紐づけるか外すかのどちらでもありません"
776                )
777            }
778            Self::InvalidValue { field, value } => {
779                write!(f, "{field}の値 {value} は定義されていません")
780            }
781            Self::UnsortedMosaics => f.write_str("モザイクが ID の昇順に並んでいません"),
782            Self::NestedAggregate => f.write_str("アグリゲートの中にアグリゲートが入っています"),
783            Self::TransactionsHashMismatch => {
784                f.write_str("アグリゲートの中のトランザクションのハッシュが、中身と合いません")
785            }
786        }
787    }
788}
789
790impl core::error::Error for DecodeError {}
791
792#[derive(Debug, Clone, PartialEq, Eq)]
793pub enum SignError {
794    /// 秘密鍵が、署名者の公開鍵と合わない
795    KeyMismatch,
796    /// 付けようとした署名が、署名者の公開鍵で検証できない
797    InvalidSignature,
798}
799
800impl fmt::Display for SignError {
801    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802        match self {
803            Self::KeyMismatch => f.write_str("秘密鍵が署名者の公開鍵と合いません"),
804            Self::InvalidSignature => f.write_str("署名が、署名者の公開鍵で検証できません"),
805        }
806    }
807}
808
809impl core::error::Error for SignError {}
810
811#[derive(Debug, Clone, PartialEq, Eq)]
812pub enum CosignError {
813    /// アグリゲートではない
814    NotAggregate,
815    /// 外側の署名がまだない
816    NotSigned,
817    /// 外側の署名者か、すでに連署した鍵
818    Redundant,
819    /// 切り離した連署が、別のアグリゲートへのもの
820    OtherParent,
821    /// 切り離した連署の署名が正しくない
822    InvalidSignature,
823}
824
825impl fmt::Display for CosignError {
826    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
827        match self {
828            Self::NotAggregate => f.write_str("アグリゲートではないので連署できません"),
829            Self::NotSigned => f.write_str("まだ署名されていないので連署できません"),
830            Self::Redundant => {
831                f.write_str("この鍵は署名者か、すでに連署しているので、連署を重ねられません")
832            }
833            Self::OtherParent => f.write_str("別のアグリゲートへの連署なので、付けられません"),
834            Self::InvalidSignature => f.write_str("連署の署名が正しくないので、付けられません"),
835        }
836    }
837}
838
839impl core::error::Error for CosignError {}
840
841/// 種類ごとのモジュールのテストで使う。
842#[cfg(test)]
843pub(crate) mod testing {
844    use super::*;
845
846    /// `body` を入れたトランザクションを書いて読み戻し、同じ本体になることを確かめる。返すのは本体のバイト列
847    pub fn round_trip(body: Body) -> Vec<u8> {
848        let transaction = Transaction::new(
849            PublicKey([0x11; 32]),
850            NetworkIdentifier::TESTNET,
851            0,
852            0,
853            body,
854        );
855        let bytes = transaction.to_bytes();
856        assert_eq!(Transaction::from_bytes(&bytes).as_ref(), Ok(&transaction));
857        bytes[HEADER_SIZE..].to_vec()
858    }
859
860    /// 本体のバイト列を、バージョン 1 の種類 `transaction_type` として読む
861    pub fn decode(transaction_type: u16, body: &[u8]) -> Result<Body, DecodeError> {
862        Body::decode(transaction_type, 1, body)
863    }
864}
865
866#[cfg(test)]
867mod tests {
868    use super::*;
869
870    // RFC 8032 の 7.1 節にある Ed25519 のテスト 1
871    const PRIVATE: &str = "9D61B19DEFFD5A60BA844AF492EC2CC44449C5697B326919703BAC031CAE7F60";
872
873    fn private_key() -> PrivateKey {
874        PRIVATE.parse().unwrap()
875    }
876
877    fn seed() -> GenerationHashSeed {
878        GenerationHashSeed([0x5E; 32])
879    }
880
881    fn transaction(body: Body) -> Transaction {
882        Transaction::new(
883            PublicKey::from_private_key(&private_key()),
884            NetworkIdentifier::TESTNET,
885            0x0807_0605_0403_0201,
886            0x1817_1615_1413_1211,
887            body,
888        )
889    }
890
891    fn vrf_key_link() -> Transaction {
892        transaction(Body::VrfKeyLink(KeyLink {
893            linked_public_key: PublicKey([0xAA; 32]),
894            link_action: LinkAction::Link,
895        }))
896    }
897
898    #[test]
899    fn writes_the_catbuffer_layout() {
900        let bytes = vrf_key_link().to_bytes();
901        assert_eq!(bytes.len(), 161);
902        assert_eq!(bytes[..8], [0xA1, 0, 0, 0, 0, 0, 0, 0]);
903        assert_eq!(bytes[8..72], [0; 64]);
904        assert_eq!(
905            bytes[72..104],
906            PublicKey::from_private_key(&private_key()).0
907        );
908        assert_eq!(bytes[104..108], [0; 4]);
909        assert_eq!(bytes[108..112], [0x01, 0x98, 0x43, 0x42]);
910        assert_eq!(bytes[112..120], [1, 2, 3, 4, 5, 6, 7, 8]);
911        assert_eq!(
912            bytes[120..128],
913            [0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18]
914        );
915        assert_eq!(bytes[128..160], [0xAA; 32]);
916        assert_eq!(bytes[160], 1);
917    }
918
919    #[test]
920    fn round_trips_every_key_link() {
921        let link = KeyLink {
922            linked_public_key: PublicKey([0xAA; 32]),
923            link_action: LinkAction::Unlink,
924        };
925        for (body, transaction_type) in [
926            (Body::AccountKeyLink(link), [0x4C, 0x41]),
927            (Body::NodeKeyLink(link), [0x4C, 0x42]),
928            (Body::VrfKeyLink(link), [0x43, 0x42]),
929        ] {
930            let transaction = transaction(body);
931            let bytes = transaction.to_bytes();
932            assert_eq!(bytes[110..112], transaction_type);
933            assert_eq!(bytes[160], 0);
934            assert_eq!(Transaction::from_bytes(&bytes), Ok(transaction));
935        }
936    }
937
938    #[test]
939    fn writes_the_epochs_of_a_voting_key_link() {
940        let link = VotingKeyLink {
941            linked_public_key: PublicKey([0xAA; 32]),
942            start_epoch: 0x0102,
943            end_epoch: 0x0304,
944            link_action: LinkAction::Link,
945        };
946        let transaction = transaction(Body::VotingKeyLink(link));
947        let bytes = transaction.to_bytes();
948        assert_eq!(bytes[110..112], [0x43, 0x41]);
949        assert_eq!(bytes[HEADER_SIZE + 32..], [2, 1, 0, 0, 4, 3, 0, 0, 1]);
950        assert_eq!(Transaction::from_bytes(&bytes), Ok(transaction));
951    }
952
953    #[test]
954    fn rejects_a_short_header() {
955        let bytes = vrf_key_link().to_bytes();
956        assert_eq!(
957            Transaction::from_bytes(&bytes[..HEADER_SIZE - 1]),
958            Err(DecodeError::TooShort)
959        );
960    }
961
962    #[test]
963    fn rejects_a_wrong_size() {
964        let mut bytes = vrf_key_link().to_bytes();
965        bytes[0] = 0xA0;
966        assert_eq!(
967            Transaction::from_bytes(&bytes),
968            Err(DecodeError::SizeMismatch {
969                stated: 160,
970                actual: 161
971            })
972        );
973    }
974
975    #[test]
976    fn keeps_non_zero_reserved_bytes_like_catapult() {
977        let seed = seed();
978        let mut signed = vrf_key_link();
979        signed.sign(&private_key(), &seed).unwrap();
980        for offset in [4, 104] {
981            let mut bytes = signed.to_bytes();
982            bytes[offset] = 1;
983            let transaction = Transaction::from_bytes(&bytes).unwrap();
984            assert_eq!(transaction.to_bytes(), bytes, "offset {offset}");
985            // 署名にもハッシュにも入らない
986            assert!(transaction.verify(&seed), "offset {offset}");
987            assert_eq!(
988                transaction.hash(&seed),
989                signed.hash(&seed),
990                "offset {offset}"
991            );
992        }
993    }
994
995    #[test]
996    fn rejects_an_unknown_type() {
997        let mut bytes = vrf_key_link().to_bytes();
998        bytes[110..112].copy_from_slice(&0x4999u16.to_le_bytes());
999        assert_eq!(
1000            Transaction::from_bytes(&bytes),
1001            Err(DecodeError::UnknownType(0x4999))
1002        );
1003    }
1004
1005    #[test]
1006    fn rejects_an_unsupported_version() {
1007        let mut bytes = vrf_key_link().to_bytes();
1008        bytes[108] = 2;
1009        assert_eq!(
1010            Transaction::from_bytes(&bytes),
1011            Err(DecodeError::UnsupportedVersion {
1012                transaction_type: 0x4243,
1013                version: 2
1014            })
1015        );
1016    }
1017
1018    #[test]
1019    fn rejects_a_body_of_the_wrong_size() {
1020        let mut bytes = vrf_key_link().to_bytes();
1021        bytes.push(0);
1022        bytes[0] = 162;
1023        assert_eq!(
1024            Transaction::from_bytes(&bytes),
1025            Err(DecodeError::InvalidBodySize)
1026        );
1027    }
1028
1029    #[test]
1030    fn rejects_an_unknown_link_action() {
1031        let mut bytes = vrf_key_link().to_bytes();
1032        bytes[160] = 2;
1033        assert_eq!(
1034            Transaction::from_bytes(&bytes),
1035            Err(DecodeError::InvalidLinkAction(2))
1036        );
1037    }
1038
1039    #[test]
1040    fn signs_the_seed_and_the_signed_part() {
1041        let mut transaction = vrf_key_link();
1042        transaction.sign(&private_key(), &seed()).unwrap();
1043        let bytes = transaction.to_bytes();
1044        let signature = private_key().sign(&[&seed().0, &bytes[108..]]);
1045        assert_eq!(transaction.signature, signature);
1046        assert!(transaction.verify(&seed()));
1047    }
1048
1049    #[test]
1050    fn rejects_another_network_or_a_changed_field() {
1051        let mut transaction = vrf_key_link();
1052        transaction.sign(&private_key(), &seed()).unwrap();
1053        assert!(!transaction.verify(&GenerationHashSeed([0; 32])));
1054        let mut changed = transaction.clone();
1055        changed.fee += 1;
1056        assert!(!changed.verify(&seed()));
1057    }
1058
1059    #[test]
1060    fn refuses_to_sign_with_another_key() {
1061        let mut transaction = vrf_key_link();
1062        let other = PrivateKey::from_bytes(&[1; 32]);
1063        assert_eq!(
1064            transaction.sign(&other, &seed()),
1065            Err(SignError::KeyMismatch)
1066        );
1067        assert_eq!(transaction.signature, Signature([0; 64]));
1068    }
1069
1070    #[test]
1071    fn hashes_the_signature_the_signer_the_seed_and_the_signed_part() {
1072        let mut transaction = vrf_key_link();
1073        transaction.sign(&private_key(), &seed()).unwrap();
1074        let bytes = transaction.to_bytes();
1075        let mut hasher = Sha3_256::new();
1076        hasher.update(&bytes[8..104]);
1077        hasher.update(seed().0);
1078        hasher.update(&bytes[108..]);
1079        let expected = Hash256(hasher.finalize().into());
1080        assert_eq!(transaction.hash(&seed()), expected);
1081        assert_ne!(transaction.hash(&GenerationHashSeed([0; 32])), expected);
1082    }
1083
1084    fn aggregate_complete() -> Transaction {
1085        let cosigner = PublicKey::from_private_key(&cosigner_key());
1086        let embedded = vrf_key_link().body;
1087        let aggregate = Aggregate::new(vec![EmbeddedTransaction::new(
1088            cosigner,
1089            NetworkIdentifier::TESTNET,
1090            embedded,
1091        )])
1092        .unwrap();
1093        transaction(Body::AggregateComplete(aggregate))
1094    }
1095
1096    fn cosigner_key() -> PrivateKey {
1097        PrivateKey::from_bytes(&[7; 32])
1098    }
1099
1100    #[test]
1101    fn calculates_the_fee_from_the_size() {
1102        let transaction = vrf_key_link();
1103        let size = transaction.to_bytes().len();
1104        assert_eq!(transaction.size(), size);
1105        assert_eq!(transaction.fee_for(100, 0), size as u64 * 100);
1106        // これから付く連署の分も数える
1107        assert_eq!(transaction.fee_for(100, 2), (size as u64 + 2 * 104) * 100);
1108        assert_eq!(transaction.fee_for(0, 2), 0);
1109    }
1110
1111    #[test]
1112    fn counts_attached_cosignatures_in_the_size() {
1113        let mut transaction = aggregate_complete();
1114        transaction.sign(&private_key(), &seed()).unwrap();
1115        let before = transaction.fee_for(100, 1);
1116        transaction.cosign(&cosigner_key(), &seed()).unwrap();
1117        assert_eq!(transaction.fee_for(100, 0), before);
1118    }
1119
1120    #[test]
1121    fn calculates_the_max_fee_multiplier() {
1122        let mut transaction = vrf_key_link();
1123        let size = transaction.size() as u64;
1124        transaction.fee = size * 100 + size - 1;
1125        assert_eq!(transaction.max_fee_multiplier(), 100);
1126        transaction.fee = 0;
1127        assert_eq!(transaction.max_fee_multiplier(), 0);
1128        // 倍率は u32 なので、それより大きければ上限に丸める
1129        transaction.fee = u64::MAX;
1130        assert_eq!(transaction.max_fee_multiplier(), u32::MAX);
1131    }
1132
1133    #[test]
1134    fn attaches_a_detached_cosignature() {
1135        let mut transaction = aggregate_complete();
1136        transaction.sign(&private_key(), &seed()).unwrap();
1137        let hash = transaction.hash(&seed());
1138        let detached = DetachedCosignature::sign(&cosigner_key(), &hash);
1139
1140        // 別のアグリゲートへの連署や、署名を壊したものは付けない
1141        let other = DetachedCosignature::sign(&cosigner_key(), &Hash256([0; 32]));
1142        assert_eq!(
1143            transaction.attach_cosignature(&other, &seed()),
1144            Err(CosignError::OtherParent)
1145        );
1146        let mut broken = detached;
1147        broken.cosignature.signature.0[0] ^= 1;
1148        assert_eq!(
1149            transaction.attach_cosignature(&broken, &seed()),
1150            Err(CosignError::InvalidSignature)
1151        );
1152
1153        transaction.attach_cosignature(&detached, &seed()).unwrap();
1154        assert!(transaction.verify_cosignatures(&seed()));
1155        assert_eq!(
1156            transaction.attach_cosignature(&detached, &seed()),
1157            Err(CosignError::Redundant)
1158        );
1159        // 自分で連署したのと同じものになる
1160        let mut cosigned = aggregate_complete();
1161        cosigned.sign(&private_key(), &seed()).unwrap();
1162        cosigned.cosign(&cosigner_key(), &seed()).unwrap();
1163        assert_eq!(transaction, cosigned);
1164    }
1165
1166    #[test]
1167    fn signs_the_payload_elsewhere_and_attaches_the_signature() {
1168        for mut transaction in [vrf_key_link(), aggregate_complete()] {
1169            let payload = transaction.signing_payload(&seed());
1170            assert_eq!(payload[..32], seed().0);
1171            let signature = private_key().sign(&[&payload]);
1172
1173            let mut signed = transaction.clone();
1174            signed.sign(&private_key(), &seed()).unwrap();
1175            assert_eq!(signed.signature, signature);
1176
1177            // 別のネットワークの署名や、壊した署名は付けない
1178            let other =
1179                private_key().sign(&[&transaction.signing_payload(&GenerationHashSeed([0; 32]))]);
1180            assert_eq!(
1181                transaction.attach_signature(other, &seed()),
1182                Err(SignError::InvalidSignature)
1183            );
1184            assert_eq!(transaction.signature, Signature([0; 64]));
1185            transaction.attach_signature(signature, &seed()).unwrap();
1186            assert_eq!(transaction, signed);
1187        }
1188    }
1189
1190    #[test]
1191    fn cosigns_the_hash_of_a_signed_aggregate() {
1192        let mut transaction = aggregate_complete();
1193        transaction.sign(&private_key(), &seed()).unwrap();
1194        let hash = transaction.hash(&seed());
1195        transaction.cosign(&cosigner_key(), &seed()).unwrap();
1196        assert_eq!(transaction.hash(&seed()), hash);
1197        let Body::AggregateComplete(aggregate) = &transaction.body else {
1198            unreachable!()
1199        };
1200        assert_eq!(
1201            aggregate.cosignatures(),
1202            [Cosignature::sign(&cosigner_key(), &hash)]
1203        );
1204        assert!(transaction.verify_cosignatures(&seed()));
1205        assert!(!transaction.verify_cosignatures(&GenerationHashSeed([0; 32])));
1206    }
1207
1208    #[test]
1209    fn mixes_cosigners_into_the_merkle_component_hash() {
1210        let mut transaction = vrf_key_link();
1211        transaction.sign(&private_key(), &seed()).unwrap();
1212        assert_eq!(
1213            transaction.merkle_component_hash(&seed()),
1214            transaction.hash(&seed())
1215        );
1216
1217        let mut transaction = aggregate_complete();
1218        transaction.sign(&private_key(), &seed()).unwrap();
1219        let hash = transaction.hash(&seed());
1220        assert_eq!(transaction.merkle_component_hash(&seed()), hash);
1221        transaction.cosign(&cosigner_key(), &seed()).unwrap();
1222        let cosigner = PublicKey::from_private_key(&cosigner_key());
1223        assert_eq!(
1224            transaction.merkle_component_hash(&seed()),
1225            Hash256(Sha3_256::digest([hash.0, cosigner.0].concat()).into())
1226        );
1227    }
1228
1229    #[test]
1230    fn refuses_to_cosign_an_unsigned_or_non_aggregate_transaction() {
1231        assert_eq!(
1232            aggregate_complete().cosign(&cosigner_key(), &seed()),
1233            Err(CosignError::NotSigned)
1234        );
1235        let mut transaction = vrf_key_link();
1236        transaction.sign(&private_key(), &seed()).unwrap();
1237        assert_eq!(
1238            transaction.cosign(&cosigner_key(), &seed()),
1239            Err(CosignError::NotAggregate)
1240        );
1241        assert!(transaction.verify_cosignatures(&seed()));
1242    }
1243
1244    #[test]
1245    fn refuses_a_redundant_cosignature() {
1246        let mut transaction = aggregate_complete();
1247        transaction.sign(&private_key(), &seed()).unwrap();
1248        assert_eq!(
1249            transaction.cosign(&private_key(), &seed()),
1250            Err(CosignError::Redundant)
1251        );
1252        transaction.cosign(&cosigner_key(), &seed()).unwrap();
1253        assert_eq!(
1254            transaction.cosign(&cosigner_key(), &seed()),
1255            Err(CosignError::Redundant)
1256        );
1257    }
1258}