1use std::{
10 collections::{BTreeMap, BTreeSet, HashMap, HashSet},
11 fmt::{Debug, Display, Formatter, Write},
12 hash::Hash,
13 iter::{self},
14};
15
16use anyhow::bail;
17use fastcrypto::{encoding::Base64, hash::HashFunction};
18use iota_protocol_config::ProtocolConfig;
19use iota_sdk_types::{
20 AccountClaimKind, Address, Argument, CanceledTransaction, CertificateDigest, Command,
21 ConsensusCommitDigest, ConsensusCommitPrologueV1, ConsensusDeterminedVersionAssignments,
22 EndOfEpochTransactionKind, Event, GasPayment, GenesisObject, GenesisTransaction, Identifier,
23 Input, MakeMoveVector, MergeCoins, MoveAuthenticator, MoveCall, MoveStruct, ObjectDigest,
24 ObjectId, ObjectReference, Owner, ProgrammableTransaction, Publish, RandomnessRound,
25 RandomnessStateUpdate, SenderSignedTransaction, SharedObjectReference, SignatureScheme,
26 SplitCoins, Transaction, TransactionDenyRulesUpdate, TransactionDigest, TransactionExpiration,
27 TransactionKind, TransactionV1, TransferObjects, TypeTag, Upgrade, UserSignature, Version,
28 crypto::{Intent, IntentMessage, IntentScope, SimpleSignature},
29};
30use itertools::Either;
31use nonempty::{NonEmpty, nonempty};
32use serde::{Deserialize, Serialize};
33use tap::Pipe;
34use tracing::{instrument, trace};
35
36use super::{base_types::*, error::*};
37use crate::{
38 IOTA_CLOCK_OBJECT_SHARED_VERSION, IOTA_SYSTEM_STATE_OBJECT_SHARED_VERSION,
39 committee::{Committee, EpochId},
40 crypto::{
41 AuthoritySignInfo, AuthoritySignInfoTrait, AuthoritySignature,
42 AuthorityStrongQuorumSignInfo, DefaultHash, EmptySignInfo, Signer, zero_ed25519_signature,
43 },
44 execution::SharedInput,
45 message_envelope::{Envelope, Message, TrustedEnvelope, VerifiedEnvelope},
46 messages_checkpoint::CheckpointTimestamp,
47 move_authenticator::MoveAuthenticatorExt,
48 move_public_key::MovePublicKey,
49 object::Object,
50 programmable_transaction_builder::ProgrammableTransactionBuilder,
51 signature::VerifyParams,
52 signature_verification::verify_sender_signed_data_message_signatures,
53};
54
55pub const TEST_ONLY_GAS_UNIT_FOR_TRANSFER: u64 = 10_000;
56pub const TEST_ONLY_GAS_UNIT_FOR_OBJECT_BASICS: u64 = 50_000;
57pub const TEST_ONLY_GAS_UNIT_FOR_PUBLISH: u64 = 50_000;
58pub const TEST_ONLY_GAS_UNIT_FOR_STAKING: u64 = 50_000;
59pub const TEST_ONLY_GAS_UNIT_FOR_GENERIC: u64 = 50_000;
60pub const TEST_ONLY_GAS_UNIT_FOR_SPLIT_COIN: u64 = 10_000;
61pub const TEST_ONLY_GAS_UNIT_FOR_HEAVY_COMPUTATION_STORAGE: u64 = 5_000_000;
66
67pub const GAS_PRICE_FOR_SYSTEM_TX: u64 = 1;
68
69pub const DEFAULT_VALIDATOR_GAS_PRICE: u64 = 1000;
70
71pub const MAX_PROGRAMMABLE_TX_INPUTS: usize = u16::MAX as usize;
73
74const BLOCKED_MOVE_FUNCTIONS: [(ObjectId, &str, &str); 0] = [];
75
76#[cfg(test)]
77#[path = "unit_tests/messages_tests.rs"]
78mod messages_tests;
79
80#[cfg(test)]
81#[path = "unit_tests/claim_account_validity_tests.rs"]
82mod claim_account_validity_tests;
83
84pub type CallArg = Input;
86
87fn input_object_version_validity_check(version: Version) -> UserInputResult {
94 fp_ensure!(
95 version.next().is_ok_and(|next| next.is_valid()),
96 UserInputError::InvalidSequenceNumber
97 );
98
99 Ok(())
100}
101
102pub fn move_core_identifier_validity_check(identifier: &Identifier) -> UserInputResult {
105 fp_ensure!(
106 move_core_types::identifier::Identifier::is_valid(identifier.as_str()),
107 UserInputError::InvalidIdentifier {
108 error: identifier.to_string()
109 }
110 );
111 Ok(())
112}
113
114pub fn type_tags_identifiers_validity_check<'a>(
117 type_tags: impl IntoIterator<Item = &'a TypeTag>,
118) -> UserInputResult {
119 let mut stack: Vec<&TypeTag> = type_tags.into_iter().collect();
120 while let Some(type_tag) = stack.pop() {
121 match type_tag {
122 TypeTag::Vector(inner) => stack.push(inner.as_ref()),
123 TypeTag::Struct(s) => {
124 move_core_identifier_validity_check(s.module())?;
125 move_core_identifier_validity_check(s.name())?;
126 stack.extend(s.type_params());
127 }
128 TypeTag::Bool
129 | TypeTag::U8
130 | TypeTag::U16
131 | TypeTag::U32
132 | TypeTag::U64
133 | TypeTag::U128
134 | TypeTag::U256
135 | TypeTag::Address
136 | TypeTag::Signer => {}
137 }
138 }
139 Ok(())
140}
141
142fn command_identifiers_validity_check(command: &Command) -> UserInputResult {
146 match command {
147 Command::MoveCall(call) => {
148 move_core_identifier_validity_check(&call.module)?;
149 move_core_identifier_validity_check(&call.function)?;
150 type_tags_identifiers_validity_check(&call.type_arguments)
151 }
152 Command::MakeMoveVector(MakeMoveVector {
153 type_tag: Some(type_tag),
154 ..
155 }) => type_tags_identifiers_validity_check([type_tag]),
156 Command::MakeMoveVector(MakeMoveVector { type_tag: None, .. })
157 | Command::TransferObjects(_)
158 | Command::SplitCoins(_)
159 | Command::MergeCoins(_)
160 | Command::Publish(_)
161 | Command::Upgrade(_) => Ok(()),
162 _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
163 }
164}
165
166pub(crate) fn move_authenticator_identifiers_validity_check(
169 authenticator: &impl MoveAuthenticatorExt,
170) -> UserInputResult {
171 type_tags_identifiers_validity_check(authenticator.type_args())
172}
173
174pub fn type_tag_validity_check(
175 tag: &TypeTag,
176 config: &ProtocolConfig,
177 starting_count: &mut usize,
178) -> UserInputResult<()> {
179 let mut stack = vec![(tag, 1)];
180 while let Some((tag, depth)) = stack.pop() {
181 *starting_count += 1;
182 fp_ensure!(
183 *starting_count < config.max_type_arguments() as usize,
184 UserInputError::SizeLimitExceeded {
185 limit: "maximum type arguments in a call transaction".to_string(),
186 value: config.max_type_arguments().to_string()
187 }
188 );
189 fp_ensure!(
190 depth < config.max_type_argument_depth(),
191 UserInputError::SizeLimitExceeded {
192 limit: "maximum type argument depth in a call transaction".to_string(),
193 value: config.max_type_argument_depth().to_string()
194 }
195 );
196 match tag {
197 TypeTag::Bool
198 | TypeTag::U8
199 | TypeTag::U64
200 | TypeTag::U128
201 | TypeTag::Address
202 | TypeTag::Signer
203 | TypeTag::U16
204 | TypeTag::U32
205 | TypeTag::U256 => (),
206 TypeTag::Vector(t) => {
207 stack.push((t, depth + 1));
208 }
209 TypeTag::Struct(s) => {
210 let next_depth = depth + 1;
211 if config.validate_identifier_inputs() {
212 fp_ensure!(
213 Identifier::is_valid(s.module().as_str()),
214 UserInputError::InvalidIdentifier {
215 error: s.module().as_str().to_owned()
216 }
217 );
218 fp_ensure!(
219 Identifier::is_valid(s.name().as_str()),
220 UserInputError::InvalidIdentifier {
221 error: s.name().as_str().to_owned()
222 }
223 );
224 }
225 stack.extend(s.type_params().iter().map(|t| (t, next_depth)));
226 }
227 }
228 }
229 Ok(())
230}
231
232pub(crate) trait EndOfEpochTransactionKindExt {
236 fn input_objects(&self) -> Vec<InputObjectKind>;
237 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
238}
239
240impl EndOfEpochTransactionKindExt for EndOfEpochTransactionKind {
241 fn input_objects(&self) -> Vec<InputObjectKind> {
242 match self {
243 Self::ChangeEpoch(_)
244 | Self::ChangeEpochV2(_)
245 | Self::ChangeEpochV3(_)
246 | Self::ChangeEpochV4(_) => {
247 vec![InputObjectKind::SharedMoveObject {
248 id: ObjectId::SYSTEM_STATE,
249 initial_shared_version: IOTA_SYSTEM_STATE_OBJECT_SHARED_VERSION,
250 mutable: true,
251 }]
252 }
253 Self::TransactionDenyRulesCreate => vec![],
256 _ => unimplemented!(
257 "a new EndOfEpochTransactionKind enum variant was added and needs to be handled"
258 ),
259 }
260 }
261
262 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
263 match self {
264 Self::ChangeEpoch(_) => {
265 if config.protocol_defined_base_fee() {
266 return Err(UserInputError::Unsupported(
267 "protocol defined base fee not supported".to_string(),
268 ));
269 }
270 if config.select_committee_from_eligible_validators() {
271 return Err(UserInputError::Unsupported(
272 "selecting committee only among validators supporting the protocol version not supported".to_string(),
273 ));
274 }
275 if config.pass_validator_scores_to_advance_epoch() {
276 return Err(UserInputError::Unsupported(
277 "passing of validator scores not supported".to_string(),
278 ));
279 }
280 if config.adjust_rewards_by_score() {
281 return Err(UserInputError::Unsupported(
282 "adjusting rewards by score not supported".to_string(),
283 ));
284 }
285 }
286 Self::ChangeEpochV2(_) => {
287 if !config.protocol_defined_base_fee() {
288 return Err(UserInputError::Unsupported(
289 "protocol defined base fee required".to_string(),
290 ));
291 }
292 if config.select_committee_from_eligible_validators() {
293 return Err(UserInputError::Unsupported(
294 "selecting committee only among validators supporting the protocol version not supported".to_string(),
295 ));
296 }
297 if config.pass_validator_scores_to_advance_epoch() {
298 return Err(UserInputError::Unsupported(
299 "passing of validator scores not supported".to_string(),
300 ));
301 }
302 if config.adjust_rewards_by_score() {
303 return Err(UserInputError::Unsupported(
304 "adjusting rewards by score not supported".to_string(),
305 ));
306 }
307 }
308 Self::ChangeEpochV3(_) => {
309 if !config.protocol_defined_base_fee() {
310 return Err(UserInputError::Unsupported(
311 "protocol defined base fee required".to_string(),
312 ));
313 }
314 if !config.select_committee_from_eligible_validators() {
315 return Err(UserInputError::Unsupported(
316 "selecting committee only among validators supporting the protocol version required".to_string(),
317 ));
318 }
319 if config.pass_validator_scores_to_advance_epoch() {
320 return Err(UserInputError::Unsupported(
321 "passing of validator scores not supported".to_string(),
322 ));
323 }
324 if config.adjust_rewards_by_score() {
325 return Err(UserInputError::Unsupported(
326 "adjusting rewards by score not supported".to_string(),
327 ));
328 }
329 }
330 Self::ChangeEpochV4(_) => {
331 if !config.protocol_defined_base_fee() {
332 return Err(UserInputError::Unsupported(
333 "protocol defined base fee required".to_string(),
334 ));
335 }
336 if !config.select_committee_from_eligible_validators() {
337 return Err(UserInputError::Unsupported(
338 "selecting committee only among validators supporting the protocol version required".to_string(),
339 ));
340 }
341 if !config.pass_validator_scores_to_advance_epoch() {
342 return Err(UserInputError::Unsupported(
343 "passing of validator scores required".to_string(),
344 ));
345 }
346 }
347 Self::TransactionDenyRulesCreate => {
348 if !config.enable_pcool_flow() {
349 return Err(UserInputError::Unsupported(
350 "on-chain deny rule governance not supported at current protocol version"
351 .to_string(),
352 ));
353 }
354 }
355 _ => unimplemented!(
356 "a new EndOfEpochTransactionKind enum variant was added and needs to be handled"
357 ),
358 }
359 Ok(())
360 }
361}
362
363mod call_arg_ext {
364 pub trait Sealed {}
365 impl Sealed for super::CallArg {}
366}
367
368pub trait CallArgExt: Sized + call_arg_ext::Sealed {
370 fn input_object_kind(&self) -> Option<InputObjectKind>;
373
374 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
376}
377
378impl CallArgExt for CallArg {
379 fn input_object_kind(&self) -> Option<InputObjectKind> {
380 match self {
381 CallArg::ImmutableOrOwned(object_ref) => {
382 Some(InputObjectKind::ImmOrOwnedMoveObject(*object_ref))
383 }
384 CallArg::Shared(SharedObjectReference {
385 object_id,
386 initial_shared_version,
387 mutable,
388 }) => Some(InputObjectKind::SharedMoveObject {
389 id: *object_id,
390 initial_shared_version: *initial_shared_version,
391 mutable: *mutable,
392 }),
393 CallArg::Pure(_) | CallArg::Receiving(_) | CallArg::TransactionDependency(_) => None,
394 _ => unimplemented!("a new CallArg enum variant was added and needs to be handled"),
395 }
396 }
397
398 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
399 match self {
400 CallArg::TransactionDependency(_) => {
401 fp_ensure!(
402 config.enable_transaction_dependencies(),
403 UserInputError::Unsupported(
404 "transaction dependency inputs are not enabled".to_string()
405 )
406 );
407 }
408 CallArg::Pure(bytes) => {
409 fp_ensure!(
410 bytes.len() < config.max_pure_argument_size() as usize,
411 UserInputError::SizeLimitExceeded {
412 limit: "maximum pure argument size".to_string(),
413 value: config.max_pure_argument_size().to_string()
414 }
415 );
416 }
417 CallArg::ImmutableOrOwned(ObjectReference { version, .. })
418 | CallArg::Receiving(ObjectReference { version, .. })
419 | CallArg::Shared(SharedObjectReference {
420 initial_shared_version: version,
421 ..
422 }) => {
423 if config.validate_input_object_versions() {
424 input_object_version_validity_check(*version)?;
425 }
426 }
427 _ => unimplemented!("a new CallArg enum variant was added and needs to be handled"),
428 }
429 Ok(())
430 }
431}
432
433pub(crate) fn add_type_tag_packages(packages: &mut BTreeSet<ObjectId>, type_argument: &TypeTag) {
435 let mut stack = vec![type_argument];
436 while let Some(cur) = stack.pop() {
437 match cur {
438 TypeTag::U8
439 | TypeTag::U16
440 | TypeTag::U32
441 | TypeTag::U64
442 | TypeTag::U128
443 | TypeTag::U256
444 | TypeTag::Bool
445 | TypeTag::Address
446 | TypeTag::Signer => (),
447 TypeTag::Vector(inner) => stack.push(inner),
448 TypeTag::Struct(struct_tag) => {
449 packages.insert(ObjectId::new(struct_tag.address().into_bytes()));
450 stack.extend(struct_tag.type_params().iter())
451 }
452 }
453 }
454}
455
456mod move_call_ext {
457 pub trait Sealed {}
458 impl Sealed for super::MoveCall {}
459}
460
461pub trait MoveCallExt: Sized + move_call_ext::Sealed {
462 fn input_objects(&self) -> Vec<InputObjectKind>;
463 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
464 fn is_input_arg_used(&self, arg: usize) -> bool;
465}
466
467impl MoveCallExt for MoveCall {
468 fn input_objects(&self) -> Vec<InputObjectKind> {
469 let mut packages = BTreeSet::from([self.package]);
470 for type_argument in &self.type_arguments {
471 add_type_tag_packages(&mut packages, type_argument);
472 }
473 packages
474 .into_iter()
475 .map(InputObjectKind::MovePackage)
476 .collect()
477 }
478
479 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
480 let is_blocked = BLOCKED_MOVE_FUNCTIONS.contains(&(
481 self.package,
482 self.module.as_str(),
483 self.function.as_str(),
484 ));
485 fp_ensure!(!is_blocked, UserInputError::BlockedMoveFunction);
486 let mut type_arguments_count = 0;
487 for tag in &self.type_arguments {
488 type_tag_validity_check(tag, config, &mut type_arguments_count)?;
489 }
490 fp_ensure!(
491 self.arguments.len() < config.max_arguments() as usize,
492 UserInputError::SizeLimitExceeded {
493 limit: "maximum arguments in a move call".to_string(),
494 value: config.max_arguments().to_string()
495 }
496 );
497 if config.validate_identifier_inputs() {
498 fp_ensure!(
499 Identifier::is_valid(&self.module),
500 UserInputError::InvalidIdentifier {
501 error: self.module.to_string()
502 }
503 );
504 fp_ensure!(
505 Identifier::is_valid(&self.function),
506 UserInputError::InvalidIdentifier {
507 error: self.function.to_string()
508 }
509 );
510 }
511 Ok(())
512 }
513
514 fn is_input_arg_used(&self, arg: usize) -> bool {
515 self.arguments
516 .iter()
517 .any(|a| matches!(a, Argument::Input(inp) if usize::from(*inp) == arg))
518 }
519}
520
521mod command_ext {
522 pub trait Sealed {}
523 impl Sealed for super::Command {}
524}
525
526pub trait CommandExt: Sized + command_ext::Sealed {
527 fn input_objects(&self) -> Vec<InputObjectKind>;
528 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
529 fn non_system_packages_to_be_published(&self) -> Option<&Vec<Vec<u8>>>;
530 fn is_input_arg_used(&self, input_arg: usize) -> bool;
531}
532
533impl CommandExt for Command {
534 fn input_objects(&self) -> Vec<InputObjectKind> {
535 match self {
536 Command::MoveCall(cmd) => cmd.input_objects(),
537 Command::Upgrade(cmd) => cmd
538 .dependencies
539 .iter()
540 .map(|id| InputObjectKind::MovePackage(*id))
541 .chain(Some(InputObjectKind::MovePackage(cmd.package)))
542 .collect(),
543 Command::Publish(cmd) => cmd
544 .dependencies
545 .iter()
546 .map(|id| InputObjectKind::MovePackage(*id))
547 .collect(),
548 Command::MakeMoveVector(MakeMoveVector {
549 type_tag: Some(t), ..
550 }) => {
551 let mut packages = BTreeSet::new();
552 add_type_tag_packages(&mut packages, t);
553 packages
554 .into_iter()
555 .map(InputObjectKind::MovePackage)
556 .collect()
557 }
558 Command::MakeMoveVector(MakeMoveVector { type_tag: None, .. })
559 | Command::TransferObjects(_)
560 | Command::SplitCoins(_)
561 | Command::MergeCoins(_) => vec![],
562 _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
563 }
564 }
565
566 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
567 match self {
568 Command::MoveCall(call) => call.validity_check(config)?,
569 Command::TransferObjects(TransferObjects { objects: args, .. })
570 | Command::MergeCoins(MergeCoins {
571 coins_to_merge: args,
572 ..
573 })
574 | Command::SplitCoins(SplitCoins { amounts: args, .. }) => {
575 fp_ensure!(!args.is_empty(), UserInputError::EmptyCommandInput);
576 fp_ensure!(
577 args.len() < config.max_arguments() as usize,
578 UserInputError::SizeLimitExceeded {
579 limit: "maximum arguments in a programmable transaction command"
580 .to_string(),
581 value: config.max_arguments().to_string()
582 }
583 );
584 }
585 Command::MakeMoveVector(MakeMoveVector {
586 type_tag: ty_opt,
587 elements: args,
588 }) => {
589 fp_ensure!(
591 ty_opt.is_some() || !args.is_empty(),
592 UserInputError::EmptyCommandInput
593 );
594 if let Some(ty) = ty_opt {
595 let mut type_arguments_count = 0;
596 type_tag_validity_check(ty, config, &mut type_arguments_count)?;
597 }
598 fp_ensure!(
599 args.len() < config.max_arguments() as usize,
600 UserInputError::SizeLimitExceeded {
601 limit: "maximum arguments in a programmable transaction command"
602 .to_string(),
603 value: config.max_arguments().to_string()
604 }
605 );
606 }
607 Command::Publish(Publish {
608 modules,
609 dependencies,
610 })
611 | Command::Upgrade(Upgrade {
612 modules,
613 dependencies,
614 ..
615 }) => {
616 fp_ensure!(!modules.is_empty(), UserInputError::EmptyCommandInput);
617 fp_ensure!(
618 modules.len() < config.max_modules_in_publish() as usize,
619 UserInputError::SizeLimitExceeded {
620 limit: "maximum modules in a programmable transaction upgrade command"
621 .to_string(),
622 value: config.max_modules_in_publish().to_string()
623 }
624 );
625 if let Some(max_package_dependencies) = config.max_package_dependencies_as_option()
626 {
627 fp_ensure!(
628 dependencies.len() < max_package_dependencies as usize,
629 UserInputError::SizeLimitExceeded {
630 limit: "maximum package dependencies".to_string(),
631 value: max_package_dependencies.to_string()
632 }
633 );
634 };
635 }
636 _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
637 };
638 if config.disallow_self_identifier_in_transactions() {
639 command_identifiers_validity_check(self)?;
640 }
641
642 Ok(())
643 }
644
645 fn non_system_packages_to_be_published(&self) -> Option<&Vec<Vec<u8>>> {
646 match self {
647 Command::Publish(cmd) => Some(&cmd.modules),
648 Command::Upgrade(cmd) => Some(&cmd.modules),
649 Command::MoveCall(_)
650 | Command::TransferObjects(_)
651 | Command::SplitCoins(_)
652 | Command::MergeCoins(_)
653 | Command::MakeMoveVector(_) => None,
654 _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
655 }
656 }
657
658 fn is_input_arg_used(&self, input_arg: usize) -> bool {
659 match self {
660 Command::MoveCall(c) => c.is_input_arg_used(input_arg),
661 Command::TransferObjects(TransferObjects {
662 objects: args,
663 address: arg,
664 })
665 | Command::MergeCoins(MergeCoins {
666 coins_to_merge: args,
667 coin: arg,
668 })
669 | Command::SplitCoins(SplitCoins {
670 amounts: args,
671 coin: arg,
672 }) => args.iter().chain(iter::once(arg)).any(
673 |arg| matches!(arg, Argument::Input(input) if usize::from(*input) == input_arg),
674 ),
675 Command::MakeMoveVector(MakeMoveVector { elements, .. }) => elements.iter().any(
676 |arg| matches!(arg, Argument::Input(input) if usize::from(*input) == input_arg),
677 ),
678 Command::Upgrade(Upgrade { ticket, .. }) => {
679 matches!(ticket, Argument::Input(input) if usize::from(*input) == input_arg)
680 }
681 Command::Publish(_) => false,
682 _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
683 }
684 }
685}
686
687fn command_arguments(command: &Command) -> Box<dyn Iterator<Item = &Argument> + '_> {
689 match command {
690 Command::MoveCall(c) => Box::new(c.arguments.iter()),
691 Command::TransferObjects(TransferObjects { objects, address }) => {
692 Box::new(objects.iter().chain(iter::once(address)))
693 }
694 Command::SplitCoins(SplitCoins { coin, amounts }) => {
695 Box::new(iter::once(coin).chain(amounts))
696 }
697 Command::MergeCoins(MergeCoins {
698 coin,
699 coins_to_merge,
700 }) => Box::new(iter::once(coin).chain(coins_to_merge)),
701 Command::MakeMoveVector(MakeMoveVector { elements, .. }) => Box::new(elements.iter()),
702 Command::Upgrade(Upgrade { ticket, .. }) => Box::new(iter::once(ticket)),
703 Command::Publish(_) => Box::new(iter::empty()),
704 _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
705 }
706}
707
708mod programmable_transaction_ext {
709 pub trait Sealed {}
710 impl Sealed for super::ProgrammableTransaction {}
711}
712
713pub trait ProgrammableTransactionExt: Sized + programmable_transaction_ext::Sealed {
714 fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>>;
715 fn receiving_objects(&self) -> Vec<ObjectReference>;
716 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
717 fn validate_argument_indices(&self) -> UserInputResult;
718 fn dependency_input(&self) -> Option<(usize, TransactionDigest)>;
720 fn transaction_dependency(&self) -> Option<TransactionDigest>;
722 fn validate_transaction_dependency_inputs(&self) -> UserInputResult;
725 fn shared_input_objects(&self) -> impl Iterator<Item = SharedObjectReference>;
726 fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)>;
727 fn non_system_packages_to_be_published(&self) -> impl Iterator<Item = &Vec<Vec<u8>>>;
728}
729
730impl ProgrammableTransactionExt for ProgrammableTransaction {
731 fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>> {
732 let ProgrammableTransaction { inputs, commands } = self;
733 let input_arg_objects = inputs
734 .iter()
735 .filter_map(|arg| arg.input_object_kind())
736 .collect::<Vec<_>>();
737 let mut used = HashSet::new();
739 if !input_arg_objects.iter().all(|o| used.insert(o.object_id())) {
740 return Err(UserInputError::DuplicateObjectRefInput);
741 }
742 let command_input_objects: BTreeSet<InputObjectKind> = commands
744 .iter()
745 .flat_map(|command| command.input_objects())
746 .collect();
747 Ok(input_arg_objects
748 .into_iter()
749 .chain(command_input_objects)
750 .collect())
751 }
752
753 fn receiving_objects(&self) -> Vec<ObjectReference> {
754 let ProgrammableTransaction { inputs, .. } = self;
755 inputs
756 .iter()
757 .filter_map(|arg| arg.as_opt_receiving().copied())
758 .collect()
759 }
760
761 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
762 let ProgrammableTransaction { inputs, commands } = self;
763 fp_ensure!(
764 commands.len() < config.max_programmable_tx_commands() as usize,
765 UserInputError::SizeLimitExceeded {
766 limit: "maximum commands in a programmable transaction".to_string(),
767 value: config.max_programmable_tx_commands().to_string()
768 }
769 );
770 fp_ensure!(
773 inputs.len() <= MAX_PROGRAMMABLE_TX_INPUTS,
774 UserInputError::SizeLimitExceeded {
775 limit: "maximum inputs in a programmable transaction".to_string(),
776 value: MAX_PROGRAMMABLE_TX_INPUTS.to_string(),
777 }
778 );
779 let total_inputs = self.input_objects()?.len() + self.receiving_objects().len();
780 fp_ensure!(
781 total_inputs <= config.max_input_objects() as usize,
782 UserInputError::SizeLimitExceeded {
783 limit: "maximum input + receiving objects in a transaction".to_string(),
784 value: config.max_input_objects().to_string()
785 }
786 );
787 for input in inputs {
788 input.validity_check(config)?
789 }
790 self.validate_transaction_dependency_inputs()?;
791 if let Some(max_publish_commands) = config.max_publish_or_upgrade_per_ptb_as_option() {
792 let publish_count = commands
793 .iter()
794 .filter(|c| c.is_publish() || c.is_upgrade())
795 .count() as u64;
796 fp_ensure!(
797 publish_count <= max_publish_commands,
798 UserInputError::MaxPublishCountExceeded {
799 max_publish_commands,
800 publish_count,
801 }
802 );
803 }
804 for command in commands {
805 command.validity_check(config)?;
806 }
807 if config.validate_ptb_argument_indices() {
808 self.validate_argument_indices()?;
809 }
810
811 if let Some(random_index) = inputs.iter().position(|obj| {
815 matches!(obj, CallArg::Shared(SharedObjectReference { object_id, .. }) if *object_id == ObjectId::RANDOMNESS_STATE)
816 }) {
817 let mut used_random_object = false;
818 for command in commands {
819 if !used_random_object {
820 used_random_object = command.is_input_arg_used(random_index);
821 } else {
822 fp_ensure!(
823 command.is_transfer_objects() || command.is_merge_coins(),
824 UserInputError::PostRandomCommandRestrictions
825 );
826 }
827 }
828 }
829
830 Ok(())
831 }
832
833 fn dependency_input(&self) -> Option<(usize, TransactionDigest)> {
834 self.inputs
835 .iter()
836 .enumerate()
837 .find_map(|(index, input)| match input {
838 CallArg::TransactionDependency(digest) => Some((index, *digest)),
839 _ => None,
840 })
841 }
842
843 fn transaction_dependency(&self) -> Option<TransactionDigest> {
844 self.dependency_input().map(|(_, digest)| digest)
845 }
846
847 fn validate_transaction_dependency_inputs(&self) -> UserInputResult {
848 let dep_index = match self.dependency_input() {
849 Some((index, _)) => index,
850 None => return Ok(()),
851 };
852 fp_ensure!(
854 self.inputs[dep_index + 1..]
855 .iter()
856 .all(|input| !matches!(input, CallArg::TransactionDependency(_))),
857 UserInputError::SizeLimitExceeded {
858 limit: "maximum transaction dependency inputs in a programmable transaction"
859 .to_string(),
860 value: "1".to_string(),
861 }
862 );
863 for (command_idx, command) in self.commands.iter().enumerate() {
865 for (argument_idx, argument) in command_arguments(command).enumerate() {
866 if let Argument::Input(index) = argument {
867 if *index as usize == dep_index {
868 return Err(UserInputError::TransactionDependencyInputUsed {
869 command_idx,
870 argument_idx,
871 });
872 }
873 }
874 }
875 }
876 Ok(())
877 }
878
879 fn validate_argument_indices(&self) -> UserInputResult {
880 for (command_idx, command) in self.commands.iter().enumerate() {
881 for (argument_idx, argument) in command_arguments(command).enumerate() {
882 let index = match argument {
883 Argument::Input(index) if *index as usize >= self.inputs.len() => *index,
884 Argument::Result(index) | Argument::NestedResult(index, _)
885 if *index as usize >= command_idx =>
886 {
887 *index
888 }
889 Argument::Gas
890 | Argument::Input(_)
891 | Argument::Result(_)
892 | Argument::NestedResult(_, _) => continue,
893 _ => unimplemented!(
894 "a new Argument enum variant was added and needs to be handled"
895 ),
896 };
897 return Err(UserInputError::InvalidArgumentIndex {
898 command_idx,
899 argument_idx,
900 index,
901 });
902 }
903 }
904 Ok(())
905 }
906
907 fn shared_input_objects(&self) -> impl Iterator<Item = SharedObjectReference> {
908 self.inputs.iter().filter_map(|arg| match arg {
909 CallArg::Shared(shared) => Some(*shared),
910 CallArg::Pure(_)
911 | CallArg::Receiving(_)
912 | CallArg::ImmutableOrOwned(_)
913 | CallArg::TransactionDependency(_) => None,
914 _ => unimplemented!("a new CallArg enum variant was added and needs to be handled"),
915 })
916 }
917
918 fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)> {
919 self.commands
920 .iter()
921 .filter_map(|command| match command {
922 Command::MoveCall(m) => Some((&m.package, m.module.as_str(), m.function.as_str())),
923 _ => None,
924 })
925 .collect()
926 }
927
928 fn non_system_packages_to_be_published(&self) -> impl Iterator<Item = &Vec<Vec<u8>>> {
929 self.commands
930 .iter()
931 .filter_map(|q| q.non_system_packages_to_be_published())
932 }
933}
934
935fn left_union_shared_input_objects(
939 this: &mut SharedObjectReference,
940 other: &SharedObjectReference,
941) -> UserInputResult<()> {
942 fp_ensure!(
943 this.object_id == other.object_id,
944 UserInputError::SharedObjectIdMismatch
945 );
946 fp_ensure!(
947 this.initial_shared_version == other.initial_shared_version,
948 UserInputError::SharedObjectStartingVersionMismatch
949 );
950
951 if !this.mutable && other.mutable {
952 this.mutable = other.mutable;
953 }
954
955 Ok(())
956}
957
958mod transaction_kind_ext {
959 pub trait Sealed {}
960 impl Sealed for super::TransactionKind {}
961}
962
963pub trait TransactionKindExt: Sized + transaction_kind_ext::Sealed {
964 fn get_advance_epoch_tx_gas_summary(&self) -> Option<(u64, u64)>;
968 fn contains_shared_object(&self) -> bool;
970 fn shared_input_objects(&self) -> impl Iterator<Item = SharedObjectReference> + '_;
973 fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)>;
976 fn receiving_objects(&self) -> Vec<ObjectReference>;
978 fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>>;
984 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
986 fn iter_commands(&self) -> impl Iterator<Item = &Command>;
988 fn name(&self) -> &'static str;
990}
991
992impl TransactionKindExt for TransactionKind {
993 fn get_advance_epoch_tx_gas_summary(&self) -> Option<(u64, u64)> {
994 match self {
995 Self::EndOfEpoch(txns) => {
996 match txns.last().expect("at least one end-of-epoch txn required") {
997 EndOfEpochTransactionKind::ChangeEpoch(e) => {
998 Some((e.computation_charge + e.storage_charge, e.storage_rebate))
999 }
1000 EndOfEpochTransactionKind::ChangeEpochV2(e) => {
1001 Some((e.computation_charge + e.storage_charge, e.storage_rebate))
1002 }
1003 EndOfEpochTransactionKind::ChangeEpochV3(e) => {
1004 Some((e.computation_charge + e.storage_charge, e.storage_rebate))
1005 }
1006 EndOfEpochTransactionKind::ChangeEpochV4(e) => {
1007 Some((e.computation_charge + e.storage_charge, e.storage_rebate))
1008 }
1009 EndOfEpochTransactionKind::TransactionDenyRulesCreate => None,
1012 _ => unimplemented!(
1013 "a new EndOfEpochTransactionKind enum variant was added and needs to be handled"
1014 ),
1015 }
1016 }
1017 _ => None,
1018 }
1019 }
1020
1021 fn contains_shared_object(&self) -> bool {
1022 self.shared_input_objects().next().is_some()
1023 }
1024
1025 fn shared_input_objects(&self) -> impl Iterator<Item = SharedObjectReference> + '_ {
1026 match &self {
1027 Self::ConsensusCommitPrologueV1(_) => Either::Left(Either::Left(iter::once(
1028 SharedObjectReference::new(ObjectId::CLOCK, IOTA_CLOCK_OBJECT_SHARED_VERSION, true),
1029 ))),
1030 #[allow(deprecated)]
1031 Self::AuthenticatorStateUpdateV1Deprecated => {
1032 Either::Right(Either::Right(iter::empty()))
1036 }
1037 Self::RandomnessStateUpdate(update) => {
1038 Either::Left(Either::Left(iter::once(SharedObjectReference::new(
1039 ObjectId::RANDOMNESS_STATE,
1040 update.randomness_obj_initial_shared_version,
1041 true,
1042 ))))
1043 }
1044 Self::TransactionDenyRulesUpdate(update) => {
1045 Either::Left(Either::Left(iter::once(SharedObjectReference::new(
1046 ObjectId::TRANSACTION_DENY_RULES,
1047 update.deny_rules_obj_initial_shared_version,
1048 true,
1049 ))))
1050 }
1051 Self::EndOfEpoch(txns) => Either::Left(Either::Right(
1052 txns.iter().flat_map(|txn| txn.shared_input_objects()),
1053 )),
1054 Self::Programmable(pt) => Either::Right(Either::Left(pt.shared_input_objects())),
1055 _ => Either::Right(Either::Right(iter::empty())),
1056 }
1057 }
1058
1059 fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)> {
1060 match &self {
1061 Self::Programmable(pt) => pt.move_calls(),
1062 _ => vec![],
1063 }
1064 }
1065
1066 fn receiving_objects(&self) -> Vec<ObjectReference> {
1067 match &self {
1068 #[allow(deprecated)]
1069 TransactionKind::Genesis(_)
1070 | TransactionKind::ConsensusCommitPrologueV1(_)
1071 | TransactionKind::AuthenticatorStateUpdateV1Deprecated
1072 | TransactionKind::RandomnessStateUpdate(_)
1073 | TransactionKind::TransactionDenyRulesUpdate(_)
1074 | TransactionKind::EndOfEpoch(_)
1075 | TransactionKind::ClaimAccount(_) => vec![],
1076 TransactionKind::Programmable(pt) => pt.receiving_objects(),
1077 _ => unimplemented!(
1078 "a new TransactionKind enum variant was added and needs to be handled"
1079 ),
1080 }
1081 }
1082
1083 fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>> {
1084 let input_objects = match &self {
1085 Self::Genesis(_) => {
1086 vec![]
1087 }
1088 Self::ConsensusCommitPrologueV1(_) => {
1089 vec![InputObjectKind::SharedMoveObject {
1090 id: ObjectId::CLOCK,
1091 initial_shared_version: IOTA_CLOCK_OBJECT_SHARED_VERSION,
1092 mutable: true,
1093 }]
1094 }
1095 #[allow(deprecated)]
1096 Self::AuthenticatorStateUpdateV1Deprecated => {
1097 vec![]
1101 }
1102 Self::RandomnessStateUpdate(update) => {
1103 vec![InputObjectKind::SharedMoveObject {
1104 id: ObjectId::RANDOMNESS_STATE,
1105 initial_shared_version: update.randomness_obj_initial_shared_version,
1106 mutable: true,
1107 }]
1108 }
1109 Self::TransactionDenyRulesUpdate(update) => {
1110 vec![InputObjectKind::SharedMoveObject {
1111 id: ObjectId::TRANSACTION_DENY_RULES,
1112 initial_shared_version: update.deny_rules_obj_initial_shared_version,
1113 mutable: true,
1114 }]
1115 }
1116 Self::EndOfEpoch(txns) => {
1117 let before_dedup: Vec<_> =
1120 txns.iter().flat_map(|txn| txn.input_objects()).collect();
1121 let mut has_seen = HashSet::new();
1122 let mut after_dedup = vec![];
1123 for obj in before_dedup {
1124 if has_seen.insert(obj) {
1125 after_dedup.push(obj);
1126 }
1127 }
1128 after_dedup
1129 }
1130 Self::Programmable(p) => return p.input_objects(),
1131 Self::ClaimAccount(_) => vec![],
1132 _ => unimplemented!(
1133 "a new TransactionKind enum variant was added and needs to be handled"
1134 ),
1135 };
1136 let mut used = HashSet::new();
1144 if !input_objects.iter().all(|o| used.insert(o.object_id())) {
1145 return Err(UserInputError::DuplicateObjectRefInput);
1146 }
1147 Ok(input_objects)
1148 }
1149
1150 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
1151 match self {
1152 TransactionKind::Programmable(p) => p.validity_check(config)?,
1153 TransactionKind::Genesis(_) | TransactionKind::ConsensusCommitPrologueV1(_) => (),
1156 TransactionKind::EndOfEpoch(txns) => {
1157 for tx in txns {
1158 tx.validity_check(config)?;
1159 }
1160 }
1161
1162 #[allow(deprecated)]
1163 TransactionKind::AuthenticatorStateUpdateV1Deprecated => {
1164 return Err(UserInputError::Unsupported(
1168 "authenticator state transactions are deprecated and were never created on IOTA"
1169 .to_string(),
1170 ));
1171 }
1172 TransactionKind::RandomnessStateUpdate(_) => (),
1173 TransactionKind::TransactionDenyRulesUpdate(_) => {
1174 if !config.enable_pcool_flow() {
1175 return Err(UserInputError::Unsupported(
1176 "on-chain deny rule governance not supported at current protocol version"
1177 .to_string(),
1178 ));
1179 }
1180 }
1181 TransactionKind::ClaimAccount(claim) => {
1182 fp_ensure!(
1183 config.enable_claim_account_transaction(),
1184 UserInputError::Unsupported(
1185 "claim account transactions are not enabled on this network".to_string()
1186 )
1187 );
1188 match &claim.kind {
1189 AccountClaimKind::SmartAccount(smart) => {
1190 let scheme =
1194 SignatureScheme::from_byte(smart.public_key_scheme).map_err(|e| {
1195 UserInputError::Unsupported(format!(
1196 "invalid claim account public key scheme: {e}"
1197 ))
1198 })?;
1199 MovePublicKey::new(scheme, smart.public_key_raw_bytes.clone()).map_err(
1200 |e| {
1201 UserInputError::Unsupported(format!(
1202 "invalid claim account public key: {e}"
1203 ))
1204 },
1205 )?;
1206 }
1207 _ => unimplemented!(
1208 "a new AccountClaimKind enum variant was added and needs to be handled"
1209 ),
1210 }
1211 }
1212 _ => unimplemented!(
1213 "a new TransactionKind enum variant was added and needs to be handled"
1214 ),
1215 };
1216 Ok(())
1217 }
1218
1219 fn iter_commands(&self) -> impl Iterator<Item = &Command> {
1220 match self {
1221 TransactionKind::Programmable(pt) => pt.commands.iter(),
1222 _ => [].iter(),
1223 }
1224 }
1225
1226 fn name(&self) -> &'static str {
1227 match self {
1228 Self::Genesis(_) => "Genesis",
1229 Self::ConsensusCommitPrologueV1(_) => "ConsensusCommitPrologueV1",
1230 Self::Programmable(_) => "Programmable",
1231 #[allow(deprecated)]
1232 Self::AuthenticatorStateUpdateV1Deprecated => "AuthenticatorStateUpdateV1Deprecated",
1233 Self::RandomnessStateUpdate(_) => "RandomnessStateUpdate",
1234 Self::TransactionDenyRulesUpdate(_) => "TransactionDenyRulesUpdate",
1235 Self::EndOfEpoch(_) => "EndOfEpoch",
1236 Self::ClaimAccount(_) => "ClaimAccount",
1237 _ => unimplemented!(
1238 "a new TransactionKind enum variant was added and needs to be handled"
1239 ),
1240 }
1241 }
1242}
1243
1244pub trait TransactionAPI {
1255 fn sender(&self) -> Address;
1257
1258 fn kind(&self) -> &TransactionKind;
1260
1261 fn kind_mut(&mut self) -> &mut TransactionKind;
1263
1264 fn into_kind(self) -> TransactionKind;
1266
1267 fn signers(&self) -> NonEmpty<Address>;
1270
1271 fn gas_data(&self) -> &GasPayment;
1274
1275 fn gas_owner(&self) -> Address;
1277
1278 fn gas(&self) -> &[ObjectReference];
1280
1281 fn gas_price(&self) -> u64;
1283
1284 fn gas_budget(&self) -> u64;
1286
1287 fn expiration(&self) -> &TransactionExpiration;
1289
1290 fn transaction_dependency(&self) -> Option<TransactionDigest>;
1294
1295 fn shared_input_objects(&self) -> Vec<SharedObjectReference>;
1301
1302 fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)>;
1305
1306 fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>>;
1314
1315 fn receiving_objects(&self) -> Vec<ObjectReference>;
1318
1319 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
1322
1323 fn validity_check_no_gas_check(&self, config: &ProtocolConfig) -> UserInputResult;
1326
1327 fn check_serialized_size(&self, config: &ProtocolConfig) -> IotaResult;
1330
1331 fn check_gas_payment_size(&self, config: &ProtocolConfig) -> UserInputResult;
1334
1335 fn check_sponsorship(&self) -> UserInputResult;
1337
1338 fn is_system_tx(&self) -> bool;
1340 fn is_genesis_tx(&self) -> bool;
1342
1343 fn is_end_of_epoch_tx(&self) -> bool;
1346
1347 fn is_sponsored_tx(&self) -> bool;
1349
1350 fn sender_mut_for_testing(&mut self) -> &mut Address;
1352
1353 fn gas_data_mut(&mut self) -> &mut GasPayment;
1355
1356 fn expiration_mut_for_testing(&mut self) -> &mut TransactionExpiration;
1358
1359 fn new_system_transaction(kind: TransactionKind) -> Transaction;
1362
1363 #[allow(clippy::new_ret_no_self)]
1366 fn new(
1367 kind: TransactionKind,
1368 sender: Address,
1369 gas_payment: ObjectReference,
1370 gas_budget: u64,
1371 gas_price: u64,
1372 ) -> Transaction;
1373
1374 fn new_with_gas_coins(
1377 kind: TransactionKind,
1378 sender: Address,
1379 gas_payment: Vec<ObjectReference>,
1380 gas_budget: u64,
1381 gas_price: u64,
1382 ) -> Transaction;
1383
1384 fn new_with_gas_coins_allow_sponsor(
1388 kind: TransactionKind,
1389 sender: Address,
1390 gas_payment: Vec<ObjectReference>,
1391 gas_budget: u64,
1392 gas_price: u64,
1393 gas_sponsor: Address,
1394 ) -> Transaction;
1395
1396 fn new_with_gas_data(
1398 kind: TransactionKind,
1399 sender: Address,
1400 gas_data: GasPayment,
1401 ) -> Transaction;
1402
1403 fn new_move_call(
1406 sender: Address,
1407 package: ObjectId,
1408 module: Identifier,
1409 function: Identifier,
1410 type_arguments: Vec<TypeTag>,
1411 gas_payment: ObjectReference,
1412 arguments: Vec<CallArg>,
1413 gas_budget: u64,
1414 gas_price: u64,
1415 ) -> anyhow::Result<Transaction>;
1416
1417 fn new_move_call_with_gas_coins(
1420 sender: Address,
1421 package: ObjectId,
1422 module: Identifier,
1423 function: Identifier,
1424 type_arguments: Vec<TypeTag>,
1425 gas_payment: Vec<ObjectReference>,
1426 arguments: Vec<CallArg>,
1427 gas_budget: u64,
1428 gas_price: u64,
1429 ) -> anyhow::Result<Transaction>;
1430
1431 fn new_transfer(
1433 recipient: Address,
1434 object_ref: ObjectReference,
1435 sender: Address,
1436 gas_payment: ObjectReference,
1437 gas_budget: u64,
1438 gas_price: u64,
1439 ) -> Transaction;
1440
1441 fn new_transfer_iota(
1445 recipient: Address,
1446 sender: Address,
1447 amount: Option<u64>,
1448 gas_payment: ObjectReference,
1449 gas_budget: u64,
1450 gas_price: u64,
1451 ) -> Transaction;
1452
1453 fn new_transfer_iota_allow_sponsor(
1457 recipient: Address,
1458 sender: Address,
1459 amount: Option<u64>,
1460 gas_payment: ObjectReference,
1461 gas_budget: u64,
1462 gas_price: u64,
1463 gas_sponsor: Address,
1464 ) -> Transaction;
1465
1466 fn new_pay(
1470 sender: Address,
1471 coins: Vec<ObjectReference>,
1472 recipients: Vec<Address>,
1473 amounts: Vec<u64>,
1474 gas_payment: ObjectReference,
1475 gas_budget: u64,
1476 gas_price: u64,
1477 ) -> anyhow::Result<Transaction>;
1478
1479 fn new_pay_iota(
1483 sender: Address,
1484 coins: Vec<ObjectReference>,
1485 recipients: Vec<Address>,
1486 amounts: Vec<u64>,
1487 gas_payment: ObjectReference,
1488 gas_budget: u64,
1489 gas_price: u64,
1490 ) -> anyhow::Result<Transaction>;
1491
1492 fn new_pay_all_iota(
1495 sender: Address,
1496 coins: Vec<ObjectReference>,
1497 recipient: Address,
1498 gas_payment: ObjectReference,
1499 gas_budget: u64,
1500 gas_price: u64,
1501 ) -> Transaction;
1502
1503 fn new_split_coin(
1506 sender: Address,
1507 coin: ObjectReference,
1508 amounts: Vec<u64>,
1509 gas_payment: ObjectReference,
1510 gas_budget: u64,
1511 gas_price: u64,
1512 ) -> Transaction;
1513
1514 fn new_module(
1516 sender: Address,
1517 gas_payment: ObjectReference,
1518 modules: Vec<Vec<u8>>,
1519 dep_ids: Vec<ObjectId>,
1520 gas_budget: u64,
1521 gas_price: u64,
1522 ) -> Transaction;
1523
1524 fn new_upgrade(
1527 sender: Address,
1528 gas_payment: ObjectReference,
1529 package_id: ObjectId,
1530 modules: Vec<Vec<u8>>,
1531 dep_ids: Vec<ObjectId>,
1532 upgrade_capability_and_owner: (ObjectReference, Owner),
1533 upgrade_policy: u8,
1534 digest: Vec<u8>,
1535 gas_budget: u64,
1536 gas_price: u64,
1537 ) -> anyhow::Result<Transaction>;
1538
1539 fn new_programmable(
1542 sender: Address,
1543 gas_payment: Vec<ObjectReference>,
1544 pt: ProgrammableTransaction,
1545 gas_budget: u64,
1546 gas_price: u64,
1547 ) -> Transaction;
1548
1549 fn new_programmable_allow_sponsor(
1552 sender: Address,
1553 gas_payment: Vec<ObjectReference>,
1554 pt: ProgrammableTransaction,
1555 gas_budget: u64,
1556 gas_price: u64,
1557 sponsor: Address,
1558 ) -> Transaction;
1559
1560 fn message_version(&self) -> u64;
1562
1563 fn execution_parts(&self) -> (TransactionKind, Address, GasPayment);
1566}
1567
1568fn tx_bcs_size<T: Serialize>(tx: &T) -> IotaResult<usize> {
1569 bcs::serialized_size(tx).map_err(|e| IotaError::TransactionSerialization {
1570 error: e.to_string(),
1571 })
1572}
1573
1574fn check_transaction_size<T: Serialize>(
1577 transaction: &T,
1578 config: &ProtocolConfig,
1579) -> IotaResult<usize> {
1580 let tx_size = tx_bcs_size(transaction)?;
1581 let max_tx_size_bytes = config.max_tx_size_bytes();
1582 fp_ensure!(
1583 tx_size as u64 <= max_tx_size_bytes,
1584 IotaError::UserInput {
1585 error: UserInputError::SizeLimitExceeded {
1586 limit: format!(
1587 "serialized transaction size exceeded maximum of {max_tx_size_bytes}"
1588 ),
1589 value: tx_size.to_string(),
1590 }
1591 }
1592 );
1593 Ok(tx_size)
1594}
1595
1596impl TransactionAPI for Transaction {
1597 fn check_serialized_size(&self, config: &ProtocolConfig) -> IotaResult {
1598 check_transaction_size(self, config).map(|_| ())
1599 }
1600
1601 fn sender(&self) -> Address {
1602 match self {
1603 Self::V1(v1) => v1.sender,
1604 _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1605 }
1606 }
1607
1608 fn kind(&self) -> &TransactionKind {
1609 match self {
1610 Self::V1(v1) => &v1.kind,
1611 _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1612 }
1613 }
1614
1615 fn kind_mut(&mut self) -> &mut TransactionKind {
1616 match self {
1617 Self::V1(v1) => &mut v1.kind,
1618 _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1619 }
1620 }
1621
1622 fn into_kind(self) -> TransactionKind {
1623 match self {
1624 Self::V1(v1) => v1.kind,
1625 _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1626 }
1627 }
1628
1629 fn signers(&self) -> NonEmpty<Address> {
1630 let mut signers = nonempty![self.sender()];
1631 if self.gas_owner() != self.sender() {
1632 signers.push(self.gas_owner());
1633 }
1634 signers
1635 }
1636
1637 fn gas_data(&self) -> &GasPayment {
1638 match self {
1639 Self::V1(v1) => &v1.gas_payment,
1640 _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1641 }
1642 }
1643
1644 fn gas_owner(&self) -> Address {
1645 self.gas_data().owner
1646 }
1647
1648 fn gas(&self) -> &[ObjectReference] {
1649 &self.gas_data().objects
1650 }
1651
1652 fn gas_price(&self) -> u64 {
1653 self.gas_data().price
1654 }
1655
1656 fn gas_budget(&self) -> u64 {
1657 self.gas_data().budget
1658 }
1659
1660 fn expiration(&self) -> &TransactionExpiration {
1661 match self {
1662 Self::V1(v1) => &v1.expiration,
1663 _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1664 }
1665 }
1666
1667 fn shared_input_objects(&self) -> Vec<SharedObjectReference> {
1668 self.kind().shared_input_objects().collect()
1669 }
1670
1671 fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)> {
1672 self.kind().move_calls()
1673 }
1674
1675 fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>> {
1676 let mut inputs = self.kind().input_objects()?;
1677
1678 if !self.kind().is_system() {
1679 inputs.extend(
1680 self.gas()
1681 .iter()
1682 .map(|obj_ref| InputObjectKind::ImmOrOwnedMoveObject(*obj_ref)),
1683 );
1684 }
1685 Ok(inputs)
1686 }
1687
1688 fn receiving_objects(&self) -> Vec<ObjectReference> {
1689 self.kind().receiving_objects()
1690 }
1691
1692 fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
1693 fp_ensure!(!self.gas().is_empty(), UserInputError::MissingGasPayment);
1694 self.check_gas_payment_size(config)?;
1695 if config.validate_input_object_versions() {
1696 for gas_object in self.gas() {
1697 input_object_version_validity_check(gas_object.version)?;
1698 }
1699 }
1700 check_claim_account_gas_budget(self, config)?;
1701 self.validity_check_no_gas_check(config)
1702 }
1703
1704 #[instrument(level = "trace", skip_all)]
1705 fn validity_check_no_gas_check(&self, config: &ProtocolConfig) -> UserInputResult {
1706 self.kind().validity_check(config)?;
1707 if self.transaction_dependency().is_some() {
1708 fp_ensure!(
1709 matches!(self.expiration(), TransactionExpiration::Epoch(_)),
1710 UserInputError::TransactionDependencyRequiresExpiration
1711 );
1712 }
1713 check_claimed_key_derives_sender(self)?;
1714 self.check_sponsorship()
1715 }
1716
1717 fn transaction_dependency(&self) -> Option<TransactionDigest> {
1718 match self.kind() {
1719 TransactionKind::Programmable(ptb) => ptb.transaction_dependency(),
1720 _ => None,
1721 }
1722 }
1723
1724 fn check_gas_payment_size(&self, config: &ProtocolConfig) -> UserInputResult {
1725 fp_ensure!(
1726 self.gas().len() < config.max_gas_payment_objects() as usize,
1727 UserInputError::SizeLimitExceeded {
1728 limit: "maximum number of gas payment objects".to_string(),
1729 value: config.max_gas_payment_objects().to_string()
1730 }
1731 );
1732 Ok(())
1733 }
1734
1735 fn is_sponsored_tx(&self) -> bool {
1736 self.gas_owner() != self.sender()
1737 }
1738
1739 fn check_sponsorship(&self) -> UserInputResult {
1740 if self.gas_owner() == self.sender() {
1741 return Ok(());
1742 }
1743 if matches!(
1744 self.kind(),
1745 TransactionKind::Programmable(_) | TransactionKind::ClaimAccount(_)
1746 ) {
1747 return Ok(());
1748 }
1749 Err(UserInputError::UnsupportedSponsoredTransactionKind)
1750 }
1751
1752 fn is_end_of_epoch_tx(&self) -> bool {
1753 matches!(self.kind(), TransactionKind::EndOfEpoch(_))
1754 }
1755
1756 fn is_system_tx(&self) -> bool {
1757 self.kind().is_system()
1758 }
1759
1760 fn is_genesis_tx(&self) -> bool {
1761 matches!(self.kind(), TransactionKind::Genesis(_))
1762 }
1763
1764 fn sender_mut_for_testing(&mut self) -> &mut Address {
1765 match self {
1766 Self::V1(v1) => &mut v1.sender,
1767 _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1768 }
1769 }
1770
1771 fn gas_data_mut(&mut self) -> &mut GasPayment {
1772 match self {
1773 Self::V1(v1) => &mut v1.gas_payment,
1774 _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1775 }
1776 }
1777
1778 fn expiration_mut_for_testing(&mut self) -> &mut TransactionExpiration {
1779 match self {
1780 Self::V1(v1) => &mut v1.expiration,
1781 _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1782 }
1783 }
1784
1785 fn new_system_transaction(kind: TransactionKind) -> Transaction {
1786 assert!(kind.is_system());
1787 let sender = Address::ZERO;
1788 Transaction::V1(TransactionV1 {
1789 kind,
1790 sender,
1791 gas_payment: GasPayment {
1792 price: GAS_PRICE_FOR_SYSTEM_TX,
1793 owner: sender,
1794 objects: vec![ObjectReference::new(
1795 ObjectId::ZERO,
1796 Version::default(),
1797 ObjectDigest::MIN,
1798 )],
1799 budget: 0,
1800 },
1801 expiration: TransactionExpiration::None,
1802 })
1803 }
1804
1805 fn new(
1806 kind: TransactionKind,
1807 sender: Address,
1808 gas_payment: ObjectReference,
1809 gas_budget: u64,
1810 gas_price: u64,
1811 ) -> Transaction {
1812 Transaction::V1(TransactionV1 {
1813 kind,
1814 sender,
1815 gas_payment: GasPayment {
1816 price: gas_price,
1817 owner: sender,
1818 objects: vec![gas_payment],
1819 budget: gas_budget,
1820 },
1821 expiration: TransactionExpiration::None,
1822 })
1823 }
1824
1825 fn new_with_gas_coins(
1826 kind: TransactionKind,
1827 sender: Address,
1828 gas_payment: Vec<ObjectReference>,
1829 gas_budget: u64,
1830 gas_price: u64,
1831 ) -> Transaction {
1832 Transaction::new_with_gas_coins_allow_sponsor(
1833 kind,
1834 sender,
1835 gas_payment,
1836 gas_budget,
1837 gas_price,
1838 sender,
1839 )
1840 }
1841
1842 fn new_with_gas_coins_allow_sponsor(
1843 kind: TransactionKind,
1844 sender: Address,
1845 gas_payment: Vec<ObjectReference>,
1846 gas_budget: u64,
1847 gas_price: u64,
1848 gas_sponsor: Address,
1849 ) -> Transaction {
1850 Transaction::V1(TransactionV1 {
1851 kind,
1852 sender,
1853 gas_payment: GasPayment {
1854 price: gas_price,
1855 owner: gas_sponsor,
1856 objects: gas_payment,
1857 budget: gas_budget,
1858 },
1859 expiration: TransactionExpiration::None,
1860 })
1861 }
1862
1863 fn new_with_gas_data(
1864 kind: TransactionKind,
1865 sender: Address,
1866 gas_data: GasPayment,
1867 ) -> Transaction {
1868 Transaction::V1(TransactionV1 {
1869 kind,
1870 sender,
1871 gas_payment: gas_data,
1872 expiration: TransactionExpiration::None,
1873 })
1874 }
1875
1876 fn new_move_call(
1877 sender: Address,
1878 package: ObjectId,
1879 module: Identifier,
1880 function: Identifier,
1881 type_arguments: Vec<TypeTag>,
1882 gas_payment: ObjectReference,
1883 arguments: Vec<CallArg>,
1884 gas_budget: u64,
1885 gas_price: u64,
1886 ) -> anyhow::Result<Transaction> {
1887 Transaction::new_move_call_with_gas_coins(
1888 sender,
1889 package,
1890 module,
1891 function,
1892 type_arguments,
1893 vec![gas_payment],
1894 arguments,
1895 gas_budget,
1896 gas_price,
1897 )
1898 }
1899
1900 fn new_move_call_with_gas_coins(
1901 sender: Address,
1902 package: ObjectId,
1903 module: Identifier,
1904 function: Identifier,
1905 type_arguments: Vec<TypeTag>,
1906 gas_payment: Vec<ObjectReference>,
1907 arguments: Vec<CallArg>,
1908 gas_budget: u64,
1909 gas_price: u64,
1910 ) -> anyhow::Result<Transaction> {
1911 let pt = {
1912 let mut builder = ProgrammableTransactionBuilder::new();
1913 builder.move_call(package, module, function, type_arguments, arguments)?;
1914 builder.finish()
1915 };
1916 Ok(Transaction::new_programmable(
1917 sender,
1918 gas_payment,
1919 pt,
1920 gas_budget,
1921 gas_price,
1922 ))
1923 }
1924
1925 fn new_transfer(
1926 recipient: Address,
1927 object_ref: ObjectReference,
1928 sender: Address,
1929 gas_payment: ObjectReference,
1930 gas_budget: u64,
1931 gas_price: u64,
1932 ) -> Transaction {
1933 let pt = {
1934 let mut builder = ProgrammableTransactionBuilder::new();
1935 builder.transfer_object(recipient, object_ref).unwrap();
1936 builder.finish()
1937 };
1938 Transaction::new_programmable(sender, vec![gas_payment], pt, gas_budget, gas_price)
1939 }
1940
1941 fn new_transfer_iota(
1942 recipient: Address,
1943 sender: Address,
1944 amount: Option<u64>,
1945 gas_payment: ObjectReference,
1946 gas_budget: u64,
1947 gas_price: u64,
1948 ) -> Transaction {
1949 Transaction::new_transfer_iota_allow_sponsor(
1950 recipient,
1951 sender,
1952 amount,
1953 gas_payment,
1954 gas_budget,
1955 gas_price,
1956 sender,
1957 )
1958 }
1959
1960 fn new_transfer_iota_allow_sponsor(
1961 recipient: Address,
1962 sender: Address,
1963 amount: Option<u64>,
1964 gas_payment: ObjectReference,
1965 gas_budget: u64,
1966 gas_price: u64,
1967 gas_sponsor: Address,
1968 ) -> Transaction {
1969 let pt = {
1970 let mut builder = ProgrammableTransactionBuilder::new();
1971 builder.transfer_iota(recipient, amount);
1972 builder.finish()
1973 };
1974 Transaction::new_programmable_allow_sponsor(
1975 sender,
1976 vec![gas_payment],
1977 pt,
1978 gas_budget,
1979 gas_price,
1980 gas_sponsor,
1981 )
1982 }
1983
1984 fn new_pay(
1985 sender: Address,
1986 coins: Vec<ObjectReference>,
1987 recipients: Vec<Address>,
1988 amounts: Vec<u64>,
1989 gas_payment: ObjectReference,
1990 gas_budget: u64,
1991 gas_price: u64,
1992 ) -> anyhow::Result<Transaction> {
1993 let pt = {
1994 let mut builder = ProgrammableTransactionBuilder::new();
1995 builder.pay(coins, recipients, amounts)?;
1996 builder.finish()
1997 };
1998 Ok(Transaction::new_programmable(
1999 sender,
2000 vec![gas_payment],
2001 pt,
2002 gas_budget,
2003 gas_price,
2004 ))
2005 }
2006
2007 fn new_pay_iota(
2008 sender: Address,
2009 mut coins: Vec<ObjectReference>,
2010 recipients: Vec<Address>,
2011 amounts: Vec<u64>,
2012 gas_payment: ObjectReference,
2013 gas_budget: u64,
2014 gas_price: u64,
2015 ) -> anyhow::Result<Transaction> {
2016 coins.insert(0, gas_payment);
2017 let pt = {
2018 let mut builder = ProgrammableTransactionBuilder::new();
2019 builder.pay_iota(recipients, amounts)?;
2020 builder.finish()
2021 };
2022 Ok(Transaction::new_programmable(
2023 sender, coins, pt, gas_budget, gas_price,
2024 ))
2025 }
2026
2027 fn new_pay_all_iota(
2028 sender: Address,
2029 mut coins: Vec<ObjectReference>,
2030 recipient: Address,
2031 gas_payment: ObjectReference,
2032 gas_budget: u64,
2033 gas_price: u64,
2034 ) -> Transaction {
2035 coins.insert(0, gas_payment);
2036 let pt = {
2037 let mut builder = ProgrammableTransactionBuilder::new();
2038 builder.pay_all_iota(recipient);
2039 builder.finish()
2040 };
2041 Transaction::new_programmable(sender, coins, pt, gas_budget, gas_price)
2042 }
2043
2044 fn new_split_coin(
2045 sender: Address,
2046 coin: ObjectReference,
2047 amounts: Vec<u64>,
2048 gas_payment: ObjectReference,
2049 gas_budget: u64,
2050 gas_price: u64,
2051 ) -> Transaction {
2052 let pt = {
2053 let mut builder = ProgrammableTransactionBuilder::new();
2054 builder.split_coin(sender, coin, amounts);
2055 builder.finish()
2056 };
2057 Transaction::new_programmable(sender, vec![gas_payment], pt, gas_budget, gas_price)
2058 }
2059
2060 fn new_module(
2061 sender: Address,
2062 gas_payment: ObjectReference,
2063 modules: Vec<Vec<u8>>,
2064 dep_ids: Vec<ObjectId>,
2065 gas_budget: u64,
2066 gas_price: u64,
2067 ) -> Transaction {
2068 let pt = {
2069 let mut builder = ProgrammableTransactionBuilder::new();
2070 let upgrade_cap = builder.publish_upgradeable(modules, dep_ids);
2071 builder.transfer_arg(sender, upgrade_cap);
2072 builder.finish()
2073 };
2074 Transaction::new_programmable(sender, vec![gas_payment], pt, gas_budget, gas_price)
2075 }
2076
2077 fn new_upgrade(
2078 sender: Address,
2079 gas_payment: ObjectReference,
2080 package_id: ObjectId,
2081 modules: Vec<Vec<u8>>,
2082 dep_ids: Vec<ObjectId>,
2083 (upgrade_capability, capability_owner): (ObjectReference, Owner),
2084 upgrade_policy: u8,
2085 digest: Vec<u8>,
2086 gas_budget: u64,
2087 gas_price: u64,
2088 ) -> anyhow::Result<Transaction> {
2089 let pt = {
2090 let mut builder = ProgrammableTransactionBuilder::new();
2091 let capability_arg = match capability_owner {
2092 Owner::Address(_) => CallArg::ImmutableOrOwned(upgrade_capability),
2093 Owner::Shared(initial_shared_version) => {
2094 CallArg::Shared(SharedObjectReference::new(
2095 upgrade_capability.object_id,
2096 initial_shared_version,
2097 true,
2098 ))
2099 }
2100 Owner::Immutable => {
2101 bail!("Upgrade capability is stored immutably and cannot be used for upgrades");
2102 }
2103 Owner::Object(_) => {
2104 bail!("Upgrade capability controlled by object");
2105 }
2106 _ => unimplemented!("a new Owner enum variant was added and needs to be handled"),
2107 };
2108 builder.obj(capability_arg).unwrap();
2109 let upgrade_arg = builder.pure(upgrade_policy).unwrap();
2110 let digest_arg = builder.pure(digest).unwrap();
2111 let upgrade_ticket = builder.programmable_move_call(
2112 ObjectId::FRAMEWORK,
2113 Identifier::PACKAGE_MODULE,
2114 Identifier::from_static("authorize_upgrade"),
2115 vec![],
2116 vec![Argument::Input(0), upgrade_arg, digest_arg],
2117 );
2118 let upgrade_receipt = builder.upgrade(package_id, upgrade_ticket, dep_ids, modules);
2119
2120 builder.programmable_move_call(
2121 ObjectId::FRAMEWORK,
2122 Identifier::PACKAGE_MODULE,
2123 Identifier::from_static("commit_upgrade"),
2124 vec![],
2125 vec![Argument::Input(0), upgrade_receipt],
2126 );
2127
2128 builder.finish()
2129 };
2130 Ok(Transaction::new_programmable(
2131 sender,
2132 vec![gas_payment],
2133 pt,
2134 gas_budget,
2135 gas_price,
2136 ))
2137 }
2138
2139 fn new_programmable(
2140 sender: Address,
2141 gas_payment: Vec<ObjectReference>,
2142 pt: ProgrammableTransaction,
2143 gas_budget: u64,
2144 gas_price: u64,
2145 ) -> Transaction {
2146 Transaction::new_programmable_allow_sponsor(
2147 sender,
2148 gas_payment,
2149 pt,
2150 gas_budget,
2151 gas_price,
2152 sender,
2153 )
2154 }
2155
2156 fn new_programmable_allow_sponsor(
2157 sender: Address,
2158 gas_payment: Vec<ObjectReference>,
2159 pt: ProgrammableTransaction,
2160 gas_budget: u64,
2161 gas_price: u64,
2162 sponsor: Address,
2163 ) -> Transaction {
2164 let kind = TransactionKind::Programmable(pt);
2165 Transaction::new_with_gas_coins_allow_sponsor(
2166 kind,
2167 sender,
2168 gas_payment,
2169 gas_budget,
2170 gas_price,
2171 sponsor,
2172 )
2173 }
2174
2175 fn message_version(&self) -> u64 {
2176 match self {
2177 Transaction::V1(_) => 1,
2178 _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
2179 }
2180 }
2181
2182 fn execution_parts(&self) -> (TransactionKind, Address, GasPayment) {
2183 (self.kind().clone(), self.sender(), self.gas_data().clone())
2184 }
2185}
2186
2187pub struct TxValidityCheckContext<'a> {
2188 pub config: &'a ProtocolConfig,
2189 pub epoch: EpochId,
2190}
2191
2192pub fn merge_authenticator_input_objects<'a>(
2206 move_authenticators: impl IntoIterator<Item = &'a MoveAuthenticator>,
2207 include_type_arg_packages: bool,
2208 input_objects: &mut Vec<InputObjectKind>,
2209) -> UserInputResult<()> {
2210 let mut type_arg_packages = Vec::new();
2211 for move_authenticator in move_authenticators {
2212 for auth_object in move_authenticator.input_objects(false) {
2213 let entry = input_objects
2214 .iter_mut()
2215 .find(|o| o.object_id() == auth_object.object_id());
2216
2217 match entry {
2218 None => input_objects.push(auth_object),
2219 Some(existing) => existing.left_union_with_checks(&auth_object)?,
2220 }
2221 }
2222 if include_type_arg_packages {
2223 type_arg_packages.extend(move_authenticator.type_arg_packages());
2224 }
2225 }
2226 for package_id in type_arg_packages {
2227 if input_objects.iter().all(|o| o.object_id() != package_id) {
2228 input_objects.push(InputObjectKind::MovePackage(package_id));
2229 }
2230 }
2231 Ok(())
2232}
2233
2234pub trait SenderSignedTransactionAPI {
2241 fn new_from_sender_signature(
2244 tx: Transaction,
2245 tx_signature: SimpleSignature,
2246 ) -> SenderSignedTransaction;
2247
2248 fn add_signature(&mut self, new_signature: SimpleSignature);
2251
2252 fn get_signer_sig_mapping(&self) -> IotaResult<BTreeMap<Address, &UserSignature>>;
2255
2256 fn has_multisig(&self) -> bool;
2258
2259 fn transaction_mut_for_testing(&mut self) -> &mut Transaction;
2261
2262 fn tx_signatures_mut_for_testing(&mut self) -> &mut Vec<UserSignature>;
2264
2265 fn serialized_size(&self) -> IotaResult<usize>;
2267
2268 fn validity_check(&self, context: &TxValidityCheckContext<'_>) -> Result<usize, IotaError>;
2272
2273 fn collect_all_input_object_kind_for_reading(
2285 &self,
2286 include_type_arg_packages: bool,
2287 ) -> IotaResult<Vec<InputObjectKind>>;
2288
2289 fn split_input_objects_into_groups_for_reading(
2298 &self,
2299 input_objects: InputObjects,
2300 ) -> IotaResult<(InputObjects, Vec<(InputObjects, ObjectReadResult)>)>;
2301
2302 fn contains_shared_object(&self) -> bool;
2310
2311 fn shared_input_objects(&self) -> Vec<SharedObjectReference>;
2320
2321 fn input_objects(&self, include_type_arg_packages: bool) -> IotaResult<Vec<InputObjectKind>>;
2337
2338 fn uses_randomness(&self) -> bool;
2343}
2344
2345impl SenderSignedTransactionAPI for SenderSignedTransaction {
2346 fn new_from_sender_signature(
2347 tx: Transaction,
2348 tx_signature: SimpleSignature,
2349 ) -> SenderSignedTransaction {
2350 Self::new(tx, vec![tx_signature.into()])
2351 }
2352
2353 fn add_signature(&mut self, new_signature: SimpleSignature) {
2354 self.signed_transaction_mut()
2355 .signatures
2356 .push(new_signature.into());
2357 }
2358
2359 fn get_signer_sig_mapping(&self) -> IotaResult<BTreeMap<Address, &UserSignature>> {
2360 let mut mapping = BTreeMap::new();
2361 for sig in &self.signed_transaction().signatures {
2362 let address = sig.derive_address();
2363 mapping.insert(address, sig);
2364 }
2365 Ok(mapping)
2366 }
2367
2368 fn has_multisig(&self) -> bool {
2369 self.signatures().iter().any(|sig| sig.is_multisig())
2370 }
2371
2372 fn transaction_mut_for_testing(&mut self) -> &mut Transaction {
2373 &mut self.signed_transaction_mut().transaction
2374 }
2375
2376 fn tx_signatures_mut_for_testing(&mut self) -> &mut Vec<UserSignature> {
2377 &mut self.signed_transaction_mut().signatures
2378 }
2379
2380 fn serialized_size(&self) -> IotaResult<usize> {
2381 tx_bcs_size(self)
2382 }
2383
2384 fn validity_check(&self, context: &TxValidityCheckContext<'_>) -> Result<usize, IotaError> {
2385 check_user_signature_protocol_compatibility(self, context.config)?;
2388
2389 let tx = self.transaction();
2392 fp_ensure!(
2393 !tx.is_system_tx(),
2394 IotaError::UserInput {
2395 error: UserInputError::Unsupported(
2396 "SenderSignedTransaction must not contain system transaction".to_string()
2397 )
2398 }
2399 );
2400
2401 if match &tx.expiration() {
2403 TransactionExpiration::None => false,
2404 TransactionExpiration::Epoch(exp_poch) => *exp_poch < context.epoch,
2405 _ => unimplemented!(
2406 "a new TransactionExpiration enum variant was added and needs to be handled"
2407 ),
2408 } {
2409 return Err(IotaError::TransactionExpired);
2410 }
2411
2412 let tx_size = check_transaction_size(self, context.config)?;
2414
2415 tx.validity_check(context.config)
2416 .map_err(Into::<IotaError>::into)?;
2417
2418 if tx.transaction_dependency().is_some() {
2422 fp_ensure!(
2423 matches!(tx.expiration(), TransactionExpiration::Epoch(epoch) if *epoch == context.epoch),
2424 IotaError::UserInput {
2425 error: UserInputError::TransactionDependencyRequiresExpiration
2426 }
2427 );
2428 }
2429
2430 move_authenticators_validity_check(self, context.config)?;
2431
2432 Ok(tx_size)
2433 }
2434
2435 fn collect_all_input_object_kind_for_reading(
2436 &self,
2437 include_type_arg_packages: bool,
2438 ) -> IotaResult<Vec<InputObjectKind>> {
2439 let mut seen = HashSet::new();
2440 Ok(self
2441 .transaction()
2442 .input_objects()?
2443 .into_iter()
2444 .chain(
2445 self.move_authenticators()
2446 .into_iter()
2447 .flat_map(|authenticator| {
2448 authenticator.input_objects(include_type_arg_packages)
2449 }),
2450 )
2451 .filter(|kind| seen.insert(*kind))
2452 .collect())
2453 }
2454
2455 fn split_input_objects_into_groups_for_reading(
2456 &self,
2457 input_objects: InputObjects,
2458 ) -> IotaResult<(InputObjects, Vec<(InputObjects, ObjectReadResult)>)> {
2459 let input_objects_map = input_objects
2460 .iter()
2461 .map(|o| (&o.input_object_kind, o))
2462 .collect::<HashMap<_, _>>();
2463
2464 let tx_input_object_kinds = self.transaction().input_objects()?;
2465 let mut tx_input_objects: InputObjects = tx_input_object_kinds
2466 .iter()
2467 .map(|k| {
2468 input_objects_map
2469 .get(k)
2470 .map(|&r| r.clone())
2471 .expect("All transaction input objects are expected to be present")
2472 })
2473 .collect::<Vec<_>>()
2474 .into();
2475 if let Some((gas_object_id, version)) = input_objects.gas_object_cancellation() {
2476 tx_input_objects.set_gas_object_cancellation(gas_object_id, version);
2477 }
2478 if let Some(dependency) = input_objects.transaction_dependency() {
2479 tx_input_objects.set_transaction_dependency(dependency);
2480 }
2481
2482 let per_authenticator_inputs =
2483 self.move_authenticators()
2484 .into_iter()
2485 .map(|move_authenticator| {
2486 let type_arg_packages = move_authenticator
2490 .type_arg_packages()
2491 .into_iter()
2492 .map(InputObjectKind::MovePackage)
2493 .filter(|k| !tx_input_object_kinds.contains(k))
2494 .filter_map(|k| input_objects_map.get(&k).map(|&r| r.clone()));
2495 let authenticator_input_objects = move_authenticator
2496 .input_objects(false)
2497 .iter()
2498 .map(|k| {
2499 input_objects_map.get(k).map(|&r| r.clone()).expect(
2500 "All authenticator input objects are expected to be present",
2501 )
2502 })
2503 .chain(type_arg_packages)
2504 .collect::<Vec<_>>()
2505 .into();
2506
2507 let account_objects = move_authenticator
2508 .object_to_authenticate()
2509 .input_object_kind()
2510 .iter()
2511 .map(|k| {
2512 input_objects_map
2513 .get(k)
2514 .map(|&r| r.clone())
2515 .expect("Account object is expected to be present")
2516 })
2517 .collect::<Vec<_>>();
2518
2519 debug_assert!(
2520 account_objects.len() == 1,
2521 "Only one account object must be loaded"
2522 );
2523
2524 (
2525 authenticator_input_objects,
2526 account_objects
2527 .into_iter()
2528 .next()
2529 .expect("Account object is expected to be present"),
2530 )
2531 })
2532 .collect();
2533
2534 Ok((tx_input_objects, per_authenticator_inputs))
2535 }
2536
2537 fn contains_shared_object(&self) -> bool {
2538 self.transaction().kind().contains_shared_object()
2539 || self
2540 .move_authenticators()
2541 .iter()
2542 .any(|move_authenticator| !move_authenticator.shared_objects().is_empty())
2543 }
2544
2545 fn shared_input_objects(&self) -> Vec<SharedObjectReference> {
2546 let mut input_objects = self.transaction().shared_input_objects();
2548
2549 self.move_authenticators()
2551 .into_iter()
2552 .for_each(|move_authenticator| {
2553 for auth_shared_object in move_authenticator.shared_objects() {
2554 let entry = input_objects
2555 .iter_mut()
2556 .find(|o| o.object_id == auth_shared_object.object_id);
2557
2558 match entry {
2559 None => input_objects.push(auth_shared_object),
2560 Some(existing) => {
2561 left_union_shared_input_objects(existing, &auth_shared_object)
2562 .expect("union of shared objects should not fail")
2563 }
2564 }
2565 }
2566 });
2567
2568 input_objects
2569 }
2570
2571 fn input_objects(&self, include_type_arg_packages: bool) -> IotaResult<Vec<InputObjectKind>> {
2572 let mut input_objects = self.transaction().input_objects()?;
2575
2576 merge_authenticator_input_objects(
2578 self.move_authenticators(),
2579 include_type_arg_packages,
2580 &mut input_objects,
2581 )?;
2582
2583 Ok(input_objects)
2584 }
2585
2586 fn uses_randomness(&self) -> bool {
2587 self.shared_input_objects()
2588 .iter()
2589 .any(|obj| obj.object_id == ObjectId::RANDOMNESS_STATE)
2590 }
2591}
2592
2593fn check_user_signature_protocol_compatibility(
2594 signed_tx: &SenderSignedTransaction,
2595 config: &ProtocolConfig,
2596) -> IotaResult {
2597 for sig in signed_tx.signatures() {
2598 match sig {
2599 UserSignature::PasskeyAuthenticator(_) => {
2600 if !config.passkey_auth() {
2601 return Err(IotaError::UserInput {
2602 error: UserInputError::Unsupported(
2603 "passkey is not enabled on this network".to_string(),
2604 ),
2605 });
2606 }
2607 }
2608 UserSignature::MoveAuthenticator(_) => {
2609 if !config.enable_move_authentication() {
2610 return Err(IotaError::UserInput {
2611 error: UserInputError::Unsupported(
2612 "`Move authentication` is not enabled on this network".to_string(),
2613 ),
2614 });
2615 }
2616 }
2617 UserSignature::Simple(_) | UserSignature::Multisig(_) => (),
2618 _ => {
2619 unimplemented!("a new UserSignature variant was added and needs to be handled")
2620 }
2621 }
2622 }
2623
2624 Ok(())
2625}
2626
2627pub fn transaction_identifiers_validity_check(
2636 signed_tx: &SenderSignedTransaction,
2637) -> UserInputResult {
2638 fp_ensure!(
2641 !signed_tx.transaction().is_system_tx(),
2642 UserInputError::Unsupported(
2643 "SenderSignedTransaction must not contain system transaction".to_string()
2644 )
2645 );
2646 if let TransactionKind::Programmable(pt) = signed_tx.transaction().kind() {
2647 pt.commands
2648 .iter()
2649 .try_for_each(command_identifiers_validity_check)?;
2650 }
2651 signed_tx
2652 .move_authenticators()
2653 .into_iter()
2654 .try_for_each(move_authenticator_identifiers_validity_check)
2655}
2656
2657fn move_authenticators_validity_check(
2658 signed_tx: &SenderSignedTransaction,
2659 config: &ProtocolConfig,
2660) -> IotaResult {
2661 let authenticators = signed_tx.move_authenticators();
2662
2663 authenticators
2665 .iter()
2666 .try_for_each(|authenticator| authenticator.validity_check(config))?;
2667
2668 let authenticators_num = authenticators.len();
2670 if authenticators_num > 0 {
2671 let tx = signed_tx.transaction();
2672
2673 fp_ensure!(
2674 tx.kind().is_programmable(),
2675 UserInputError::Unsupported(
2676 "SenderSignedTransaction with MoveAuthenticator must be a programmable transaction"
2677 .to_string(),
2678 )
2679 .into()
2680 );
2681
2682 if !config.enable_move_authentication_for_sponsor() {
2683 fp_ensure!(
2684 authenticators_num == 1,
2685 UserInputError::Unsupported(
2686 "SenderSignedTransaction with more than one MoveAuthenticator is not supported"
2687 .to_string(),
2688 )
2689 .into()
2690 );
2691
2692 fp_ensure!(
2693 signed_tx.sender_move_authenticator().is_some(),
2694 UserInputError::Unsupported(
2695 "SenderSignedTransaction can have MoveAuthenticator only for the sender"
2696 .to_string(),
2697 )
2698 .into()
2699 );
2700 }
2701
2702 check_move_authenticators_input_consistency(
2703 tx,
2704 &authenticators,
2705 config.move_authenticator_type_arg_packages_as_inputs(),
2706 )?;
2707 }
2708
2709 Ok(())
2710}
2711
2712fn check_move_authenticators_input_consistency(
2713 tx: &Transaction,
2714 authenticators: &[&MoveAuthenticator],
2715 include_type_arg_packages: bool,
2716) -> IotaResult {
2717 let mut checked_inputs = tx
2719 .kind()
2720 .input_objects()?
2721 .into_iter()
2722 .map(|o| (o.object_id(), o))
2723 .collect::<HashMap<_, _>>();
2724
2725 authenticators.iter().try_for_each(|authenticator| {
2726 authenticator
2727 .input_objects(include_type_arg_packages)
2728 .iter()
2729 .try_for_each(|auth_input_object| {
2730 match checked_inputs.get(&auth_input_object.object_id()) {
2731 Some(existing) => {
2732 auth_input_object.check_consistency_for_authentication(existing)?
2733 }
2734 None => {
2735 checked_inputs.insert(auth_input_object.object_id(), *auth_input_object);
2736 }
2737 };
2738
2739 Ok(())
2740 })
2741 })
2742}
2743
2744impl Message for SenderSignedTransaction {
2745 type DigestType = TransactionDigest;
2746 const SCOPE: IntentScope = IntentScope::SenderSignedTransaction;
2747
2748 fn digest(&self) -> Self::DigestType {
2751 self.transaction().digest()
2752 }
2753}
2754
2755impl<S> Envelope<SenderSignedTransaction, S> {
2756 pub fn sender_address(&self) -> Address {
2757 self.data().transaction().sender()
2758 }
2759
2760 pub fn gas(&self) -> &[ObjectReference] {
2761 self.data().transaction().gas()
2762 }
2763
2764 pub fn key(&self) -> TransactionKey {
2766 match &self.data().transaction().kind() {
2767 TransactionKind::RandomnessStateUpdate(rsu) => {
2768 TransactionKey::RandomnessRound(rsu.epoch, rsu.randomness_round)
2769 }
2770 _ => TransactionKey::Digest(*self.digest()),
2771 }
2772 }
2773
2774 pub fn non_digest_key(&self) -> Option<TransactionKey> {
2779 match &self.data().transaction().kind() {
2780 TransactionKind::RandomnessStateUpdate(rsu) => Some(TransactionKey::RandomnessRound(
2781 rsu.epoch,
2782 rsu.randomness_round,
2783 )),
2784 _ => None,
2785 }
2786 }
2787
2788 pub fn is_system_tx(&self) -> bool {
2789 self.data().transaction().is_system_tx()
2790 }
2791
2792 pub fn is_sponsored_tx(&self) -> bool {
2793 self.data().transaction().is_sponsored_tx()
2794 }
2795}
2796
2797impl TransactionEnvelope {
2798 pub fn from_data_and_signer(
2799 tx: Transaction,
2800 signers: Vec<&impl iota_sdk_crypto::Signer<SimpleSignature>>,
2801 ) -> Self {
2802 let signatures = {
2803 let digest = tx.signing_digest();
2804 signers.into_iter().map(|s| s.sign(&digest)).collect()
2805 };
2806 Self::from_data(tx, signatures)
2807 }
2808
2809 pub fn from_data(tx: Transaction, signatures: Vec<SimpleSignature>) -> Self {
2811 Self::from_user_sig_data(tx, signatures.into_iter().map(|s| s.into()).collect())
2812 }
2813
2814 pub fn signature_from_signer(
2815 tx: Transaction,
2816 intent: Intent,
2817 signer: &impl iota_sdk_crypto::Signer<SimpleSignature>,
2818 ) -> SimpleSignature {
2819 let digest = IntentMessage::new(intent, tx).signing_digest();
2820 signer.sign(&digest)
2821 }
2822
2823 pub fn from_user_sig_data(tx: Transaction, signatures: Vec<UserSignature>) -> Self {
2824 Self::new(SenderSignedTransaction::new(tx, signatures))
2825 }
2826
2827 pub fn to_tx_bytes_and_signatures(&self) -> (Base64, Vec<Base64>) {
2830 (
2831 Base64::from_bytes(&self.data().transaction().to_bcs()),
2832 self.data()
2833 .signatures()
2834 .iter()
2835 .map(|s| Base64::from_bytes(&s.to_bytes()))
2836 .collect(),
2837 )
2838 }
2839}
2840
2841impl VerifiedTransaction {
2842 pub fn new_genesis_transaction(objects: Vec<GenesisObject>, events: Vec<Event>) -> Self {
2843 GenesisTransaction { objects, events }
2844 .pipe(TransactionKind::Genesis)
2845 .pipe(Self::new_system_transaction)
2846 }
2847
2848 pub fn new_consensus_commit_prologue_v1(
2849 epoch: u64,
2850 round: u64,
2851 commit_timestamp_ms: CheckpointTimestamp,
2852 consensus_commit_digest: ConsensusCommitDigest,
2853 canceled_transactions: Vec<CanceledTransaction>,
2854 ) -> Self {
2855 ConsensusCommitPrologueV1 {
2856 epoch,
2857 round,
2858 sub_dag_index: None,
2860 commit_timestamp_ms,
2861 consensus_commit_digest,
2862 consensus_determined_version_assignments:
2863 ConsensusDeterminedVersionAssignments::CanceledTransactions {
2864 canceled_transactions,
2865 },
2866 }
2867 .pipe(TransactionKind::ConsensusCommitPrologueV1)
2868 .pipe(Self::new_system_transaction)
2869 }
2870
2871 pub fn new_randomness_state_update(
2872 epoch: u64,
2873 randomness_round: RandomnessRound,
2874 random_bytes: Vec<u8>,
2875 randomness_obj_initial_shared_version: Version,
2876 ) -> Self {
2877 RandomnessStateUpdate {
2878 epoch,
2879 randomness_round,
2880 random_bytes,
2881 randomness_obj_initial_shared_version,
2882 }
2883 .pipe(TransactionKind::RandomnessStateUpdate)
2884 .pipe(Self::new_system_transaction)
2885 }
2886
2887 pub fn new_end_of_epoch_transaction(txns: Vec<EndOfEpochTransactionKind>) -> Self {
2888 TransactionKind::EndOfEpoch(txns).pipe(Self::new_system_transaction)
2889 }
2890
2891 pub fn new_transaction_deny_rules_update(update: TransactionDenyRulesUpdate) -> Self {
2892 TransactionKind::TransactionDenyRulesUpdate(update).pipe(Self::new_system_transaction)
2893 }
2894
2895 fn new_system_transaction(system_transaction: TransactionKind) -> Self {
2896 system_transaction
2897 .pipe(Transaction::new_system_transaction)
2898 .pipe(|data| {
2899 SenderSignedTransaction::new_from_sender_signature(data, zero_ed25519_signature())
2900 })
2901 .pipe(TransactionEnvelope::new)
2902 .pipe(Self::new_from_verified)
2903 }
2904}
2905
2906impl VerifiedSignedTransaction {
2907 #[instrument(level = "trace", skip_all)]
2909 pub fn new(
2910 epoch: EpochId,
2911 transaction: VerifiedTransaction,
2912 authority: AuthorityName,
2913 secret: &dyn Signer<AuthoritySignature>,
2914 ) -> Self {
2915 Self::new_from_verified(SignedTransaction::new(
2916 epoch,
2917 transaction.into_inner().into_data(),
2918 secret,
2919 authority,
2920 ))
2921 }
2922}
2923
2924fn check_claimed_key_derives_sender(data: &Transaction) -> UserInputResult {
2934 let TransactionKind::ClaimAccount(claim) = data.kind() else {
2935 return Ok(());
2936 };
2937 let smart = match &claim.kind {
2938 AccountClaimKind::SmartAccount(smart) => smart,
2939 _ => {
2940 unimplemented!("a new AccountClaimKind enum variant was added and needs to be handled")
2941 }
2942 };
2943
2944 let scheme = SignatureScheme::from_byte(smart.public_key_scheme).map_err(|error| {
2946 UserInputError::IncorrectUserSignature {
2947 error: format!("invalid claimed public key: {error}"),
2948 }
2949 })?;
2950 let public_key =
2951 MovePublicKey::new(scheme, smart.public_key_raw_bytes.clone()).map_err(|error| {
2952 UserInputError::IncorrectUserSignature {
2953 error: format!("invalid claimed public key: {error}"),
2954 }
2955 })?;
2956 let derived = public_key
2957 .address()
2958 .map_err(|error| UserInputError::IncorrectUserSignature {
2959 error: format!("invalid claimed public key: {error}"),
2960 })?;
2961 fp_ensure!(
2962 derived == data.sender(),
2963 UserInputError::IncorrectUserSignature {
2964 error: format!(
2965 "claimed public key derives {} but the sender is {}",
2966 derived,
2967 data.sender()
2968 ),
2969 }
2970 );
2971 Ok(())
2972}
2973
2974pub fn claim_account_min_gas_budget(
2981 config: &ProtocolConfig,
2982 gas_price: u64,
2983 public_key_len: u64,
2984) -> u64 {
2985 let computation = config
2986 .claim_account_max_computation_units()
2987 .saturating_mul(gas_price);
2988 let storage = config
2989 .claim_account_storage_bytes_bound()
2990 .saturating_add(public_key_len)
2991 .saturating_mul(config.obj_data_cost_refundable())
2992 .saturating_mul(config.storage_gas_price());
2993 computation.saturating_add(storage)
2994}
2995
2996pub(crate) fn claim_account_min_gas_budget_of_transaction(
3000 data: &Transaction,
3001 config: &ProtocolConfig,
3002) -> Option<u64> {
3003 if !config.enable_claim_account_transaction() {
3004 return None;
3005 }
3006 let TransactionKind::ClaimAccount(claim) = data.kind() else {
3007 return None;
3008 };
3009 let smart = match &claim.kind {
3010 AccountClaimKind::SmartAccount(smart) => smart,
3011 _ => {
3012 unimplemented!("a new AccountClaimKind enum variant was added and needs to be handled")
3013 }
3014 };
3015 Some(claim_account_min_gas_budget(
3018 config,
3019 data.gas_price(),
3020 smart.public_key_raw_bytes.len() as u64,
3021 ))
3022}
3023
3024pub fn check_claim_account_gas_budget(
3032 data: &Transaction,
3033 config: &ProtocolConfig,
3034) -> UserInputResult {
3035 let Some(min_budget) = claim_account_min_gas_budget_of_transaction(data, config) else {
3036 return Ok(());
3037 };
3038 fp_ensure!(
3039 data.gas_budget() >= min_budget,
3040 UserInputError::GasBudgetTooLow {
3041 gas_budget: data.gas_budget(),
3042 min_budget,
3043 }
3044 );
3045 Ok(())
3046}
3047
3048pub type TransactionEnvelope = Envelope<SenderSignedTransaction, EmptySignInfo>;
3050pub type VerifiedTransaction = VerifiedEnvelope<SenderSignedTransaction, EmptySignInfo>;
3051pub type TrustedTransaction = TrustedEnvelope<SenderSignedTransaction, EmptySignInfo>;
3052
3053pub type SignedTransaction = Envelope<SenderSignedTransaction, AuthoritySignInfo>;
3055pub type VerifiedSignedTransaction = VerifiedEnvelope<SenderSignedTransaction, AuthoritySignInfo>;
3056
3057impl TransactionEnvelope {
3058 pub fn verify_signature_for_testing(&self, verify_params: &VerifyParams) -> IotaResult {
3059 verify_sender_signed_data_message_signatures(self.data(), verify_params)
3060 }
3061
3062 pub fn try_into_verified_for_testing(
3063 self,
3064 verify_params: &VerifyParams,
3065 ) -> IotaResult<VerifiedTransaction> {
3066 self.verify_signature_for_testing(verify_params)?;
3067 Ok(VerifiedTransaction::new_from_verified(self))
3068 }
3069
3070 pub fn gas_price(&self) -> u64 {
3071 self.data().transaction().gas_price()
3072 }
3073}
3074
3075impl SignedTransaction {
3076 pub fn verify_signatures_authenticated_for_testing(
3077 &self,
3078 committee: &Committee,
3079 verify_params: &VerifyParams,
3080 ) -> IotaResult {
3081 verify_sender_signed_data_message_signatures(self.data(), verify_params)?;
3082
3083 self.auth_sig().verify_secure(
3084 self.data(),
3085 Intent::iota_app(IntentScope::SenderSignedTransaction),
3086 committee,
3087 )
3088 }
3089
3090 pub fn try_into_verified_for_testing(
3091 self,
3092 committee: &Committee,
3093 verify_params: &VerifyParams,
3094 ) -> IotaResult<VerifiedSignedTransaction> {
3095 self.verify_signatures_authenticated_for_testing(committee, verify_params)?;
3096 Ok(VerifiedSignedTransaction::new_from_verified(self))
3097 }
3098}
3099
3100pub type CertifiedTransaction = Envelope<SenderSignedTransaction, AuthorityStrongQuorumSignInfo>;
3101
3102impl CertifiedTransaction {
3103 pub fn certificate_digest(&self) -> CertificateDigest {
3104 let mut digest = DefaultHash::default();
3105 bcs::serialize_into(&mut digest, self).expect("serialization should not fail");
3106 let hash = digest.finalize();
3107 CertificateDigest::new(hash.into())
3108 }
3109
3110 pub fn gas_price(&self) -> u64 {
3111 self.data().transaction().gas_price()
3112 }
3113
3114 #[instrument(level = "trace", skip_all)]
3117 pub fn verify_signatures_authenticated(
3118 &self,
3119 committee: &Committee,
3120 verify_params: &VerifyParams,
3121 ) -> IotaResult {
3122 verify_sender_signed_data_message_signatures(self.data(), verify_params)?;
3123 self.verify_committee_sigs_only(committee)
3124 }
3125
3126 pub fn try_into_verified_for_testing(
3127 self,
3128 committee: &Committee,
3129 verify_params: &VerifyParams,
3130 ) -> IotaResult<VerifiedCertificate> {
3131 self.verify_signatures_authenticated(committee, verify_params)?;
3132 Ok(VerifiedCertificate::new_from_verified(self))
3133 }
3134
3135 pub fn verify_committee_sigs_only(&self, committee: &Committee) -> IotaResult {
3136 self.auth_sig().verify_secure(
3137 self.data(),
3138 Intent::iota_app(IntentScope::SenderSignedTransaction),
3139 committee,
3140 )
3141 }
3142}
3143
3144pub type VerifiedCertificate =
3145 VerifiedEnvelope<SenderSignedTransaction, AuthorityStrongQuorumSignInfo>;
3146pub type TrustedCertificate =
3147 TrustedEnvelope<SenderSignedTransaction, AuthorityStrongQuorumSignInfo>;
3148
3149#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord, Hash)]
3150pub enum InputObjectKind {
3151 MovePackage(ObjectId),
3153 ImmOrOwnedMoveObject(ObjectReference),
3155 SharedMoveObject {
3157 id: ObjectId,
3158 initial_shared_version: Version,
3159 mutable: bool,
3160 },
3161}
3162
3163impl InputObjectKind {
3164 pub fn object_id(&self) -> ObjectId {
3165 match self {
3166 Self::MovePackage(id) => *id,
3167 Self::ImmOrOwnedMoveObject(object_ref) => object_ref.object_id,
3168 Self::SharedMoveObject { id, .. } => *id,
3169 }
3170 }
3171
3172 pub fn version(&self) -> Option<Version> {
3173 match self {
3174 Self::MovePackage(..) => None,
3175 Self::ImmOrOwnedMoveObject(object_ref) => Some(object_ref.version),
3176 Self::SharedMoveObject { .. } => None,
3177 }
3178 }
3179
3180 pub fn object_not_found_error(&self) -> UserInputError {
3181 match *self {
3182 Self::MovePackage(package_id) => {
3183 UserInputError::DependentPackageNotFound { package_id }
3184 }
3185 Self::ImmOrOwnedMoveObject(object_ref) => UserInputError::ObjectNotFound {
3186 object_id: object_ref.object_id,
3187 version: Some(object_ref.version),
3188 },
3189 Self::SharedMoveObject { id, .. } => UserInputError::ObjectNotFound {
3190 object_id: id,
3191 version: None,
3192 },
3193 }
3194 }
3195
3196 pub fn not_available_at_commit_error(&self) -> UserInputError {
3200 let (object_id, version) = match *self {
3201 Self::MovePackage(package_id) => (package_id, None),
3202 Self::ImmOrOwnedMoveObject(object_ref) => {
3203 (object_ref.object_id, Some(object_ref.version))
3204 }
3205 Self::SharedMoveObject { id, .. } => (id, None),
3206 };
3207 UserInputError::InputObjectNotAvailableAtCommit { object_id, version }
3208 }
3209
3210 pub fn is_shared_object(&self) -> bool {
3211 matches!(self, Self::SharedMoveObject { .. })
3212 }
3213
3214 pub fn is_mutable(&self) -> bool {
3215 match self {
3216 Self::MovePackage(..) => false,
3217 Self::ImmOrOwnedMoveObject(_) => true,
3218 Self::SharedMoveObject { mutable, .. } => *mutable,
3219 }
3220 }
3221
3222 pub fn left_union_with_checks(&mut self, other: &InputObjectKind) -> UserInputResult<()> {
3228 match self {
3229 InputObjectKind::MovePackage(_) | InputObjectKind::ImmOrOwnedMoveObject(_) => {
3230 fp_ensure!(
3231 self == other,
3232 UserInputError::InconsistentInput {
3233 object_id: other.object_id(),
3234 }
3235 );
3236 }
3237 InputObjectKind::SharedMoveObject {
3238 id,
3239 initial_shared_version,
3240 mutable,
3241 } => match other {
3242 InputObjectKind::MovePackage(_) | InputObjectKind::ImmOrOwnedMoveObject(_) => {
3243 fp_bail!(UserInputError::NotSharedObject)
3244 }
3245 InputObjectKind::SharedMoveObject {
3246 id: other_id,
3247 initial_shared_version: other_initial_shared_version,
3248 mutable: other_mutable,
3249 } => {
3250 fp_ensure!(id == other_id, UserInputError::SharedObjectIdMismatch);
3251 fp_ensure!(
3252 initial_shared_version == other_initial_shared_version,
3253 UserInputError::SharedObjectStartingVersionMismatch
3254 );
3255
3256 if !*mutable && *other_mutable {
3257 *mutable = *other_mutable;
3258 }
3259 }
3260 },
3261 }
3262
3263 Ok(())
3264 }
3265
3266 pub fn check_consistency_for_authentication(
3270 &self,
3271 other: &InputObjectKind,
3272 ) -> UserInputResult<()> {
3273 match self {
3274 InputObjectKind::MovePackage(_) | InputObjectKind::ImmOrOwnedMoveObject(_) => {
3275 fp_ensure!(
3276 self == other,
3277 UserInputError::InconsistentInput {
3278 object_id: self.object_id()
3279 }
3280 );
3281 }
3282 InputObjectKind::SharedMoveObject {
3283 id,
3284 initial_shared_version,
3285 mutable: _,
3286 } => match other {
3287 InputObjectKind::MovePackage(_) | InputObjectKind::ImmOrOwnedMoveObject(_) => {
3288 fp_bail!(UserInputError::InconsistentInput {
3289 object_id: self.object_id()
3290 })
3291 }
3292 InputObjectKind::SharedMoveObject {
3293 id: other_id,
3294 initial_shared_version: other_initial_shared_version,
3295 mutable: _,
3296 } => {
3297 fp_ensure!(
3298 id == other_id,
3299 UserInputError::InconsistentInput { object_id: *id }
3300 );
3301 fp_ensure!(
3302 initial_shared_version == other_initial_shared_version,
3303 UserInputError::InconsistentInput { object_id: *id }
3304 );
3305 }
3306 },
3307 }
3308
3309 Ok(())
3310 }
3311}
3312
3313#[derive(Clone, Debug)]
3317pub struct ObjectReadResult {
3318 pub input_object_kind: InputObjectKind,
3319 pub object: ObjectReadResultKind,
3320}
3321
3322#[derive(Clone, PartialEq)]
3323pub enum ObjectReadResultKind {
3324 Object(Object),
3325 DeletedSharedObject(Version, TransactionDigest),
3328 CancelledTransactionObject(Version),
3330 UnreadSharedObject,
3335}
3336
3337impl std::fmt::Debug for ObjectReadResultKind {
3338 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3339 match self {
3340 ObjectReadResultKind::Object(obj) => {
3341 write!(f, "Object({:?})", obj.object_ref())
3342 }
3343 ObjectReadResultKind::DeletedSharedObject(seq, digest) => {
3344 write!(f, "DeletedSharedObject({seq}, {digest})")
3345 }
3346 ObjectReadResultKind::CancelledTransactionObject(seq) => {
3347 write!(f, "CancelledTransactionObject({seq})")
3348 }
3349 ObjectReadResultKind::UnreadSharedObject => write!(f, "UnreadSharedObject"),
3350 }
3351 }
3352}
3353
3354impl From<Object> for ObjectReadResultKind {
3355 fn from(object: Object) -> Self {
3356 Self::Object(object)
3357 }
3358}
3359
3360impl ObjectReadResult {
3361 pub fn new(input_object_kind: InputObjectKind, object: ObjectReadResultKind) -> Self {
3362 if let (
3363 InputObjectKind::ImmOrOwnedMoveObject(_),
3364 ObjectReadResultKind::DeletedSharedObject(_, _),
3365 ) = (&input_object_kind, &object)
3366 {
3367 panic!("only shared objects can be DeletedSharedObject");
3368 }
3369
3370 if let (
3371 InputObjectKind::ImmOrOwnedMoveObject(_),
3372 ObjectReadResultKind::CancelledTransactionObject(_),
3373 ) = (&input_object_kind, &object)
3374 {
3375 panic!("only shared objects can be CancelledTransactionObject");
3376 }
3377
3378 if let (
3379 InputObjectKind::ImmOrOwnedMoveObject(_),
3380 ObjectReadResultKind::UnreadSharedObject,
3381 ) = (&input_object_kind, &object)
3382 {
3383 panic!("only shared objects can be UnreadSharedObject");
3384 }
3385
3386 Self {
3387 input_object_kind,
3388 object,
3389 }
3390 }
3391
3392 pub fn id(&self) -> ObjectId {
3393 self.input_object_kind.object_id()
3394 }
3395
3396 pub fn as_object(&self) -> Option<&Object> {
3397 match &self.object {
3398 ObjectReadResultKind::Object(object) => Some(object),
3399 ObjectReadResultKind::DeletedSharedObject(_, _) => None,
3400 ObjectReadResultKind::CancelledTransactionObject(_) => None,
3401 ObjectReadResultKind::UnreadSharedObject => None,
3402 }
3403 }
3404
3405 pub fn version(&self) -> Version {
3408 match &self.object {
3409 ObjectReadResultKind::Object(object) => object.version(),
3410 ObjectReadResultKind::DeletedSharedObject(version, _) => *version,
3411 ObjectReadResultKind::CancelledTransactionObject(version) => *version,
3412 ObjectReadResultKind::UnreadSharedObject => {
3413 unreachable!("an unread shared object has no version to execute at")
3414 }
3415 }
3416 }
3417
3418 pub fn new_from_gas_object(gas: &Object) -> Self {
3419 let objref = gas.object_ref();
3420 Self {
3421 input_object_kind: InputObjectKind::ImmOrOwnedMoveObject(objref),
3422 object: ObjectReadResultKind::Object(gas.clone()),
3423 }
3424 }
3425
3426 pub fn is_mutable(&self) -> bool {
3427 match (&self.input_object_kind, &self.object) {
3428 (InputObjectKind::MovePackage(_), _) => false,
3429 (InputObjectKind::ImmOrOwnedMoveObject(_), ObjectReadResultKind::Object(object)) => {
3430 !object.is_immutable()
3431 }
3432 (
3433 InputObjectKind::ImmOrOwnedMoveObject(_),
3434 ObjectReadResultKind::DeletedSharedObject(_, _),
3435 ) => unreachable!(),
3436 (
3437 InputObjectKind::ImmOrOwnedMoveObject(_),
3438 ObjectReadResultKind::CancelledTransactionObject(_),
3439 ) => unreachable!(),
3440 (
3441 InputObjectKind::ImmOrOwnedMoveObject(_),
3442 ObjectReadResultKind::UnreadSharedObject,
3443 ) => unreachable!(),
3444 (InputObjectKind::SharedMoveObject { mutable, .. }, _) => *mutable,
3445 }
3446 }
3447
3448 pub fn is_shared_object(&self) -> bool {
3449 self.input_object_kind.is_shared_object()
3450 }
3451
3452 pub fn is_deleted_shared_object(&self) -> bool {
3453 self.deletion_info().is_some()
3454 }
3455
3456 pub fn deletion_info(&self) -> Option<(Version, TransactionDigest)> {
3457 match &self.object {
3458 ObjectReadResultKind::DeletedSharedObject(v, tx) => Some((*v, *tx)),
3459 _ => None,
3460 }
3461 }
3462
3463 pub fn get_owned_objref(&self) -> Option<ObjectReference> {
3466 match (&self.input_object_kind, &self.object) {
3467 (InputObjectKind::MovePackage(_), _) => None,
3468 (
3469 InputObjectKind::ImmOrOwnedMoveObject(objref),
3470 ObjectReadResultKind::Object(object),
3471 ) => {
3472 if object.is_immutable() {
3473 None
3474 } else {
3475 Some(*objref)
3476 }
3477 }
3478 (
3479 InputObjectKind::ImmOrOwnedMoveObject(_),
3480 ObjectReadResultKind::DeletedSharedObject(_, _),
3481 ) => unreachable!(),
3482 (
3483 InputObjectKind::ImmOrOwnedMoveObject(_),
3484 ObjectReadResultKind::CancelledTransactionObject(_),
3485 ) => unreachable!(),
3486 (
3487 InputObjectKind::ImmOrOwnedMoveObject(_),
3488 ObjectReadResultKind::UnreadSharedObject,
3489 ) => unreachable!(),
3490 (InputObjectKind::SharedMoveObject { .. }, _) => None,
3491 }
3492 }
3493
3494 pub fn is_owned(&self) -> bool {
3495 self.get_owned_objref().is_some()
3496 }
3497
3498 pub fn to_shared_input(&self) -> Option<SharedInput> {
3499 match self.input_object_kind {
3500 InputObjectKind::MovePackage(_) => None,
3501 InputObjectKind::ImmOrOwnedMoveObject(_) => None,
3502 InputObjectKind::SharedMoveObject { id, mutable, .. } => Some(match &self.object {
3503 ObjectReadResultKind::Object(obj) => SharedInput::Existing(obj.object_ref()),
3504 ObjectReadResultKind::DeletedSharedObject(seq, digest) => {
3505 SharedInput::Deleted((id, *seq, mutable, *digest))
3506 }
3507 ObjectReadResultKind::CancelledTransactionObject(seq) => {
3508 SharedInput::Cancelled((id, *seq))
3509 }
3510 ObjectReadResultKind::UnreadSharedObject => {
3511 unreachable!("an unread shared object has no version to execute at")
3512 }
3513 }),
3514 }
3515 }
3516
3517 pub fn get_previous_transaction(&self) -> Option<TransactionDigest> {
3518 match &self.object {
3519 ObjectReadResultKind::Object(obj) => Some(obj.previous_transaction),
3520 ObjectReadResultKind::DeletedSharedObject(_, digest) => Some(*digest),
3521 ObjectReadResultKind::CancelledTransactionObject(_) => None,
3522 ObjectReadResultKind::UnreadSharedObject => None,
3523 }
3524 }
3525}
3526
3527#[derive(Clone, Debug, PartialEq, Eq)]
3530pub enum CancelledObjects {
3531 SharedObjects(Vec<ObjectId>),
3533 GasObject,
3538}
3539
3540#[derive(Clone)]
3541pub struct InputObjects {
3542 objects: Vec<ObjectReadResult>,
3543 gas_object_cancellation: Option<(ObjectId, Version)>,
3550 transaction_dependency: Option<TransactionDependencyReadResult>,
3555}
3556
3557#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
3560pub struct TransactionDependencyReadResult {
3561 pub digest: TransactionDigest,
3562 pub succeeded: bool,
3563}
3564
3565impl std::fmt::Debug for InputObjects {
3566 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3567 match (&self.gas_object_cancellation, &self.transaction_dependency) {
3568 (None, None) => f.debug_list().entries(self.objects.iter()).finish(),
3569 (gas_object_cancellation, transaction_dependency) => f
3570 .debug_struct("InputObjects")
3571 .field("objects", &self.objects)
3572 .field("gas_object_cancellation", gas_object_cancellation)
3573 .field("transaction_dependency", transaction_dependency)
3574 .finish(),
3575 }
3576 }
3577}
3578
3579pub struct CheckedInputObjects(InputObjects);
3582
3583impl CheckedInputObjects {
3589 pub fn new_with_checked_transaction_inputs(inputs: InputObjects) -> Self {
3591 Self(inputs)
3592 }
3593
3594 pub fn new_for_genesis(input_objects: Vec<ObjectReadResult>) -> Self {
3596 Self(InputObjects::new(input_objects))
3597 }
3598
3599 pub fn new_for_replay(input_objects: InputObjects) -> Self {
3601 Self(input_objects)
3602 }
3603
3604 pub fn inner(&self) -> &InputObjects {
3605 &self.0
3606 }
3607
3608 pub fn into_inner(self) -> InputObjects {
3609 self.0
3610 }
3611}
3612
3613impl From<Vec<ObjectReadResult>> for InputObjects {
3614 fn from(objects: Vec<ObjectReadResult>) -> Self {
3615 Self::new(objects)
3616 }
3617}
3618
3619impl InputObjects {
3620 pub fn new(objects: Vec<ObjectReadResult>) -> Self {
3621 Self {
3622 objects,
3623 gas_object_cancellation: None,
3624 transaction_dependency: None,
3625 }
3626 }
3627
3628 pub fn set_gas_object_cancellation(&mut self, gas_object_id: ObjectId, version: Version) {
3633 assert!(
3634 version.is_canceled(),
3635 "gas object cancellation must use a cancellation version, got {version:?}"
3636 );
3637 assert!(
3638 !self.objects.iter().any(|obj| obj.is_shared_object()),
3639 "transactions with shared inputs carry cancellation on their shared objects"
3640 );
3641 self.gas_object_cancellation = Some((gas_object_id, version));
3642 }
3643
3644 pub fn gas_object_cancellation(&self) -> Option<(ObjectId, Version)> {
3645 self.gas_object_cancellation
3646 }
3647
3648 pub fn len(&self) -> usize {
3649 self.objects.len()
3650 }
3651
3652 pub fn is_empty(&self) -> bool {
3653 self.objects.is_empty()
3654 }
3655
3656 pub fn contains_deleted_objects(&self) -> bool {
3657 self.objects
3658 .iter()
3659 .any(|obj| obj.is_deleted_shared_object())
3660 }
3661
3662 pub fn get_cancelled_objects(&self) -> Option<(CancelledObjects, Version)> {
3665 if let Some((_, version)) = &self.gas_object_cancellation {
3666 return Some((CancelledObjects::GasObject, *version));
3667 }
3668
3669 let mut contains_cancelled = false;
3670 let mut cancel_reason = None;
3671 let mut cancelled_objects = Vec::new();
3672 for obj in &self.objects {
3673 if let ObjectReadResultKind::CancelledTransactionObject(version) = obj.object {
3674 contains_cancelled = true;
3675 if version.is_congested() || version == Version::RANDOMNESS_UNAVAILABLE {
3676 assert!(cancel_reason.is_none() || cancel_reason == Some(version));
3678 cancel_reason = Some(version);
3679 cancelled_objects.push(obj.id());
3680 }
3681 }
3682 }
3683
3684 if !cancelled_objects.is_empty() {
3685 Some((
3686 CancelledObjects::SharedObjects(cancelled_objects),
3687 cancel_reason
3688 .expect("there should be a cancel reason if there are cancelled objects"),
3689 ))
3690 } else {
3691 assert!(!contains_cancelled);
3692 None
3693 }
3694 }
3695
3696 pub fn filter_owned_objects(&self) -> Vec<ObjectReference> {
3697 let owned_objects: Vec<_> = self
3698 .objects
3699 .iter()
3700 .filter_map(|obj| obj.get_owned_objref())
3701 .collect();
3702
3703 trace!(
3704 num_mutable_objects = owned_objects.len(),
3705 "Checked locks and found mutable objects"
3706 );
3707
3708 owned_objects
3709 }
3710
3711 pub fn filter_shared_objects(&self) -> Vec<SharedInput> {
3712 self.objects
3713 .iter()
3714 .filter(|obj| obj.is_shared_object())
3715 .map(|obj| {
3716 obj.to_shared_input()
3717 .expect("already filtered for shared objects")
3718 })
3719 .collect()
3720 }
3721
3722 pub fn transaction_dependencies(&self) -> BTreeSet<TransactionDigest> {
3723 self.objects
3724 .iter()
3725 .filter_map(|obj| obj.get_previous_transaction())
3726 .chain(
3727 self.transaction_dependency
3728 .map(|dependency| dependency.digest),
3729 )
3730 .collect()
3731 }
3732
3733 pub fn set_transaction_dependency(&mut self, dependency: TransactionDependencyReadResult) {
3734 self.transaction_dependency = Some(dependency);
3735 }
3736
3737 pub fn transaction_dependency(&self) -> Option<TransactionDependencyReadResult> {
3738 self.transaction_dependency
3739 }
3740
3741 pub fn failed_transaction_dependency(&self) -> Option<TransactionDigest> {
3745 self.transaction_dependency
3746 .filter(|dependency| !dependency.succeeded)
3747 .map(|dependency| dependency.digest)
3748 }
3749
3750 pub fn mutable_inputs(&self) -> BTreeMap<ObjectId, (VersionDigest, Owner)> {
3751 self.objects
3752 .iter()
3753 .filter_map(
3754 |ObjectReadResult {
3755 input_object_kind,
3756 object,
3757 }| match (input_object_kind, object) {
3758 (InputObjectKind::MovePackage(_), _) => None,
3759 (
3760 InputObjectKind::ImmOrOwnedMoveObject(object_ref),
3761 ObjectReadResultKind::Object(object),
3762 ) => {
3763 if object.is_immutable() {
3764 None
3765 } else {
3766 Some((
3767 object_ref.object_id,
3768 ((object_ref.version, object_ref.digest), object.owner),
3769 ))
3770 }
3771 }
3772 (
3773 InputObjectKind::ImmOrOwnedMoveObject(_),
3774 ObjectReadResultKind::DeletedSharedObject(_, _),
3775 ) => {
3776 unreachable!()
3777 }
3778 (
3779 InputObjectKind::SharedMoveObject { .. },
3780 ObjectReadResultKind::DeletedSharedObject(_, _),
3781 ) => None,
3782 (
3783 InputObjectKind::SharedMoveObject { mutable, .. },
3784 ObjectReadResultKind::Object(object),
3785 ) => {
3786 if *mutable {
3787 let oref = object.object_ref();
3788 Some((oref.object_id, ((oref.version, oref.digest), object.owner)))
3789 } else {
3790 None
3791 }
3792 }
3793 (
3794 InputObjectKind::ImmOrOwnedMoveObject(_),
3795 ObjectReadResultKind::CancelledTransactionObject(_),
3796 ) => {
3797 unreachable!()
3798 }
3799 (
3800 InputObjectKind::SharedMoveObject { .. },
3801 ObjectReadResultKind::CancelledTransactionObject(_),
3802 ) => None,
3803 (
3804 InputObjectKind::ImmOrOwnedMoveObject(_),
3805 ObjectReadResultKind::UnreadSharedObject,
3806 ) => {
3807 unreachable!()
3808 }
3809 (
3810 InputObjectKind::SharedMoveObject { .. },
3811 ObjectReadResultKind::UnreadSharedObject,
3812 ) => {
3813 unreachable!("an unread shared object has no version, digest or owner")
3814 }
3815 },
3816 )
3817 .collect()
3818 }
3819
3820 pub fn lamport_timestamp(&self, receiving_objects: &[ObjectReference]) -> Version {
3824 let input_versions = self
3825 .objects
3826 .iter()
3827 .filter_map(|object| match &object.object {
3828 ObjectReadResultKind::Object(object) => {
3829 object.data.as_opt_struct().map(MoveStruct::version)
3830 }
3831 ObjectReadResultKind::DeletedSharedObject(v, _) => Some(*v),
3832 ObjectReadResultKind::CancelledTransactionObject(_) => None,
3833 ObjectReadResultKind::UnreadSharedObject => {
3834 unreachable!("an unread shared object has no version to exceed")
3835 }
3836 })
3837 .chain(
3838 receiving_objects
3839 .iter()
3840 .map(|object_ref| object_ref.version),
3841 );
3842
3843 Version::lamport_increment(input_versions).unwrap()
3844 }
3845
3846 pub fn object_kinds(&self) -> impl Iterator<Item = &InputObjectKind> {
3847 self.objects.iter().map(
3848 |ObjectReadResult {
3849 input_object_kind, ..
3850 }| input_object_kind,
3851 )
3852 }
3853
3854 pub fn into_object_map(self) -> BTreeMap<ObjectId, Object> {
3855 self.objects
3856 .into_iter()
3857 .filter_map(|o| o.as_object().map(|object| (o.id(), object.clone())))
3858 .collect()
3859 }
3860
3861 pub fn push(&mut self, object: ObjectReadResult) {
3862 self.objects.push(object);
3863 }
3864
3865 pub fn find_object_id_mut(&mut self, object_id: ObjectId) -> Option<&mut ObjectReadResult> {
3867 self.objects.iter_mut().find(|o| o.id() == object_id)
3868 }
3869
3870 pub fn iter(&self) -> impl Iterator<Item = &ObjectReadResult> {
3871 self.objects.iter()
3872 }
3873
3874 pub fn iter_objects(&self) -> impl Iterator<Item = &Object> {
3875 self.objects.iter().filter_map(|o| o.as_object())
3876 }
3877}
3878
3879#[derive(Clone, Debug)]
3883pub enum ReceivingObjectReadResultKind {
3884 Object(Object),
3885 PreviouslyReceivedObject,
3887}
3888
3889impl ReceivingObjectReadResultKind {
3890 pub fn as_object(&self) -> Option<&Object> {
3891 match &self {
3892 Self::Object(object) => Some(object),
3893 Self::PreviouslyReceivedObject => None,
3894 }
3895 }
3896}
3897
3898pub struct ReceivingObjectReadResult {
3899 pub object_ref: ObjectReference,
3900 pub object: ReceivingObjectReadResultKind,
3901}
3902
3903impl ReceivingObjectReadResult {
3904 pub fn new(object_ref: ObjectReference, object: ReceivingObjectReadResultKind) -> Self {
3905 Self { object_ref, object }
3906 }
3907
3908 pub fn is_previously_received(&self) -> bool {
3909 matches!(
3910 self.object,
3911 ReceivingObjectReadResultKind::PreviouslyReceivedObject
3912 )
3913 }
3914}
3915
3916impl From<Object> for ReceivingObjectReadResultKind {
3917 fn from(object: Object) -> Self {
3918 Self::Object(object)
3919 }
3920}
3921
3922pub struct ReceivingObjects {
3923 pub objects: Vec<ReceivingObjectReadResult>,
3924}
3925
3926impl ReceivingObjects {
3927 pub fn iter(&self) -> impl Iterator<Item = &ReceivingObjectReadResult> {
3928 self.objects.iter()
3929 }
3930
3931 pub fn iter_objects(&self) -> impl Iterator<Item = &Object> {
3932 self.objects.iter().filter_map(|o| o.object.as_object())
3933 }
3934}
3935
3936impl From<Vec<ReceivingObjectReadResult>> for ReceivingObjects {
3937 fn from(objects: Vec<ReceivingObjectReadResult>) -> Self {
3938 Self { objects }
3939 }
3940}
3941
3942impl Display for CertifiedTransaction {
3943 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
3944 let mut writer = String::new();
3945 writeln!(writer, "Transaction Hash: {:?}", self.digest())?;
3946 writeln!(
3947 writer,
3948 "Signed Authorities Bitmap : {:?}",
3949 self.auth_sig().signers_map
3950 )?;
3951 write!(writer, "{}", self.data().transaction().kind())?;
3952 write!(f, "{writer}")
3953 }
3954}
3955
3956#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
3961pub enum TransactionKey {
3962 Digest(TransactionDigest),
3963 RandomnessRound(EpochId, RandomnessRound),
3964}
3965
3966impl TransactionKey {
3967 pub fn unwrap_digest(&self) -> &TransactionDigest {
3968 match self {
3969 TransactionKey::Digest(d) => d,
3970 _ => panic!("called expect_digest on a non-Digest TransactionKey: {self:?}"),
3971 }
3972 }
3973
3974 pub fn as_digest(&self) -> Option<&TransactionDigest> {
3975 match self {
3976 TransactionKey::Digest(d) => Some(d),
3977 _ => None,
3978 }
3979 }
3980}