Skip to main content

heika_transaction/
aggregate.rs

1//! アグリゲート。catbuffer の `aggregate/aggregate.cats` と、catapult の aggregate プラグイン。
2//!
3//! いくつかのトランザクションを、全部成功するか全部失敗するかのひとまとまりにする。
4//! 中のトランザクション(embedded)は署名を持たず、署名者は外側の署名か連署で示す。
5
6use alloc::vec::Vec;
7
8use heika_core::hash::Hash256;
9use heika_core::key::{PrivateKey, PublicKey};
10use heika_core::merkle;
11use heika_core::network::NetworkIdentifier;
12use heika_core::signature::Signature;
13use sha3::{Digest, Sha3_256};
14
15use crate::{Body, DecodeError, Reader};
16
17/// embedded のヘッダー。サイズ、予約、署名者の公開鍵、予約、バージョン、ネットワーク、種類。
18const EMBEDDED_HEADER_SIZE: usize = 4 + 4 + 32 + 4 + 1 + 1 + 2;
19
20/// 中のトランザクションより前の部分。中のトランザクションのハッシュ、それらの長さ、予約。
21pub(crate) const FIXED_SIZE: usize = 32 + 4 + 4;
22
23/// 連署の長さ。バージョン、署名者の公開鍵、署名。
24pub(crate) const COSIGNATURE_SIZE: usize = 8 + 32 + 64;
25
26/// アグリゲートの中のトランザクション。catbuffer の `EmbeddedTransaction` に、種類ごとの本体が続く。
27#[derive(Clone, PartialEq, Eq, Debug)]
28pub struct EmbeddedTransaction {
29    pub signer_public_key: PublicKey,
30    pub network: NetworkIdentifier,
31    pub body: Body,
32    /// ヘッダーの2つの予約の部分と、後ろの8バイト境界までの埋め草(リトルエンディアン)。catapult は確かめないので、
33    /// 0 でなくてもブロックに入りうる。予約の部分は中のトランザクションのハッシュに、埋め草はバージョン 1 の誤った
34    /// 葉の求め方に入るので、読んだ値を持っておく
35    reserved: [u32; 2],
36    padding: u64,
37}
38
39impl EmbeddedTransaction {
40    pub fn new(signer_public_key: PublicKey, network: NetworkIdentifier, body: Body) -> Self {
41        Self {
42            signer_public_key,
43            network,
44            body,
45            reserved: [0; 2],
46            padding: 0,
47        }
48    }
49
50    /// 8バイト境界までの埋め草を含まないバイト列。
51    pub fn to_bytes(&self) -> Vec<u8> {
52        let mut body = Vec::new();
53        self.body.encode(&mut body);
54        let size = EMBEDDED_HEADER_SIZE + body.len();
55        let mut bytes = Vec::with_capacity(size);
56        bytes.extend_from_slice(&(size as u32).to_le_bytes());
57        bytes.extend_from_slice(&self.reserved[0].to_le_bytes());
58        bytes.extend_from_slice(&self.signer_public_key.0);
59        bytes.extend_from_slice(&self.reserved[1].to_le_bytes());
60        bytes.push(self.body.version());
61        bytes.push(self.network.0);
62        bytes.extend_from_slice(&self.body.transaction_type().to_le_bytes());
63        bytes.extend_from_slice(&body);
64        bytes
65    }
66
67    /// Merkle ツリーの葉にするハッシュ。埋め草を含まないバイト列の SHA3-256。
68    /// catapult の `AggregateTransactionsHashValidator` の `HashEmbeddedTransaction`。
69    pub fn hash(&self) -> Hash256 {
70        Hash256(Sha3_256::digest(self.to_bytes()).into())
71    }
72
73    /// 埋め草まで含めた SHA3-256。バージョン 1 で許されていた、誤った葉の求め方
74    /// (`HashEmbeddedTransactionWithPadding`)。
75    fn padded_hash(&self) -> Hash256 {
76        Hash256(Sha3_256::digest(self.padded_bytes()).into())
77    }
78
79    /// 8バイト境界までの埋め草を含めたバイト列。アグリゲートの中には、この形で並ぶ。
80    fn padded_bytes(&self) -> Vec<u8> {
81        let mut bytes = self.to_bytes();
82        let padding = bytes.len().next_multiple_of(8) - bytes.len();
83        bytes.extend_from_slice(&self.padding.to_le_bytes()[..padding]);
84        bytes
85    }
86
87    /// `padding` は後ろの埋め草
88    fn decode(bytes: &[u8], padding: &[u8]) -> Result<Self, DecodeError> {
89        let mut reader = Reader(bytes);
90        reader.u32();
91        let reserved_before = reader.u32();
92        let signer_public_key = PublicKey(reader.array());
93        let reserved = [reserved_before, reader.u32()];
94        let version = reader.u8();
95        let network = NetworkIdentifier(reader.u8());
96        let transaction_type = reader.u16();
97        if Body::is_aggregate_type(transaction_type) {
98            return Err(DecodeError::NestedAggregate);
99        }
100        let body = Body::decode(transaction_type, version, reader.0)?;
101        let mut padding_bytes = [0; 8];
102        padding_bytes[..padding.len()].copy_from_slice(padding);
103        Ok(Self {
104            signer_public_key,
105            network,
106            body,
107            reserved,
108            padding: u64::from_le_bytes(padding_bytes),
109        })
110    }
111}
112
113/// 連署。外側の署名者のほかに同意が要るアカウントが、アグリゲートのハッシュに署名したもの。
114#[derive(Clone, Copy, PartialEq, Eq, Debug)]
115pub struct Cosignature {
116    pub signer_public_key: PublicKey,
117    pub signature: Signature,
118}
119
120impl Cosignature {
121    /// アグリゲートのハッシュに署名する。ハッシュは連署を含まないので、連署を足しても変わらない。
122    pub fn sign(private_key: &PrivateKey, transaction_hash: &Hash256) -> Self {
123        Self {
124            signer_public_key: PublicKey::from_private_key(private_key),
125            signature: private_key.sign(&[&transaction_hash.0]),
126        }
127    }
128
129    pub fn verify(&self, transaction_hash: &Hash256) -> bool {
130        self.signer_public_key
131            .verify(&[&transaction_hash.0], &self.signature)
132    }
133
134    /// アグリゲートの中と同じ形のバイト列。バージョン(予約で0)、署名者の公開鍵、署名
135    pub fn to_bytes(&self) -> [u8; COSIGNATURE_SIZE] {
136        let mut bytes = [0; COSIGNATURE_SIZE];
137        bytes[8..40].copy_from_slice(&self.signer_public_key.0);
138        bytes[40..].copy_from_slice(&self.signature.0);
139        bytes
140    }
141
142    /// [`Cosignature::to_bytes`] の形を読む。バージョンは0でなければならない
143    pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
144        let mut reader = Reader::exact(bytes, COSIGNATURE_SIZE)?;
145        if reader.u64() != 0 {
146            return Err(DecodeError::NonZeroReserved);
147        }
148        Ok(Self {
149            signer_public_key: PublicKey(reader.array()),
150            signature: Signature(reader.array()),
151        })
152    }
153}
154
155/// アグリゲートから切り離して受け渡す連署。catbuffer の `DetachedCosignature`。
156/// ボンデッドのアグリゲートに、あとから連署を集めるときに使う。
157#[derive(Clone, Copy, PartialEq, Eq, Debug)]
158pub struct DetachedCosignature {
159    pub cosignature: Cosignature,
160    /// 連署したアグリゲートのハッシュ
161    pub parent_hash: Hash256,
162}
163
164impl DetachedCosignature {
165    /// バージョン(予約で0)、署名者の公開鍵、署名、アグリゲートのハッシュ。
166    pub const SIZE: usize = COSIGNATURE_SIZE + 32;
167
168    /// アグリゲートのハッシュに連署する。
169    pub fn sign(private_key: &PrivateKey, parent_hash: &Hash256) -> Self {
170        Self {
171            cosignature: Cosignature::sign(private_key, parent_hash),
172            parent_hash: *parent_hash,
173        }
174    }
175
176    /// 連署が、書いてあるアグリゲートのハッシュに対して正しいか。
177    pub fn verify(&self) -> bool {
178        self.cosignature.verify(&self.parent_hash)
179    }
180
181    pub fn to_bytes(&self) -> [u8; Self::SIZE] {
182        let mut bytes = [0; Self::SIZE];
183        bytes[8..40].copy_from_slice(&self.cosignature.signer_public_key.0);
184        bytes[40..104].copy_from_slice(&self.cosignature.signature.0);
185        bytes[104..].copy_from_slice(&self.parent_hash.0);
186        bytes
187    }
188
189    /// バイト列から読む。アグリゲートの中の連署と同じく、バージョンは0でなければならない。
190    pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
191        let mut reader = Reader::exact(bytes, Self::SIZE)?;
192        if reader.u64() != 0 {
193            return Err(DecodeError::NonZeroReserved);
194        }
195        Ok(Self {
196            cosignature: Cosignature {
197                signer_public_key: PublicKey(reader.array()),
198                signature: Signature(reader.array()),
199            },
200            parent_hash: Hash256(reader.array()),
201        })
202    }
203}
204
205/// アグリゲートの構造のバージョン。形は同じで、署名の範囲と、中のトランザクションのハッシュの決まりが違う。
206///
207/// 新しく作るのはいつもバージョン 3。それより前のものは、チェーンにあるものを読むためだけに扱う。
208/// どの高さでどのバージョンが使えるかは、catapult の `AggregateTransactionVersionValidator` と
209/// ネットワークの設定の `[fork_heights]` で決まる。
210#[derive(Clone, Copy, PartialEq, Eq, Debug)]
211pub enum AggregateVersion {
212    /// メインネットで高さ 1,690,500(strictAggregateTransactionHash)より前。
213    /// 中のトランザクションのハッシュに誤った求め方も許されていたので、中身から求めずに、書いてあったものを持つ
214    V1 {
215        transactions_hash: Hash256,
216    },
217    /// メインネットで高さ 4,759,100(uniqueAggregateTransactionHash)より前。
218    /// 署名の範囲に、中のトランザクションの長さを含まない
219    V2,
220    V3,
221}
222
223impl AggregateVersion {
224    pub fn number(self) -> u8 {
225        match self {
226            Self::V1 { .. } => 1,
227            Self::V2 => 2,
228            Self::V3 => 3,
229        }
230    }
231
232    /// 本体のうち、署名の範囲に入らない後ろの部分の長さ。catapult の `Footer_Size` と `Pre_V3_Footer_Size`。
233    pub(crate) fn footer_size(self) -> usize {
234        match self {
235            Self::V3 => 4,
236            _ => 4 + 4,
237        }
238    }
239}
240
241/// 中のトランザクションのハッシュが、どの求め方と合うか。
242#[derive(Clone, Copy, PartialEq, Eq, Debug)]
243pub enum TransactionsHashCalculation {
244    /// 正しい求め方。バージョン 2 からは、これしか認められない
245    Correct,
246    /// バージョン 1 で許されていた誤った求め方(葉に埋め草を含める、誤った Merkle の根、またはその両方)
247    Legacy,
248    /// どの求め方とも合わない。バージョン 1 には、ネットワークの設定の
249    /// `[corrupt_aggregate_transaction_hashes]` に載せて認めたものがある。
250    /// 署名は書いてあったハッシュにしか掛かっていないので、表示している中身が署名されたものとは限らない
251    Unknown,
252}
253
254/// アグリゲートの本体。中のトランザクションと連署。
255///
256/// 中のトランザクションのハッシュは中身から決まるので持たず、書くときに求める(バージョン 1 を除く)。
257#[derive(Clone, PartialEq, Eq, Debug)]
258pub struct Aggregate {
259    version: AggregateVersion,
260    transactions: Vec<EmbeddedTransaction>,
261    cosignatures: Vec<Cosignature>,
262    /// 中のトランザクションの長さの後ろの予約の部分。catapult は確かめず、署名にもハッシュにも入らないので、
263    /// 読んだ値を持っておく
264    reserved: u32,
265}
266
267impl Aggregate {
268    /// 中のトランザクションから、連署のないアグリゲート(バージョン 3)を作る。アグリゲートは入れ子にできない。
269    pub fn new(transactions: Vec<EmbeddedTransaction>) -> Result<Self, NestedAggregate> {
270        if transactions
271            .iter()
272            .any(|transaction| Body::is_aggregate_type(transaction.body.transaction_type()))
273        {
274            return Err(NestedAggregate);
275        }
276        Ok(Self {
277            version: AggregateVersion::V3,
278            transactions,
279            cosignatures: Vec::new(),
280            reserved: 0,
281        })
282    }
283
284    pub fn version(&self) -> AggregateVersion {
285        self.version
286    }
287
288    pub fn transactions(&self) -> &[EmbeddedTransaction] {
289        &self.transactions
290    }
291
292    pub fn cosignatures(&self) -> &[Cosignature] {
293        &self.cosignatures
294    }
295
296    pub fn add_cosignature(&mut self, cosignature: Cosignature) {
297        self.cosignatures.push(cosignature);
298    }
299
300    /// 連署を外して返す。ハッシュと外側の署名は連署を含まないので、外しても変わらない
301    pub fn take_cosignatures(&mut self) -> Vec<Cosignature> {
302        core::mem::take(&mut self.cosignatures)
303    }
304
305    /// 中のトランザクションのハッシュ。署名はこれに掛かる。
306    /// ふつうは、それぞれのハッシュを葉にした Merkle ツリーの根。バージョン 1 は、書いてあったもの。
307    pub fn transactions_hash(&self) -> Hash256 {
308        match self.version {
309            AggregateVersion::V1 { transactions_hash } => transactions_hash,
310            _ => self.correct_transactions_hash(),
311        }
312    }
313
314    fn correct_transactions_hash(&self) -> Hash256 {
315        let leaves: Vec<_> = self
316            .transactions
317            .iter()
318            .map(EmbeddedTransaction::hash)
319            .collect();
320        merkle::root(&leaves)
321    }
322
323    /// 中のトランザクションのハッシュが、どの求め方と合うか。
324    /// catapult の `AggregateTransactionsHashValidator` と同じ順に確かめる。
325    pub fn transactions_hash_calculation(&self) -> TransactionsHashCalculation {
326        let hash = self.transactions_hash();
327        if hash == self.correct_transactions_hash() {
328            return TransactionsHashCalculation::Correct;
329        }
330        let leaves: Vec<_> = self
331            .transactions
332            .iter()
333            .map(EmbeddedTransaction::hash)
334            .collect();
335        let padded: Vec<_> = self
336            .transactions
337            .iter()
338            .map(EmbeddedTransaction::padded_hash)
339            .collect();
340        if [
341            merkle::root(&padded),
342            merkle::invalid_root(&leaves),
343            merkle::invalid_root(&padded),
344        ]
345        .contains(&hash)
346        {
347            TransactionsHashCalculation::Legacy
348        } else {
349            TransactionsHashCalculation::Unknown
350        }
351    }
352
353    pub(crate) fn encode(&self, out: &mut Vec<u8>) {
354        let mut payload = Vec::new();
355        for transaction in &self.transactions {
356            payload.extend_from_slice(&transaction.padded_bytes());
357        }
358        out.extend_from_slice(&self.transactions_hash().0);
359        out.extend_from_slice(&(payload.len() as u32).to_le_bytes());
360        out.extend_from_slice(&self.reserved.to_le_bytes());
361        out.extend_from_slice(&payload);
362        for cosignature in &self.cosignatures {
363            out.extend_from_slice(&[0; 8]);
364            out.extend_from_slice(&cosignature.signer_public_key.0);
365            out.extend_from_slice(&cosignature.signature.0);
366        }
367    }
368
369    /// catapult の `IsSizeValid` と同じく、中のトランザクションの長さが8の倍数で、
370    /// 残りが連署の長さの倍数になっているものを読む。
371    /// バージョン 2 からは、中のトランザクションのハッシュが正しく求めたものと合わなければ弾く。
372    /// バージョン 1 は、どのハッシュでも読む([`Aggregate::transactions_hash_calculation`] で確かめる)。
373    pub(crate) fn decode(version: u8, bytes: &[u8]) -> Result<Self, DecodeError> {
374        if bytes.len() < FIXED_SIZE {
375            return Err(DecodeError::InvalidBodySize);
376        }
377        let mut reader = Reader(bytes);
378        let transactions_hash = Hash256(reader.array());
379        let payload_size = reader.u32() as usize;
380        let reserved = reader.u32();
381        if !payload_size.is_multiple_of(8)
382            || payload_size > reader.0.len()
383            || !(reader.0.len() - payload_size).is_multiple_of(COSIGNATURE_SIZE)
384        {
385            return Err(DecodeError::InvalidBodySize);
386        }
387        let (mut payload, cosignatures) = reader.0.split_at(payload_size);
388
389        let mut transactions = Vec::new();
390        while !payload.is_empty() {
391            let size = match payload.first_chunk() {
392                Some(size) => u32::from_le_bytes(*size) as usize,
393                None => return Err(DecodeError::InvalidBodySize),
394            };
395            let padded_size = size.next_multiple_of(8);
396            if size < EMBEDDED_HEADER_SIZE || padded_size > payload.len() {
397                return Err(DecodeError::InvalidBodySize);
398            }
399            transactions.push(EmbeddedTransaction::decode(
400                &payload[..size],
401                &payload[size..padded_size],
402            )?);
403            payload = &payload[padded_size..];
404        }
405
406        let cosignatures = cosignatures
407            .chunks(COSIGNATURE_SIZE)
408            .map(|chunk| {
409                let mut reader = Reader(chunk);
410                if reader.u64() != 0 {
411                    return Err(DecodeError::NonZeroReserved);
412                }
413                Ok(Cosignature {
414                    signer_public_key: PublicKey(reader.array()),
415                    signature: Signature(reader.array()),
416                })
417            })
418            .collect::<Result<_, _>>()?;
419
420        let version = match version {
421            1 => AggregateVersion::V1 { transactions_hash },
422            2 => AggregateVersion::V2,
423            _ => AggregateVersion::V3,
424        };
425        let aggregate = Self {
426            version,
427            transactions,
428            cosignatures,
429            reserved,
430        };
431        if aggregate.transactions_hash() != transactions_hash {
432            return Err(DecodeError::TransactionsHashMismatch);
433        }
434        Ok(aggregate)
435    }
436}
437
438/// アグリゲートの中にアグリゲートを入れようとした。
439#[derive(Debug, Clone, PartialEq, Eq)]
440pub struct NestedAggregate;
441
442impl core::fmt::Display for NestedAggregate {
443    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
444        f.write_str("アグリゲートの中にアグリゲートは入れられません")
445    }
446}
447
448impl core::error::Error for NestedAggregate {}
449
450#[cfg(test)]
451mod tests {
452    use heika_core::network::GenerationHashSeed;
453
454    use super::*;
455    use crate::{KeyLink, LinkAction, Transaction};
456
457    // RFC 8032 の 7.1 節にある Ed25519 のテスト 1 と 2 の秘密鍵
458    const SIGNER: &str = "9D61B19DEFFD5A60BA844AF492EC2CC44449C5697B326919703BAC031CAE7F60";
459    const COSIGNER: &str = "4CCD089B28FF96DA9DB6C346EC114E0F5B8A319F35ABA624DA8CF6ED4FB8A6FB";
460
461    /// 外側のトランザクションのヘッダーの長さ
462    const BODY: usize = 128;
463
464    fn signer() -> PrivateKey {
465        SIGNER.parse().unwrap()
466    }
467
468    fn seed() -> GenerationHashSeed {
469        GenerationHashSeed([0x5E; 32])
470    }
471
472    fn link(byte: u8) -> EmbeddedTransaction {
473        EmbeddedTransaction::new(
474            PublicKey::from_private_key(&signer()),
475            NetworkIdentifier::TESTNET,
476            Body::VrfKeyLink(KeyLink {
477                linked_public_key: PublicKey([byte; 32]),
478                link_action: LinkAction::Link,
479            }),
480        )
481    }
482
483    fn aggregate(transactions: Vec<EmbeddedTransaction>) -> Transaction {
484        Transaction::new(
485            PublicKey::from_private_key(&signer()),
486            NetworkIdentifier::TESTNET,
487            0,
488            0,
489            Body::AggregateComplete(Aggregate::new(transactions).unwrap()),
490        )
491    }
492
493    fn body(transaction: &mut Transaction) -> &mut Aggregate {
494        match &mut transaction.body {
495            Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate) => aggregate,
496            _ => unreachable!(),
497        }
498    }
499
500    #[test]
501    fn detaches_a_cosignature_with_its_parent_hash() {
502        let private_key = PrivateKey::from_bytes(&[7; 32]);
503        let parent = Hash256([0x11; 32]);
504        let detached = DetachedCosignature::sign(&private_key, &parent);
505        assert!(detached.verify());
506        let bytes = detached.to_bytes();
507        assert_eq!(bytes[..8], [0; 8]);
508        assert_eq!(bytes[104..], [0x11; 32]);
509        assert_eq!(DetachedCosignature::from_bytes(&bytes), Ok(detached));
510
511        let other = DetachedCosignature {
512            parent_hash: Hash256([0x22; 32]),
513            ..detached
514        };
515        assert!(!other.verify());
516
517        let mut versioned = bytes;
518        versioned[0] = 1;
519        assert_eq!(
520            DetachedCosignature::from_bytes(&versioned),
521            Err(DecodeError::NonZeroReserved)
522        );
523        assert_eq!(
524            DetachedCosignature::from_bytes(&bytes[..135]),
525            Err(DecodeError::InvalidBodySize)
526        );
527    }
528
529    #[test]
530    fn writes_embedded_transactions_with_a_short_header() {
531        let bytes = link(0xAA).to_bytes();
532        assert_eq!(bytes.len(), 81);
533        assert_eq!(bytes[..8], [81, 0, 0, 0, 0, 0, 0, 0]);
534        assert_eq!(bytes[8..40], PublicKey::from_private_key(&signer()).0);
535        assert_eq!(bytes[40..48], [0, 0, 0, 0, 1, 0x98, 0x43, 0x42]);
536        assert_eq!(bytes[48..80], [0xAA; 32]);
537    }
538
539    #[test]
540    fn writes_the_catbuffer_layout() {
541        let transaction = aggregate(vec![link(1), link(2)]);
542        let bytes = transaction.to_bytes();
543        assert_eq!(bytes.len(), BODY + 40 + 2 * 88);
544        assert_eq!(bytes[108..112], [3, 0x98, 0x41, 0x41]);
545        let leaves = [link(1).hash(), link(2).hash()];
546        assert_eq!(bytes[BODY..BODY + 32], merkle::root(&leaves).0);
547        assert_eq!(bytes[BODY + 32..BODY + 40], [176, 0, 0, 0, 0, 0, 0, 0]);
548        // それぞれ 81 バイトを 88 バイトまで0で埋める
549        assert_eq!(bytes[BODY + 40..BODY + 121], link(1).to_bytes());
550        assert_eq!(bytes[BODY + 121..BODY + 128], [0; 7]);
551        assert_eq!(bytes[BODY + 128..BODY + 209], link(2).to_bytes());
552    }
553
554    #[test]
555    fn round_trips_with_cosignatures() {
556        let mut transaction = aggregate(vec![link(1), link(2), link(3)]);
557        transaction.sign(&signer(), &seed()).unwrap();
558        let hash = transaction.hash(&seed());
559        let cosigner: PrivateKey = COSIGNER.parse().unwrap();
560        body(&mut transaction).add_cosignature(Cosignature::sign(&cosigner, &hash));
561        let bytes = transaction.to_bytes();
562        assert_eq!(bytes.len(), BODY + 40 + 3 * 88 + 104);
563        assert_eq!(Transaction::from_bytes(&bytes), Ok(transaction));
564    }
565
566    #[test]
567    fn signs_the_header_and_the_transactions_hash_but_not_the_cosignatures() {
568        let mut transaction = aggregate(vec![link(1)]);
569        transaction.sign(&signer(), &seed()).unwrap();
570        let bytes = transaction.to_bytes();
571        let signature = signer().sign(&[&seed().0, &bytes[108..164]]);
572        assert_eq!(transaction.signature, signature);
573
574        let hash = transaction.hash(&seed());
575        let cosigner: PrivateKey = COSIGNER.parse().unwrap();
576        let cosignature = Cosignature::sign(&cosigner, &hash);
577        assert!(cosignature.verify(&hash));
578        body(&mut transaction).add_cosignature(cosignature);
579        assert_eq!(transaction.hash(&seed()), hash);
580        assert!(transaction.verify(&seed()));
581    }
582
583    #[test]
584    fn a_changed_embedded_transaction_breaks_the_signature() {
585        let mut transaction = aggregate(vec![link(1)]);
586        transaction.sign(&signer(), &seed()).unwrap();
587        let mut changed = aggregate(vec![link(2)]);
588        changed.signature = transaction.signature;
589        assert!(!changed.verify(&seed()));
590    }
591
592    /// 古いバージョンのアグリゲート。テストのために、外からは作れないものを作る
593    fn old(transactions: Vec<EmbeddedTransaction>, version: AggregateVersion) -> Transaction {
594        let mut transaction = aggregate(transactions);
595        body(&mut transaction).version = version;
596        transaction
597    }
598
599    #[test]
600    fn version_2_signs_up_to_the_transactions_hash() {
601        let mut transaction = old(vec![link(1)], AggregateVersion::V2);
602        transaction.sign(&signer(), &seed()).unwrap();
603        let bytes = transaction.to_bytes();
604        assert_eq!(bytes[108], 2);
605        let signature = signer().sign(&[&seed().0, &bytes[108..160]]);
606        assert_eq!(transaction.signature, signature);
607        assert_eq!(Transaction::from_bytes(&bytes), Ok(transaction.clone()));
608
609        // 中のトランザクションの長さは署名されていないので、バージョン 3 と同じ署名にはならない
610        let mut current = aggregate(vec![link(1)]);
611        current.sign(&signer(), &seed()).unwrap();
612        assert_ne!(current.signature, transaction.signature);
613
614        let mut wrong_hash = bytes.clone();
615        wrong_hash[BODY] ^= 1;
616        assert_eq!(
617            Transaction::from_bytes(&wrong_hash),
618            Err(DecodeError::TransactionsHashMismatch)
619        );
620    }
621
622    #[test]
623    fn version_1_keeps_the_written_transactions_hash() {
624        let transactions = vec![link(1), link(2), link(3)];
625        let leaves: Vec<_> = transactions.iter().map(EmbeddedTransaction::hash).collect();
626        let padded: Vec<_> = transactions
627            .iter()
628            .map(EmbeddedTransaction::padded_hash)
629            .collect();
630        for (transactions_hash, calculation) in [
631            (merkle::root(&leaves), TransactionsHashCalculation::Correct),
632            (merkle::root(&padded), TransactionsHashCalculation::Legacy),
633            (
634                merkle::invalid_root(&leaves),
635                TransactionsHashCalculation::Legacy,
636            ),
637            (
638                merkle::invalid_root(&padded),
639                TransactionsHashCalculation::Legacy,
640            ),
641            (Hash256([0xAB; 32]), TransactionsHashCalculation::Unknown),
642        ] {
643            let mut transaction = old(
644                transactions.clone(),
645                AggregateVersion::V1 { transactions_hash },
646            );
647            transaction.sign(&signer(), &seed()).unwrap();
648            let bytes = transaction.to_bytes();
649            assert_eq!(bytes[108], 1);
650            assert_eq!(bytes[BODY..BODY + 32], transactions_hash.0);
651            let read = Transaction::from_bytes(&bytes).unwrap();
652            assert_eq!(read, transaction);
653            assert!(read.verify(&seed()));
654            let Body::AggregateComplete(aggregate) = &read.body else {
655                unreachable!()
656            };
657            assert_eq!(
658                aggregate.transactions_hash_calculation(),
659                calculation,
660                "{transactions_hash}"
661            );
662        }
663    }
664
665    #[test]
666    fn refuses_to_nest_aggregates() {
667        let inner = EmbeddedTransaction::new(
668            PublicKey([1; 32]),
669            NetworkIdentifier::TESTNET,
670            Body::AggregateBonded(Aggregate::new(Vec::new()).unwrap()),
671        );
672        assert_eq!(Aggregate::new(vec![inner]), Err(NestedAggregate));
673    }
674
675    #[test]
676    fn keeps_reserved_bytes_and_padding_like_catapult() {
677        let seed = seed();
678        let mut signed = aggregate(vec![link(1)]);
679        signed.sign(&signer(), &seed).unwrap();
680        let bytes = signed.to_bytes();
681        // アグリゲートの予約の部分と、中のトランザクションの後ろの埋め草は、署名にもハッシュにも入らない
682        for offset in [BODY + 36, bytes.len() - 1] {
683            let mut changed = bytes.clone();
684            changed[offset] = 1;
685            let transaction = Transaction::from_bytes(&changed).unwrap();
686            assert_eq!(transaction.to_bytes(), changed, "offset {offset}");
687            assert!(transaction.verify(&seed), "offset {offset}");
688            assert_eq!(
689                transaction.hash(&seed),
690                signed.hash(&seed),
691                "offset {offset}"
692            );
693        }
694        // 中のトランザクションの予約の部分は、中のトランザクションのハッシュに入る
695        for (index, offset) in [BODY + 40 + 4, BODY + 40 + 40].into_iter().enumerate() {
696            let mut changed = bytes.clone();
697            changed[offset] = 1;
698            assert_eq!(
699                Transaction::from_bytes(&changed),
700                Err(DecodeError::TransactionsHashMismatch),
701                "offset {offset}"
702            );
703            let mut inner = link(1);
704            inner.reserved[index] = 1;
705            let mut resigned = aggregate(vec![inner]);
706            resigned.sign(&signer(), &seed).unwrap();
707            let resigned_bytes = resigned.to_bytes();
708            assert_eq!(resigned_bytes[offset], 1, "offset {offset}");
709            let transaction = Transaction::from_bytes(&resigned_bytes).unwrap();
710            assert_eq!(transaction.to_bytes(), resigned_bytes, "offset {offset}");
711            assert!(transaction.verify(&seed), "offset {offset}");
712            assert_ne!(
713                body(&mut resigned).transactions_hash(),
714                body(&mut signed.clone()).transactions_hash(),
715                "offset {offset}"
716            );
717        }
718    }
719
720    #[test]
721    fn rejects_malformed_aggregates() {
722        let bytes = aggregate(vec![link(1)]).to_bytes();
723        let mut nested = bytes.clone();
724        nested[BODY + 40 + 46..BODY + 40 + 48].copy_from_slice(&0x4141u16.to_le_bytes());
725        let mut wrong_hash = bytes.clone();
726        wrong_hash[BODY] ^= 1;
727        let mut unaligned = bytes.clone();
728        unaligned[BODY + 32] = 81;
729        let mut short_embedded = bytes.clone();
730        short_embedded[BODY + 40] = 40;
731        let mut cosignature_version = [bytes.as_slice(), &[0; 104]].concat();
732        cosignature_version[BODY + 128] = 1;
733        let mut version = bytes.clone();
734        version[108] = 4;
735        for (name, mut bytes, error) in [
736            ("nested", nested, DecodeError::NestedAggregate),
737            (
738                "wrong hash",
739                wrong_hash,
740                DecodeError::TransactionsHashMismatch,
741            ),
742            ("unaligned", unaligned, DecodeError::InvalidBodySize),
743            (
744                "short embedded",
745                short_embedded,
746                DecodeError::InvalidBodySize,
747            ),
748            (
749                "partial cosignature",
750                [bytes.as_slice(), &[0; 8]].concat(),
751                DecodeError::InvalidBodySize,
752            ),
753            (
754                "cosignature version",
755                cosignature_version,
756                DecodeError::NonZeroReserved,
757            ),
758            (
759                "version",
760                version,
761                DecodeError::UnsupportedVersion {
762                    transaction_type: 0x4141,
763                    version: 4,
764                },
765            ),
766        ] {
767            let size = bytes.len() as u32;
768            bytes[..4].copy_from_slice(&size.to_le_bytes());
769            assert_eq!(Transaction::from_bytes(&bytes), Err(error), "{name}");
770        }
771    }
772}