1use alloc::collections::BTreeSet;
11use alloc::vec::Vec;
12use core::fmt;
13
14use heika_core::address::Address;
15use heika_core::key::PublicKey;
16use heika_core::network::{NetworkIdentifier, NetworkParameters};
17
18use crate::aggregate::Aggregate;
19use crate::metadata::Metadata;
20use crate::mosaic::MosaicId;
21use crate::namespace::{NamespaceId, NamespaceRegistrationType, is_valid_namespace_name};
22use crate::restriction::{AccountRestrictionFlags, TransactionType};
23use crate::transfer::UnresolvedAddress;
24use crate::{Body, LinkAction, Transaction};
25
26#[derive(Clone, Copy, PartialEq, Eq, Debug)]
28pub struct Problem {
29 pub location: Location,
30 pub failure: Failure,
31}
32
33impl fmt::Display for Problem {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 match self.location {
36 Location::Transaction => self.failure.fmt(f),
37 Location::Embedded(index) => write!(f, "中の {} 件目: {}", index + 1, self.failure),
38 }
39 }
40}
41
42#[derive(Clone, Copy, PartialEq, Eq, Debug)]
44pub enum Location {
45 Transaction,
47 Embedded(usize),
49}
50
51#[derive(Clone, Copy, PartialEq, Eq, Debug)]
53pub enum Failure {
54 TopLevelNotSupported,
56 ZeroPublicKey,
58 WrongNetwork {
59 expected: NetworkIdentifier,
60 actual: NetworkIdentifier,
61 },
62 InvalidTransactionFee,
64 ZeroAddress,
66 LinkStartEpochInvalid,
68 InvalidLinkRange {
70 start: u32,
71 end: u32,
72 min: u32,
73 max: u32,
74 },
75 TransferMessageTooLarge {
76 size: usize,
77 max: usize,
78 },
79 HashLockInvalidDuration {
81 duration: u64,
82 max: u64,
83 },
84 SecretLockInvalidDuration {
86 duration: u64,
87 max: u64,
88 },
89 ProofSizeOutOfBounds {
90 size: usize,
91 min: usize,
92 max: usize,
93 },
94 SecretMismatch,
96 MetadataValueTooSmall,
98 MetadataValueSizeDeltaTooLarge {
100 delta: i16,
101 size: usize,
102 },
103 MetadataValueTooLarge {
104 size: usize,
105 max: usize,
106 },
107 MosaicInvalidId,
109 MosaicIdMismatch {
111 expected: MosaicId,
112 },
113 MosaicInvalidSupplyChangeAmount,
115 MultisigMultipleDeletes,
117 MultisigRedundantModification,
119 MultisigAccountInBothSets,
121 NamespaceInvalidDuration {
123 duration: u64,
124 min: u64,
125 max: u64,
126 },
127 NamespaceInvalidName,
129 NamespaceNameIdMismatch {
131 expected: NamespaceId,
132 },
133 AccountRestrictionInvalidFlags(AccountRestrictionFlags),
135 AccountRestrictionInvalidValue(TransactionType),
137 AggregateNoTransactions,
138 AggregateTooManyTransactions {
139 count: usize,
140 max: usize,
141 },
142 AggregateTooManyCosignatures {
144 count: usize,
145 max: usize,
146 },
147 AggregateRedundantCosignatures,
149}
150
151impl Failure {
152 pub fn result(&self) -> Option<(&'static str, u32)> {
155 let (name, facility, code) = match self {
157 Self::TopLevelNotSupported => return None,
158 Self::ZeroPublicKey => ("Failure_Core_Zero_Public_Key", 0x43, 12),
159 Self::WrongNetwork { .. } => ("Failure_Core_Wrong_Network", 0x43, 6),
160 Self::InvalidTransactionFee => ("Failure_Core_Invalid_Transaction_Fee", 0x43, 9),
161 Self::ZeroAddress => ("Failure_Core_Zero_Address", 0x43, 11),
162 Self::LinkStartEpochInvalid => ("Failure_Core_Link_Start_Epoch_Invalid", 0x43, 106),
163 Self::InvalidLinkRange { .. } => ("Failure_Core_Invalid_Link_Range", 0x43, 104),
164 Self::TransferMessageTooLarge { .. } => ("Failure_Transfer_Message_Too_Large", 0x54, 1),
165 Self::HashLockInvalidDuration { .. } => ("Failure_LockHash_Invalid_Duration", 0x48, 6),
166 Self::SecretLockInvalidDuration { .. } => {
167 ("Failure_LockSecret_Invalid_Duration", 0x52, 8)
168 }
169 Self::ProofSizeOutOfBounds { .. } => {
170 ("Failure_LockSecret_Proof_Size_Out_Of_Bounds", 0x52, 3)
171 }
172 Self::SecretMismatch => ("Failure_LockSecret_Secret_Mismatch", 0x52, 4),
173 Self::MetadataValueTooSmall => ("Failure_Metadata_Value_Too_Small", 0x44, 1),
174 Self::MetadataValueSizeDeltaTooLarge { .. } => {
175 ("Failure_Metadata_Value_Size_Delta_Too_Large", 0x44, 3)
176 }
177 Self::MetadataValueTooLarge { .. } => ("Failure_Metadata_Value_Too_Large", 0x44, 2),
178 Self::MosaicInvalidId => ("Failure_Mosaic_Invalid_Id", 0x4D, 106),
179 Self::MosaicIdMismatch { .. } => ("Failure_Mosaic_Id_Mismatch", 0x4D, 6),
180 Self::MosaicInvalidSupplyChangeAmount => {
181 ("Failure_Mosaic_Invalid_Supply_Change_Amount", 0x4D, 105)
182 }
183 Self::MultisigMultipleDeletes => ("Failure_Multisig_Multiple_Deletes", 0x55, 2),
184 Self::MultisigRedundantModification => {
185 ("Failure_Multisig_Redundant_Modification", 0x55, 3)
186 }
187 Self::MultisigAccountInBothSets => ("Failure_Multisig_Account_In_Both_Sets", 0x55, 1),
188 Self::NamespaceInvalidDuration { .. } => {
189 ("Failure_Namespace_Invalid_Duration", 0x4E, 1)
190 }
191 Self::NamespaceInvalidName => ("Failure_Namespace_Invalid_Name", 0x4E, 2),
192 Self::NamespaceNameIdMismatch { .. } => ("Failure_Namespace_Name_Id_Mismatch", 0x4E, 3),
193 Self::AccountRestrictionInvalidFlags(_) => (
194 "Failure_RestrictionAccount_Invalid_Restriction_Flags",
195 0x50,
196 1,
197 ),
198 Self::AccountRestrictionInvalidValue(_) => {
199 ("Failure_RestrictionAccount_Invalid_Value", 0x50, 10)
200 }
201 Self::AggregateNoTransactions => ("Failure_Aggregate_No_Transactions", 0x41, 2),
202 Self::AggregateTooManyTransactions { .. } => {
203 ("Failure_Aggregate_Too_Many_Transactions", 0x41, 1)
204 }
205 Self::AggregateTooManyCosignatures { .. } => {
206 ("Failure_Aggregate_Too_Many_Cosignatures", 0x41, 3)
207 }
208 Self::AggregateRedundantCosignatures => {
209 ("Failure_Aggregate_Redundant_Cosignatures", 0x41, 4)
210 }
211 };
212 Some((name, 0x8000_0000 | facility << 16 | code))
213 }
214}
215
216impl fmt::Display for Failure {
217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 match *self {
219 Self::TopLevelNotSupported => {
220 f.write_str("この種類はアグリゲートの中でしか使えません。単独で送ると、ノードは理由を返さずに捨てます")
221 }
222 Self::ZeroPublicKey => f.write_str("公開鍵が0です"),
223 Self::WrongNetwork { expected, actual } => write!(
224 f,
225 "ネットワークが 0x{:02X} ですが、送り先は 0x{:02X} です",
226 actual.0, expected.0
227 ),
228 Self::InvalidTransactionFee => {
229 f.write_str("手数料が、バイト数に u32 の最大値を掛けた額より大きいです")
230 }
231 Self::ZeroAddress => f.write_str("公開鍵が0のアカウントのアドレスです"),
232 Self::LinkStartEpochInvalid => f.write_str("投票鍵の最初のエポックが0です"),
233 Self::InvalidLinkRange {
234 start,
235 end,
236 min,
237 max,
238 } => write!(
239 f,
240 "投票鍵のエポックの範囲 {start}〜{end} は、{min}〜{max} エポックの長さでなければなりません"
241 ),
242 Self::TransferMessageTooLarge { size, max } => write!(
243 f,
244 "メッセージは {max} バイトまでですが、{size} バイトあります"
245 ),
246 Self::HashLockInvalidDuration { duration, max }
247 | Self::SecretLockInvalidDuration { duration, max } => write!(
248 f,
249 "ロックの期間は 1〜{max} ブロックでなければなりませんが、{duration} ブロックです"
250 ),
251 Self::ProofSizeOutOfBounds { size, min, max } => write!(
252 f,
253 "プルーフは {min}〜{max} バイトでなければなりませんが、{size} バイトです"
254 ),
255 Self::SecretMismatch => f.write_str("プルーフのハッシュがシークレットと合いません"),
256 Self::MetadataValueTooSmall => f.write_str("メタデータの値が空です"),
257 Self::MetadataValueSizeDeltaTooLarge { delta, size } => write!(
258 f,
259 "値の長さの変化 {delta} が、値の長さ {size} バイトを超えています"
260 ),
261 Self::MetadataValueTooLarge { size, max } => write!(
262 f,
263 "メタデータの値は {max} バイトまでですが、{size} バイトあります"
264 ),
265 Self::MosaicInvalidId => f.write_str("モザイクの ID が0です"),
266 Self::MosaicIdMismatch { expected } => write!(
267 f,
268 "モザイクの ID が、署名者のアドレスとノンスから求めた {:016X} と合いません",
269 expected.0
270 ),
271 Self::MosaicInvalidSupplyChangeAmount => f.write_str("発行量の増減が0です"),
272 Self::MultisigMultipleDeletes => {
273 f.write_str("連署者は一度に1人しか外せません")
274 }
275 Self::MultisigRedundantModification => {
276 f.write_str("同じ連署者を2回足しています")
277 }
278 Self::MultisigAccountInBothSets => {
279 f.write_str("同じアドレスを、足すほうと外すほうの両方に入れています")
280 }
281 Self::NamespaceInvalidDuration { duration, min, max } => write!(
282 f,
283 "ネームスペースの期間は {min}〜{max} ブロックか、0(無期限)でなければなりませんが、{duration} ブロックです"
284 ),
285 Self::NamespaceInvalidName => f.write_str(
286 "ネームスペースの名前が空か長すぎるか、英小文字、数字、`-`、`_` 以外の文字があります(最初は英小文字か数字)",
287 ),
288 Self::NamespaceNameIdMismatch { expected } => write!(
289 f,
290 "ネームスペースの ID が、親の ID と名前から求めた {:016X} と合いません",
291 expected.0
292 ),
293 Self::AccountRestrictionInvalidFlags(flags) => write!(
294 f,
295 "制限のフラグ 0x{:04X} の組み合わせは使えません(モザイクは受け取る側だけ、トランザクションの種類は送る側だけ)",
296 flags.bits()
297 ),
298 Self::AccountRestrictionInvalidValue(value) => write!(
299 f,
300 "0x{:04X} はトランザクションの種類ではありません",
301 value.0
302 ),
303 Self::AggregateNoTransactions => f.write_str("アグリゲートの中が空です"),
304 Self::AggregateTooManyTransactions { count, max } => write!(
305 f,
306 "アグリゲートの中は {max} 件までですが、{count} 件あります"
307 ),
308 Self::AggregateTooManyCosignatures { count, max } => write!(
309 f,
310 "署名は外側の署名者を含めて {max} 個までですが、{count} 個あります"
311 ),
312 Self::AggregateRedundantCosignatures => {
313 f.write_str("同じアカウントが2回署名しています")
314 }
315 }
316 }
317}
318
319impl Transaction {
320 pub fn validate(&self, parameters: &NetworkParameters) -> Vec<Problem> {
325 let mut checker = Checker {
326 parameters,
327 location: Location::Transaction,
328 problems: Vec::new(),
329 };
330 if !self.body.supports_top_level() {
331 checker.fail(Failure::TopLevelNotSupported);
332 }
333 checker.entity(&self.signer_public_key, self.network);
334 if self.fee > u64::from(u32::MAX).saturating_mul(self.size() as u64) {
336 checker.fail(Failure::InvalidTransactionFee);
337 }
338 checker.body(&self.body, &self.signer_public_key);
339 checker.problems
340 }
341}
342
343struct Checker<'a> {
344 parameters: &'a NetworkParameters,
345 location: Location,
346 problems: Vec<Problem>,
347}
348
349impl Checker<'_> {
350 fn fail(&mut self, failure: Failure) {
351 self.problems.push(Problem {
352 location: self.location,
353 failure,
354 });
355 }
356
357 fn entity(&mut self, signer_public_key: &PublicKey, network: NetworkIdentifier) {
359 self.public_key(signer_public_key);
360 if network != self.parameters.identifier {
361 self.fail(Failure::WrongNetwork {
362 expected: self.parameters.identifier,
363 actual: network,
364 });
365 }
366 }
367
368 fn public_key(&mut self, public_key: &PublicKey) {
369 if public_key.0 == [0; 32] {
370 self.fail(Failure::ZeroPublicKey);
371 }
372 }
373
374 fn address(&mut self, address: &UnresolvedAddress) {
376 let zero = Address::from_public_key(&PublicKey([0; 32]), self.parameters.identifier);
377 if address.0 == zero.0 {
378 self.fail(Failure::ZeroAddress);
379 }
380 }
381
382 fn body(&mut self, body: &Body, signer_public_key: &PublicKey) {
384 let parameters = self.parameters;
385 match body {
386 Body::AccountKeyLink(link) => {
387 if link.link_action == LinkAction::Link {
388 self.public_key(&link.linked_public_key);
389 }
390 }
391 Body::NodeKeyLink(_) | Body::VrfKeyLink(_) => {}
392 Body::VotingKeyLink(link) => {
393 let (min, max) = (
394 parameters.min_voting_key_lifetime,
395 parameters.max_voting_key_lifetime,
396 );
397 if link.start_epoch == 0 {
398 self.fail(Failure::LinkStartEpochInvalid);
399 } else if link.end_epoch < link.start_epoch
400 || !(min..=max).contains(&(link.end_epoch - link.start_epoch).saturating_add(1))
401 {
402 self.fail(Failure::InvalidLinkRange {
403 start: link.start_epoch,
404 end: link.end_epoch,
405 min,
406 max,
407 });
408 }
409 }
410 Body::HashLock(lock) => {
411 let max = parameters.blocks(parameters.max_hash_lock_duration);
412 if lock.duration == 0 || lock.duration > max {
413 self.fail(Failure::HashLockInvalidDuration {
414 duration: lock.duration,
415 max,
416 });
417 }
418 }
419 Body::SecretLock(lock) => {
420 self.address(&lock.recipient_address);
421 let max = parameters.blocks(parameters.max_secret_lock_duration);
422 if lock.duration == 0 || lock.duration > max {
423 self.fail(Failure::SecretLockInvalidDuration {
424 duration: lock.duration,
425 max,
426 });
427 }
428 }
429 Body::SecretProof(proof) => {
430 let (min, max) = (parameters.min_proof_size, parameters.max_proof_size);
431 if !(min..=max).contains(&proof.proof.len()) {
432 self.fail(Failure::ProofSizeOutOfBounds {
433 size: proof.proof.len(),
434 min,
435 max,
436 });
437 } else if proof.hash_algorithm.secret(&proof.proof) != proof.secret {
438 self.fail(Failure::SecretMismatch);
439 }
440 }
441 Body::AccountMetadata(metadata) => {
442 self.address(&metadata.target_address);
443 self.metadata(metadata);
444 }
445 Body::MosaicMetadata(metadata) => self.metadata(&metadata.metadata),
446 Body::NamespaceMetadata(metadata) => self.metadata(&metadata.metadata),
447 Body::MosaicDefinition(definition) => {
448 let owner = Address::from_public_key(signer_public_key, parameters.identifier);
449 let expected = MosaicId::generate(&owner, definition.nonce);
450 if definition.id.0 == 0 {
451 self.fail(Failure::MosaicInvalidId);
452 } else if definition.id != expected {
453 self.fail(Failure::MosaicIdMismatch { expected });
454 }
455 }
456 Body::MosaicSupplyChange(change) => {
457 if change.delta == 0 {
458 self.fail(Failure::MosaicInvalidSupplyChangeAmount);
459 }
460 }
461 Body::MosaicSupplyRevocation(revocation) => self.address(&revocation.source_address),
462 Body::MultisigAccountModification(modification) => {
463 let additions = &modification.address_additions;
464 let deletions = &modification.address_deletions;
465 for address in additions.iter() {
466 self.address(address);
467 }
468 let unique: BTreeSet<_> = additions.iter().map(|address| address.0).collect();
470 if deletions.len() > 1 {
471 self.fail(Failure::MultisigMultipleDeletes);
472 } else if unique.len() != additions.len() {
473 self.fail(Failure::MultisigRedundantModification);
474 } else if deletions.iter().any(|address| unique.contains(&address.0)) {
475 self.fail(Failure::MultisigAccountInBothSets);
476 }
477 }
478 Body::AddressAlias(_) | Body::MosaicAlias(_) => {}
479 Body::NamespaceRegistration(registration) => {
480 let parent_id = match registration.registration_type {
481 NamespaceRegistrationType::Root { duration } => {
482 let min = parameters.blocks(parameters.min_namespace_duration);
483 let max = parameters.blocks(parameters.max_namespace_duration);
484 if duration != 0 && !(min..=max).contains(&duration) {
485 self.fail(Failure::NamespaceInvalidDuration { duration, min, max });
486 }
487 None
488 }
489 NamespaceRegistrationType::Child { parent_id } => Some(parent_id),
490 };
491 let name = ®istration.name;
492 let expected = NamespaceId::generate(parent_id, name);
493 if name.len() > parameters.max_namespace_name_size || !is_valid_namespace_name(name)
494 {
495 self.fail(Failure::NamespaceInvalidName);
496 } else if registration.id != expected {
497 self.fail(Failure::NamespaceNameIdMismatch { expected });
498 }
499 }
500 Body::AccountAddressRestriction(restriction) => {
501 self.restriction_flags(restriction.restriction_flags);
502 }
503 Body::AccountMosaicRestriction(restriction) => {
504 self.restriction_flags(restriction.restriction_flags);
505 }
506 Body::AccountOperationRestriction(restriction) => {
507 self.restriction_flags(restriction.restriction_flags);
508 if let Some(value) = restriction
510 .restriction_additions
511 .iter()
512 .find(|value| value.0 & 0xC000 != 0x4000)
513 {
514 self.fail(Failure::AccountRestrictionInvalidValue(*value));
515 }
516 }
517 Body::MosaicAddressRestriction(_) | Body::MosaicGlobalRestriction(_) => {}
518 Body::Transfer(transfer) => {
519 self.address(transfer.recipient_address());
520 let size = transfer.message().len();
521 if size > parameters.max_message_size {
522 self.fail(Failure::TransferMessageTooLarge {
523 size,
524 max: parameters.max_message_size,
525 });
526 }
527 }
528 Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate) => {
529 self.aggregate(aggregate, signer_public_key);
530 }
531 }
532 }
533
534 fn metadata(&mut self, metadata: &Metadata) {
536 let size = metadata.value.len();
537 if size == 0 {
538 self.fail(Failure::MetadataValueTooSmall);
539 } else if usize::from(metadata.value_size_delta.unsigned_abs()) > size {
540 self.fail(Failure::MetadataValueSizeDeltaTooLarge {
541 delta: metadata.value_size_delta,
542 size,
543 });
544 } else if size > self.parameters.max_metadata_value_size {
545 self.fail(Failure::MetadataValueTooLarge {
546 size,
547 max: self.parameters.max_metadata_value_size,
548 });
549 }
550 }
551
552 fn restriction_flags(&mut self, flags: AccountRestrictionFlags) {
555 let kind = flags.bits()
556 & !(AccountRestrictionFlags::OUTGOING.bits() | AccountRestrictionFlags::BLOCK.bits());
557 let outgoing = flags.contains(AccountRestrictionFlags::OUTGOING);
558 let valid = match kind {
559 0x0001 => true,
560 0x0002 => !outgoing,
561 0x0004 => outgoing,
562 _ => false,
563 };
564 if !valid {
565 self.fail(Failure::AccountRestrictionInvalidFlags(flags));
566 }
567 }
568
569 fn aggregate(&mut self, aggregate: &Aggregate, signer_public_key: &PublicKey) {
571 let parameters = self.parameters;
572 let count = aggregate.transactions().len();
573 let signers: Vec<_> = core::iter::once(signer_public_key)
574 .chain(
575 aggregate
576 .cosignatures()
577 .iter()
578 .map(|cosignature| &cosignature.signer_public_key),
579 )
580 .map(|public_key| public_key.0)
581 .collect();
582 let unique: BTreeSet<_> = signers.iter().collect();
583 if count == 0 {
584 self.fail(Failure::AggregateNoTransactions);
585 } else if count > parameters.max_transactions_per_aggregate {
586 self.fail(Failure::AggregateTooManyTransactions {
587 count,
588 max: parameters.max_transactions_per_aggregate,
589 });
590 } else if signers.len() > parameters.max_cosignatures_per_aggregate {
591 self.fail(Failure::AggregateTooManyCosignatures {
592 count: signers.len(),
593 max: parameters.max_cosignatures_per_aggregate,
594 });
595 } else if unique.len() != signers.len() {
596 self.fail(Failure::AggregateRedundantCosignatures);
597 }
598
599 for (index, transaction) in aggregate.transactions().iter().enumerate() {
600 self.location = Location::Embedded(index);
601 self.entity(&transaction.signer_public_key, transaction.network);
602 self.body(&transaction.body, &transaction.signer_public_key);
603 }
604 self.location = Location::Transaction;
605 }
606}
607
608#[cfg(test)]
609mod tests {
610 use alloc::collections::BTreeMap;
611
612 use heika_core::hash::Hash256;
613 use heika_core::signature::Signature;
614
615 use super::*;
616 use crate::aggregate::{Cosignature, EmbeddedTransaction};
617 use crate::lock::{HashLock, LockHashAlgorithm, SecretProof};
618 use crate::mosaic::{
619 MosaicDefinition, MosaicFlags, MosaicSupplyChange, MosaicSupplyChangeAction,
620 UnresolvedMosaic,
621 };
622 use crate::multisig::MultisigAccountModification;
623 use crate::namespace::NamespaceRegistration;
624 use crate::restriction::AccountRestriction;
625 use crate::transfer::{Transfer, UnresolvedMosaicId};
626 use crate::{KeyLink, VotingKeyLink};
627
628 const NETWORK: NetworkParameters = NetworkParameters::TESTNET;
629
630 fn signer() -> PublicKey {
631 PublicKey([0x11; 32])
632 }
633
634 fn transaction(body: Body) -> Transaction {
635 Transaction::new(signer(), NETWORK.identifier, 0, 0, body)
636 }
637
638 fn failures(body: Body) -> Vec<Failure> {
640 transaction(body)
641 .validate(&NETWORK)
642 .into_iter()
643 .map(|problem| {
644 assert_eq!(problem.location, Location::Transaction);
645 problem.failure
646 })
647 .collect()
648 }
649
650 fn transfer(recipient: [u8; 24], message: usize) -> Body {
651 Body::Transfer(
652 Transfer::new(
653 UnresolvedAddress(recipient),
654 BTreeMap::new(),
655 vec![0; message],
656 )
657 .unwrap(),
658 )
659 }
660
661 fn zero_address() -> [u8; 24] {
662 Address::from_public_key(&PublicKey([0; 32]), NETWORK.identifier).0
663 }
664
665 fn metadata(value_size_delta: i16, value: usize) -> Metadata {
666 Metadata {
667 target_address: UnresolvedAddress([0x98; 24]),
668 scoped_metadata_key: 1,
669 value_size_delta,
670 value: vec![0; value].try_into().unwrap(),
671 }
672 }
673
674 #[test]
675 fn accepts_a_plain_transfer() {
676 assert_eq!(failures(transfer([0x98; 24], 1024)), []);
677 }
678
679 #[test]
680 fn rejects_transfers_to_the_zero_address_and_long_messages() {
681 assert_eq!(
682 failures(transfer(zero_address(), 1025)),
683 [
684 Failure::ZeroAddress,
685 Failure::TransferMessageTooLarge {
686 size: 1025,
687 max: 1024
688 }
689 ]
690 );
691 }
692
693 #[test]
694 fn checks_the_signer_the_network_and_the_fee_first() {
695 let mut transaction = transaction(transfer([0x98; 24], 0));
696 transaction.signer_public_key = PublicKey([0; 32]);
697 transaction.network = NetworkIdentifier::MAINNET;
698 transaction.fee = u64::from(u32::MAX) * transaction.size() as u64 + 1;
699 let failures: Vec<_> = transaction
700 .validate(&NETWORK)
701 .into_iter()
702 .map(|problem| problem.failure)
703 .collect();
704 assert_eq!(
705 failures,
706 [
707 Failure::ZeroPublicKey,
708 Failure::WrongNetwork {
709 expected: NetworkIdentifier::TESTNET,
710 actual: NetworkIdentifier::MAINNET
711 },
712 Failure::InvalidTransactionFee
713 ]
714 );
715 }
716
717 #[test]
718 fn rejects_embeddable_only_types_at_the_top_level() {
719 let body = Body::AccountMetadata(metadata(1, 1));
720 assert_eq!(failures(body.clone()), [Failure::TopLevelNotSupported]);
721 assert_eq!(Failure::TopLevelNotSupported.result(), None);
722
723 let embedded = EmbeddedTransaction::new(signer(), NETWORK.identifier, body);
725 let aggregate = Aggregate::new(vec![embedded]).unwrap();
726 assert_eq!(failures(Body::AggregateComplete(aggregate)), []);
727 }
728
729 #[test]
730 fn checks_voting_key_ranges() {
731 let link = |start_epoch, end_epoch| {
732 Body::VotingKeyLink(VotingKeyLink {
733 linked_public_key: PublicKey([0x22; 32]),
734 start_epoch,
735 end_epoch,
736 link_action: LinkAction::Link,
737 })
738 };
739 assert_eq!(failures(link(1, 28)), []);
741 assert_eq!(failures(link(0, 28)), [Failure::LinkStartEpochInvalid]);
742 let range = |start, end| Failure::InvalidLinkRange {
743 start,
744 end,
745 min: 28,
746 max: 720,
747 };
748 assert_eq!(failures(link(1, 27)), [range(1, 27)]);
749 assert_eq!(failures(link(1, 721)), [range(1, 721)]);
750 assert_eq!(failures(link(10, 9)), [range(10, 9)]);
751 }
752
753 #[test]
754 fn rejects_linking_the_zero_public_key() {
755 let link = |link_action| {
756 Body::AccountKeyLink(KeyLink {
757 linked_public_key: PublicKey([0; 32]),
758 link_action,
759 })
760 };
761 assert_eq!(failures(link(LinkAction::Link)), [Failure::ZeroPublicKey]);
762 assert_eq!(failures(link(LinkAction::Unlink)), []);
763 }
764
765 #[test]
766 fn checks_lock_durations_in_blocks() {
767 let lock = |duration| {
768 Body::HashLock(HashLock {
769 mosaic: UnresolvedMosaic {
770 mosaic_id: UnresolvedMosaicId(1),
771 amount: 10,
772 },
773 duration,
774 hash: Hash256([0; 32]),
775 })
776 };
777 assert_eq!(failures(lock(5_760)), []);
778 assert_eq!(
779 failures(lock(5_761)),
780 [Failure::HashLockInvalidDuration {
781 duration: 5_761,
782 max: 5_760
783 }]
784 );
785 assert_eq!(
786 failures(lock(0)),
787 [Failure::HashLockInvalidDuration {
788 duration: 0,
789 max: 5_760
790 }]
791 );
792 }
793
794 #[test]
795 fn checks_proofs_against_secrets() {
796 let proof = |proof: Vec<u8>, secret| {
797 Body::SecretProof(SecretProof {
798 recipient_address: UnresolvedAddress([0x98; 24]),
799 secret,
800 hash_algorithm: LockHashAlgorithm::Hash256,
801 proof: proof.try_into().unwrap(),
802 })
803 };
804 let secret = LockHashAlgorithm::Hash256.secret(b"proof");
805 assert_eq!(failures(proof(b"proof".to_vec(), secret)), []);
806 assert_eq!(
807 failures(proof(b"other".to_vec(), secret)),
808 [Failure::SecretMismatch]
809 );
810 assert_eq!(
811 failures(proof(vec![0; 1025], secret)),
812 [Failure::ProofSizeOutOfBounds {
813 size: 1025,
814 min: 0,
815 max: 1024
816 }]
817 );
818 }
819
820 #[test]
821 fn checks_metadata_sizes_in_order() {
822 let embedded = |metadata| {
823 let embedded = EmbeddedTransaction::new(
824 signer(),
825 NETWORK.identifier,
826 Body::MosaicMetadata(crate::MosaicMetadata {
827 target_mosaic_id: UnresolvedMosaicId(1),
828 metadata,
829 }),
830 );
831 let problems = transaction(Body::AggregateComplete(
832 Aggregate::new(vec![embedded]).unwrap(),
833 ))
834 .validate(&NETWORK);
835 problems
836 .into_iter()
837 .map(|problem| {
838 assert_eq!(problem.location, Location::Embedded(0));
839 problem.failure
840 })
841 .collect::<Vec<_>>()
842 };
843 assert_eq!(embedded(metadata(-5, 0)), [Failure::MetadataValueTooSmall]);
844 assert_eq!(
845 embedded(metadata(-5, 4)),
846 [Failure::MetadataValueSizeDeltaTooLarge { delta: -5, size: 4 }]
847 );
848 assert_eq!(
849 embedded(metadata(1, 1025)),
850 [Failure::MetadataValueTooLarge {
851 size: 1025,
852 max: 1024
853 }]
854 );
855 }
856
857 #[test]
858 fn checks_mosaic_ids_against_the_signer() {
859 let owner = Address::from_public_key(&signer(), NETWORK.identifier);
860 let definition = |id| {
861 Body::MosaicDefinition(MosaicDefinition {
862 id,
863 duration: 0,
864 nonce: 7,
865 flags: MosaicFlags::from_bits(0).unwrap(),
866 divisibility: 0,
867 })
868 };
869 let expected = MosaicId::generate(&owner, 7);
870 assert_eq!(failures(definition(expected)), []);
871 assert_eq!(
872 failures(definition(MosaicId(0))),
873 [Failure::MosaicInvalidId]
874 );
875 assert_eq!(
876 failures(definition(MosaicId(1))),
877 [Failure::MosaicIdMismatch { expected }]
878 );
879 let change = Body::MosaicSupplyChange(MosaicSupplyChange {
880 mosaic_id: UnresolvedMosaicId(1),
881 delta: 0,
882 action: MosaicSupplyChangeAction::Increase,
883 });
884 assert_eq!(failures(change), [Failure::MosaicInvalidSupplyChangeAmount]);
885 }
886
887 #[test]
888 fn checks_multisig_modifications() {
889 let modification = |additions: Vec<[u8; 24]>, deletions: Vec<[u8; 24]>| {
890 let addresses = |list: Vec<[u8; 24]>| {
891 list.into_iter()
892 .map(UnresolvedAddress)
893 .collect::<Vec<_>>()
894 .try_into()
895 .unwrap()
896 };
897 let body = Body::MultisigAccountModification(MultisigAccountModification {
898 min_removal_delta: 0,
899 min_approval_delta: 0,
900 address_additions: addresses(additions),
901 address_deletions: addresses(deletions),
902 });
903 let embedded = EmbeddedTransaction::new(signer(), NETWORK.identifier, body);
904 transaction(Body::AggregateBonded(
905 Aggregate::new(vec![embedded]).unwrap(),
906 ))
907 .validate(&NETWORK)
908 .into_iter()
909 .map(|problem| problem.failure)
910 .collect::<Vec<_>>()
911 };
912 let (a, b, c) = ([0x98; 24], [0x99; 24], [0x9A; 24]);
913 assert_eq!(modification(vec![a, b], vec![c]), []);
914 assert_eq!(
915 modification(vec![], vec![b, c]),
916 [Failure::MultisigMultipleDeletes]
917 );
918 assert_eq!(
919 modification(vec![a, a], vec![]),
920 [Failure::MultisigRedundantModification]
921 );
922 assert_eq!(
923 modification(vec![a], vec![a]),
924 [Failure::MultisigAccountInBothSets]
925 );
926 assert_eq!(
927 modification(vec![zero_address()], vec![]),
928 [Failure::ZeroAddress]
929 );
930 }
931
932 #[test]
933 fn checks_namespace_names_ids_and_durations() {
934 let root = |name: &[u8], id, duration| {
935 Body::NamespaceRegistration(NamespaceRegistration {
936 registration_type: NamespaceRegistrationType::Root { duration },
937 id,
938 name: name.to_vec().try_into().unwrap(),
939 })
940 };
941 let id = NamespaceId::generate(None, b"heika");
942 assert_eq!(failures(root(b"heika", id, 86_400)), []);
943 assert_eq!(failures(root(b"heika", id, 0)), []);
945 assert_eq!(
946 failures(root(b"heika", id, 86_399)),
947 [Failure::NamespaceInvalidDuration {
948 duration: 86_399,
949 min: 86_400,
950 max: 5_256_000
951 }]
952 );
953 assert_eq!(
954 failures(root(b"Heika", id, 0)),
955 [Failure::NamespaceInvalidName]
956 );
957 assert_eq!(
958 failures(root(&[b'a'; 65], id, 0)),
959 [Failure::NamespaceInvalidName]
960 );
961 assert_eq!(
962 failures(root(b"heika", NamespaceId(1), 0)),
963 [Failure::NamespaceNameIdMismatch { expected: id }]
964 );
965
966 let child = Body::NamespaceRegistration(NamespaceRegistration {
967 registration_type: NamespaceRegistrationType::Child { parent_id: id },
968 id: NamespaceId::generate(Some(id), b"sub"),
969 name: b"sub".to_vec().try_into().unwrap(),
970 });
971 assert_eq!(failures(child), []);
972 }
973
974 #[test]
975 fn checks_account_restriction_flags_and_values() {
976 let flags = |bits| AccountRestrictionFlags::from_bits(bits).unwrap();
977 let mosaic = |bits| {
978 Body::AccountMosaicRestriction(AccountRestriction {
979 restriction_flags: flags(bits),
980 restriction_additions: vec![UnresolvedMosaicId(1)].try_into().unwrap(),
981 restriction_deletions: Vec::new().try_into().unwrap(),
982 })
983 };
984 assert_eq!(failures(mosaic(0x8002)), []);
985 assert_eq!(
986 failures(mosaic(0x4002)),
987 [Failure::AccountRestrictionInvalidFlags(flags(0x4002))]
988 );
989 let operation = |bits, value| {
990 Body::AccountOperationRestriction(AccountRestriction {
991 restriction_flags: flags(bits),
992 restriction_additions: vec![TransactionType(0x4154), TransactionType(value)]
993 .try_into()
994 .unwrap(),
995 restriction_deletions: Vec::new().try_into().unwrap(),
996 })
997 };
998 assert_eq!(failures(operation(0x4004, 0x4141)), []);
999 assert_eq!(
1000 failures(operation(0x0004, 0x8143)),
1001 [
1002 Failure::AccountRestrictionInvalidFlags(flags(0x0004)),
1003 Failure::AccountRestrictionInvalidValue(TransactionType(0x8143))
1004 ]
1005 );
1006 let address = Body::AccountAddressRestriction(AccountRestriction {
1007 restriction_flags: flags(0x0003),
1008 restriction_additions: Vec::new().try_into().unwrap(),
1009 restriction_deletions: Vec::new().try_into().unwrap(),
1010 });
1011 assert_eq!(
1012 failures(address),
1013 [Failure::AccountRestrictionInvalidFlags(flags(0x0003))]
1014 );
1015 }
1016
1017 #[test]
1018 fn checks_aggregate_counts_and_cosigners() {
1019 let embedded =
1020 || EmbeddedTransaction::new(signer(), NETWORK.identifier, transfer([0x98; 24], 0));
1021 assert_eq!(
1022 failures(Body::AggregateComplete(Aggregate::new(Vec::new()).unwrap())),
1023 [Failure::AggregateNoTransactions]
1024 );
1025 assert_eq!(
1026 failures(Body::AggregateComplete(
1027 Aggregate::new(vec![embedded(); 101]).unwrap()
1028 )),
1029 [Failure::AggregateTooManyTransactions {
1030 count: 101,
1031 max: 100
1032 }]
1033 );
1034
1035 let cosigned = |keys: &[u8]| {
1036 let mut aggregate = Aggregate::new(vec![embedded()]).unwrap();
1037 for key in keys {
1038 aggregate.add_cosignature(Cosignature {
1039 signer_public_key: PublicKey([*key; 32]),
1040 signature: Signature([0; 64]),
1041 });
1042 }
1043 failures(Body::AggregateComplete(aggregate))
1044 };
1045 assert_eq!(cosigned(&[0x22]), []);
1046 assert_eq!(cosigned(&[0x11]), [Failure::AggregateRedundantCosignatures]);
1047 let keys: Vec<u8> = (0x20..0x38).collect();
1048 assert_eq!(cosigned(&keys), []);
1049 let keys: Vec<u8> = (0x20..0x39).collect();
1050 assert_eq!(
1051 cosigned(&keys),
1052 [Failure::AggregateTooManyCosignatures { count: 26, max: 25 }]
1053 );
1054 }
1055
1056 #[test]
1057 fn reports_where_in_the_aggregate_the_problem_is() {
1058 let mut wrong = EmbeddedTransaction::new(
1059 signer(),
1060 NetworkIdentifier::MAINNET,
1061 transfer([0x98; 24], 0),
1062 );
1063 let ok = EmbeddedTransaction::new(signer(), NETWORK.identifier, transfer([0x98; 24], 0));
1064 wrong.signer_public_key = PublicKey([0; 32]);
1065 let problems = transaction(Body::AggregateComplete(
1066 Aggregate::new(vec![ok, wrong]).unwrap(),
1067 ))
1068 .validate(&NETWORK);
1069 assert_eq!(
1070 problems,
1071 [
1072 Problem {
1073 location: Location::Embedded(1),
1074 failure: Failure::ZeroPublicKey
1075 },
1076 Problem {
1077 location: Location::Embedded(1),
1078 failure: Failure::WrongNetwork {
1079 expected: NetworkIdentifier::TESTNET,
1080 actual: NetworkIdentifier::MAINNET
1081 }
1082 }
1083 ]
1084 );
1085 assert_eq!(problems[0].to_string(), "中の 2 件目: 公開鍵が0です");
1086 }
1087
1088 #[test]
1089 fn gives_catapult_result_codes() {
1090 let result = |failure: Failure| failure.result().unwrap();
1091 assert_eq!(
1092 result(Failure::TransferMessageTooLarge { size: 0, max: 0 }),
1093 ("Failure_Transfer_Message_Too_Large", 0x8054_0001)
1094 );
1095 assert_eq!(
1096 result(Failure::ZeroPublicKey),
1097 ("Failure_Core_Zero_Public_Key", 0x8043_000C)
1098 );
1099 assert_eq!(
1100 result(Failure::MosaicInvalidId),
1101 ("Failure_Mosaic_Invalid_Id", 0x804D_006A)
1102 );
1103 assert_eq!(
1104 result(Failure::AggregateRedundantCosignatures),
1105 ("Failure_Aggregate_Redundant_Cosignatures", 0x8041_0004)
1106 );
1107 }
1108}