1use std::{
7 convert::{TryFrom, TryInto},
8 fmt,
9 str::FromStr,
10};
11
12use anyhow::anyhow;
13use fastcrypto::hash::HashFunction;
14use iota_protocol_config::ProtocolConfig;
15use iota_sdk_types::{
16 Address, Identifier, MoveObjectType, ObjectDigest, ObjectId, ObjectReference, Owner,
17 SignatureScheme, StructTag, TransactionDigest, TransactionEffects, TransactionEffectsDigest,
18 TypeTag, Version,
19};
20use move_binary_format::{CompiledModule, file_format::SignatureToken};
21use move_bytecode_utils::resolve_struct;
22use move_core_types::{
23 account_address::AccountAddress, annotated_value as A, ident_str, identifier::IdentStr,
24};
25use serde::{Deserialize, Serialize, ser::Error};
26
27pub use crate::committee::EpochId;
28use crate::{
29 IOTA_FRAMEWORK_ADDRESS, MOVE_STDLIB_ADDRESS,
30 crypto::{AuthorityPublicKeyBytes, DefaultHash, PublicKey},
31 digests::ChainIdentifier,
32 effects::{TransactionEffectsAPI, TransactionEffectsExt},
33 epoch_data::EpochData,
34 error::{ExecutionError, ExecutionErrorKind},
35 iota_sdk_types_conversions::struct_tag_sdk_to_core,
36 iota_serde::to_iota_struct_tag_string,
37 messages_checkpoint::CheckpointTimestamp,
38 object::Object,
39 parse_iota_struct_tag,
40 transaction::{TransactionEnvelope, VerifiedTransaction},
41};
42
43#[cfg(test)]
44#[path = "unit_tests/base_types_tests.rs"]
45mod base_types_tests;
46
47pub type TxSequenceNumber = u64;
48
49pub type VersionNumber = Version;
50
51pub type CommitRound = u64;
53
54pub type AuthorityName = AuthorityPublicKeyBytes;
55
56pub trait ConciseableName<'a> {
57 type ConciseTypeRef: std::fmt::Debug;
58 type ConciseType: std::fmt::Debug;
59
60 fn concise(&'a self) -> Self::ConciseTypeRef;
61 fn concise_owned(&self) -> Self::ConciseType;
62}
63
64pub type VersionDigest = (Version, ObjectDigest);
65
66pub fn random_object_ref() -> ObjectReference {
67 ObjectReference::new(
68 ObjectId::random(),
69 Version::default(),
70 ObjectDigest::new([0; 32]),
71 )
72}
73
74pub fn is_primitive_type_tag(t: &TypeTag) -> bool {
76 use TypeTag as T;
77
78 match t {
79 T::Bool | T::U8 | T::U16 | T::U32 | T::U64 | T::U128 | T::U256 | T::Address => true,
80 T::Vector(inner) => is_primitive_type_tag(inner),
81 T::Struct(st) => {
82 let resolved_struct = (
83 &AccountAddress::new(st.address().into_bytes()),
84 move_core_types::identifier::IdentStr::new(st.module().as_str()).unwrap(),
85 move_core_types::identifier::IdentStr::new(st.name().as_str()).unwrap(),
86 );
87 if resolved_struct == RESOLVED_IOTA_ID {
89 return true;
90 }
91 if resolved_struct == RESOLVED_UTF8_STR {
93 return true;
94 }
95 if resolved_struct == RESOLVED_ASCII_STR {
97 return true;
98 }
99 resolved_struct == RESOLVED_STD_OPTION
101 && st.type_params().len() == 1
102 && is_primitive_type_tag(&st.type_params()[0])
103 }
104 T::Signer => false,
105 }
106}
107
108#[derive(Clone, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq, Debug)]
110pub enum ObjectType {
111 Package,
113 Struct(MoveObjectType),
115}
116
117const PACKAGE: &str = "package";
118
119impl ObjectType {
120 pub fn is_gas_coin(&self) -> bool {
121 matches!(self, ObjectType::Struct(s) if s.is_gas_coin())
122 }
123
124 pub fn is_coin(&self) -> bool {
125 matches!(self, ObjectType::Struct(s) if s.is_coin())
126 }
127
128 pub fn is_package(&self) -> bool {
129 matches!(self, ObjectType::Package)
130 }
131}
132
133impl From<&Object> for ObjectType {
134 fn from(o: &Object) -> Self {
135 o.data
136 .opt_object_type()
137 .map(|t| ObjectType::Struct(t.clone()))
138 .unwrap_or(ObjectType::Package)
139 }
140}
141
142impl TryFrom<ObjectType> for StructTag {
143 type Error = anyhow::Error;
144
145 fn try_from(o: ObjectType) -> Result<Self, anyhow::Error> {
146 match o {
147 ObjectType::Package => Err(anyhow!("Cannot create StructTag from Package")),
148 ObjectType::Struct(s) => Ok(s.into()),
149 }
150 }
151}
152
153impl FromStr for ObjectType {
154 type Err = anyhow::Error;
155
156 fn from_str(s: &str) -> Result<Self, Self::Err> {
157 if s.to_lowercase() == PACKAGE {
158 Ok(ObjectType::Package)
159 } else {
160 let tag = parse_iota_struct_tag(s)?;
161 Ok(ObjectType::Struct(tag.into()))
162 }
163 }
164}
165
166#[derive(Clone, Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq, Debug)]
167pub struct ObjectInfo {
168 pub object_id: ObjectId,
169 pub version: Version,
170 pub digest: ObjectDigest,
171 pub object_type: ObjectType,
172 pub owner: Owner,
173 pub previous_transaction: TransactionDigest,
174}
175
176impl ObjectInfo {
177 pub fn new(oref: &ObjectReference, o: &Object) -> Self {
178 Self {
179 object_id: oref.object_id,
180 version: oref.version,
181 digest: oref.digest,
182 object_type: o.into(),
183 owner: o.owner,
184 previous_transaction: o.previous_transaction,
185 }
186 }
187
188 pub fn from_object(object: &Object) -> Self {
189 Self {
190 object_id: object.id(),
191 version: object.version(),
192 digest: object.digest(),
193 object_type: object.into(),
194 owner: object.owner,
195 previous_transaction: object.previous_transaction,
196 }
197 }
198}
199
200impl From<ObjectInfo> for ObjectReference {
201 fn from(info: ObjectInfo) -> Self {
202 ObjectReference::new(info.object_id, info.version, info.digest)
203 }
204}
205
206impl From<&ObjectInfo> for ObjectReference {
207 fn from(info: &ObjectInfo) -> Self {
208 ObjectReference::new(info.object_id, info.version, info.digest)
209 }
210}
211
212pub const IOTA_ADDRESS_LENGTH: usize = ObjectId::LENGTH;
213
214fn update_hasher_with_flag(hasher: &mut DefaultHash, scheme: SignatureScheme) {
217 if scheme != SignatureScheme::Ed25519 {
218 hasher.update([scheme.to_u8()]);
219 }
220}
221
222impl From<&PublicKey> for Address {
223 fn from(pk: &PublicKey) -> Self {
224 let mut hasher = DefaultHash::default();
225 update_hasher_with_flag(&mut hasher, pk.scheme());
226 hasher.update(pk);
227 let g_arr = hasher.finalize();
228 Address::new(g_arr.digest)
229 }
230}
231
232pub fn dbg_addr(name: u8) -> Address {
234 let addr = [name; IOTA_ADDRESS_LENGTH];
235 Address::new(addr)
236}
237
238#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash, Serialize, Deserialize, Debug)]
239pub struct ExecutionDigests {
240 pub transaction: TransactionDigest,
241 pub effects: TransactionEffectsDigest,
242}
243
244impl ExecutionDigests {
245 pub fn new(transaction: TransactionDigest, effects: TransactionEffectsDigest) -> Self {
246 Self {
247 transaction,
248 effects,
249 }
250 }
251
252 pub fn random() -> Self {
253 Self {
254 transaction: TransactionDigest::random(),
255 effects: TransactionEffectsDigest::random(),
256 }
257 }
258}
259
260#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
261pub struct ExecutionData {
262 pub transaction: TransactionEnvelope,
263 pub effects: TransactionEffects,
264}
265
266impl ExecutionData {
267 pub fn new(transaction: TransactionEnvelope, effects: TransactionEffects) -> ExecutionData {
268 debug_assert_eq!(transaction.digest(), effects.transaction_digest());
269 Self {
270 transaction,
271 effects,
272 }
273 }
274
275 pub fn digests(&self) -> ExecutionDigests {
276 self.effects.execution_digests()
277 }
278}
279
280#[derive(Clone, Eq, PartialEq, Debug)]
281pub struct VerifiedExecutionData {
282 pub transaction: VerifiedTransaction,
283 pub effects: TransactionEffects,
284}
285
286impl VerifiedExecutionData {
287 pub fn new(transaction: VerifiedTransaction, effects: TransactionEffects) -> Self {
288 debug_assert_eq!(transaction.digest(), effects.transaction_digest());
289 Self {
290 transaction,
291 effects,
292 }
293 }
294
295 pub fn new_unchecked(data: ExecutionData) -> Self {
296 Self {
297 transaction: VerifiedTransaction::new_unchecked(data.transaction),
298 effects: data.effects,
299 }
300 }
301
302 pub fn into_inner(self) -> ExecutionData {
303 ExecutionData {
304 transaction: self.transaction.into_inner(),
305 effects: self.effects,
306 }
307 }
308
309 pub fn digests(&self) -> ExecutionDigests {
310 self.effects.execution_digests()
311 }
312}
313
314pub const RESOLVED_STD_OPTION: (&AccountAddress, &IdentStr, &IdentStr) = (
315 &MOVE_STDLIB_ADDRESS,
316 ident_str!("option"),
317 ident_str!("Option"),
318);
319
320pub const RESOLVED_ASCII_STR: (&AccountAddress, &IdentStr, &IdentStr) = (
321 &MOVE_STDLIB_ADDRESS,
322 ident_str!("ascii"),
323 ident_str!("String"),
324);
325
326pub const RESOLVED_UTF8_STR: (&AccountAddress, &IdentStr, &IdentStr) = (
327 &MOVE_STDLIB_ADDRESS,
328 ident_str!("string"),
329 ident_str!("String"),
330);
331
332pub const RESOLVED_TX_CONTEXT: (&AccountAddress, &IdentStr, &IdentStr) = (
333 &crate::IOTA_FRAMEWORK_ADDRESS,
334 ident_str!("tx_context"),
335 ident_str!("TxContext"),
336);
337
338pub const RESOLVED_IOTA_ID: (&AccountAddress, &IdentStr, &IdentStr) = (
339 &IOTA_FRAMEWORK_ADDRESS,
340 ident_str!("object"),
341 ident_str!("ID"),
342);
343
344pub fn move_ascii_str_layout() -> A::MoveStructLayout {
345 A::MoveStructLayout {
346 type_: struct_tag_sdk_to_core(&StructTag::new_ascii_string()),
347 fields: vec![A::MoveFieldLayout::new(
348 ident_str!("bytes").into(),
349 A::MoveTypeLayout::Vector(Box::new(A::MoveTypeLayout::U8)),
350 )],
351 }
352}
353
354pub fn move_utf8_str_layout() -> A::MoveStructLayout {
355 A::MoveStructLayout {
356 type_: struct_tag_sdk_to_core(&StructTag::new_string()),
357 fields: vec![A::MoveFieldLayout::new(
358 ident_str!("bytes").into(),
359 A::MoveTypeLayout::Vector(Box::new(A::MoveTypeLayout::U8)),
360 )],
361 }
362}
363
364pub fn url_layout() -> A::MoveStructLayout {
365 A::MoveStructLayout {
366 type_: struct_tag_sdk_to_core(&StructTag::new_url()),
367 fields: vec![A::MoveFieldLayout::new(
368 ident_str!("url").to_owned(),
369 A::MoveTypeLayout::Struct(Box::new(move_ascii_str_layout())),
370 )],
371 }
372}
373
374#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
384pub struct MoveLegacyTxContext {
385 sender: AccountAddress,
387 digest: Vec<u8>,
389 epoch: EpochId,
391 epoch_timestamp_ms: CheckpointTimestamp,
393 ids_created: u64,
395}
396
397impl From<&TxContext> for MoveLegacyTxContext {
398 fn from(tx_context: &TxContext) -> Self {
399 Self {
400 sender: tx_context.sender,
401 digest: tx_context.digest.clone(),
402 epoch: tx_context.epoch,
403 epoch_timestamp_ms: tx_context.epoch_timestamp_ms,
404 ids_created: tx_context.ids_created,
405 }
406 }
407}
408
409#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
412pub struct TxContext {
413 sender: AccountAddress,
415 digest: Vec<u8>,
417 epoch: EpochId,
419 epoch_timestamp_ms: CheckpointTimestamp,
421 ids_created: u64,
424 rgp: u64,
426 gas_price: u64,
428 gas_budget: u64,
430 sponsor: Option<AccountAddress>,
432 chain_identifier: ChainIdentifier,
434 nonce: Option<[u8; 32]>,
438 is_native: bool,
441}
442
443#[derive(PartialEq, Eq, Clone, Copy)]
444pub enum TxContextKind {
445 None,
447 Mutable,
449 Immutable,
451}
452
453impl TxContext {
454 pub fn new(
455 sender: &Address,
456 digest: &TransactionDigest,
457 epoch_data: &EpochData,
458 rgp: u64,
459 gas_price: u64,
460 gas_budget: u64,
461 sponsor: Option<Address>,
462 chain_identifier: ChainIdentifier,
463 nonce: Option<[u8; 32]>,
464 protocol_config: &ProtocolConfig,
465 ) -> Self {
466 Self::new_from_components(
467 sender,
468 digest,
469 &epoch_data.epoch_id(),
470 epoch_data.epoch_start_timestamp(),
471 rgp,
472 gas_price,
473 gas_budget,
474 sponsor,
475 chain_identifier,
476 nonce,
477 protocol_config,
478 )
479 }
480
481 pub fn new_from_components(
482 sender: &Address,
483 digest: &TransactionDigest,
484 epoch_id: &EpochId,
485 epoch_timestamp_ms: u64,
486 rgp: u64,
487 gas_price: u64,
488 gas_budget: u64,
489 sponsor: Option<Address>,
490 chain_identifier: ChainIdentifier,
491 nonce: Option<[u8; 32]>,
492 protocol_config: &ProtocolConfig,
493 ) -> Self {
494 Self {
495 sender: AccountAddress::new(sender.into_bytes()),
496 digest: digest.into_bytes().to_vec(),
497 epoch: *epoch_id,
498 epoch_timestamp_ms,
499 ids_created: 0,
500 rgp,
501 gas_price,
502 gas_budget,
503 sponsor: sponsor.map(|s| AccountAddress::new(s.into_bytes())),
504 chain_identifier,
505 nonce,
506 is_native: protocol_config.move_native_tx_context(),
507 }
508 }
509
510 pub fn kind(view: &CompiledModule, s: &SignatureToken) -> TxContextKind {
513 use SignatureToken as S;
514 let (kind, s) = match s {
515 S::MutableReference(s) => (TxContextKind::Mutable, s),
516 S::Reference(s) => (TxContextKind::Immutable, s),
517 _ => return TxContextKind::None,
518 };
519
520 let S::Datatype(idx) = &**s else {
521 return TxContextKind::None;
522 };
523
524 let (module_addr, module_name, struct_name) = resolve_struct(view, *idx);
525 let is_tx_context_type = module_name.as_str() == Identifier::TX_CONTEXT_MODULE.as_str()
526 && module_addr.as_ref() == Address::FRAMEWORK.as_bytes()
527 && struct_name.as_str() == Identifier::TX_CONTEXT.as_str();
528
529 if is_tx_context_type {
530 kind
531 } else {
532 TxContextKind::None
533 }
534 }
535
536 pub fn epoch(&self) -> EpochId {
537 self.epoch
538 }
539
540 pub fn epoch_timestamp_ms(&self) -> u64 {
541 self.epoch_timestamp_ms
542 }
543
544 pub fn digest(&self) -> TransactionDigest {
546 TransactionDigest::new(self.digest.clone().try_into().unwrap())
547 }
548
549 pub fn sponsor(&self) -> Option<Address> {
550 self.sponsor.map(|a| Address::from(a.into_bytes()))
551 }
552
553 pub fn chain_identifier(&self) -> ChainIdentifier {
554 self.chain_identifier
555 }
556
557 pub fn rgp(&self) -> u64 {
558 self.rgp
559 }
560
561 pub fn gas_price(&self) -> u64 {
562 self.gas_price
563 }
564
565 pub fn gas_budget(&self) -> u64 {
566 self.gas_budget
567 }
568
569 pub fn ids_created(&self) -> u64 {
570 self.ids_created
571 }
572
573 pub fn fresh_id(&mut self) -> ObjectId {
576 let id = ObjectId::derive_id(self.digest(), self.ids_created);
577 self.ids_created += 1;
578 id
579 }
580
581 pub fn sender(&self) -> Address {
582 Address::new(self.sender.into_bytes())
583 }
584
585 pub fn nonce(&self) -> Option<[u8; 32]> {
587 self.nonce
588 }
589
590 pub fn to_vec(&self) -> Vec<u8> {
591 bcs::to_bytes(&self).unwrap()
592 }
593
594 pub fn to_bcs_legacy_context(&self) -> Vec<u8> {
598 let move_context: MoveLegacyTxContext = if self.is_native {
599 let tx_context = &TxContext {
600 sender: AccountAddress::ZERO,
601 digest: vec![],
602 epoch: 0,
603 epoch_timestamp_ms: 0,
604 ids_created: 0,
605 rgp: 0,
606 gas_price: 0,
607 gas_budget: 0,
608 sponsor: None,
609 chain_identifier: ChainIdentifier::default(),
610 nonce: None,
611 is_native: true,
612 };
613 tx_context.into()
614 } else {
615 self.into()
616 };
617 bcs::to_bytes(&move_context).unwrap()
618 }
619
620 pub fn update_state(&mut self, other: MoveLegacyTxContext) -> Result<(), ExecutionError> {
625 if !self.is_native {
626 if self.sender != other.sender
627 || self.digest != other.digest
628 || other.ids_created < self.ids_created
629 {
630 return Err(ExecutionError::new_with_source(
631 ExecutionErrorKind::InvariantViolation,
632 "Immutable fields for TxContext changed",
633 ));
634 }
635 self.ids_created = other.ids_created;
636 }
637 Ok(())
638 }
639
640 pub fn replace(
644 &mut self,
645 sender: AccountAddress,
646 tx_hash: Vec<u8>,
647 epoch: u64,
648 epoch_timestamp_ms: u64,
649 ids_created: u64,
650 rgp: u64,
651 gas_price: u64,
652 gas_budget: u64,
653 sponsor: Option<AccountAddress>,
654 ) {
655 self.sender = sender;
656 self.digest = tx_hash;
657 self.epoch = epoch;
658 self.epoch_timestamp_ms = epoch_timestamp_ms;
659 self.ids_created = ids_created;
660 self.rgp = rgp;
661 self.gas_price = gas_price;
662 self.gas_budget = gas_budget;
663 self.sponsor = sponsor;
664 }
665
666 pub fn set_chain_identifier(&mut self, chain_identifier: ChainIdentifier) {
668 self.chain_identifier = chain_identifier;
669 }
670
671 pub fn replace_nonce(&mut self, nonce: Option<[u8; 32]>) {
673 self.nonce = nonce;
674 }
675
676 #[cfg(not(target_arch = "wasm32"))]
678 pub fn random_for_testing_only() -> Self {
679 Self::new(
680 &Address::random(),
681 &TransactionDigest::random(),
682 &EpochData::new_test(),
683 0,
684 0,
685 0,
686 None,
687 ChainIdentifier::default(),
688 None,
689 &ProtocolConfig::get_for_max_version_UNSAFE(),
690 )
691 }
692}
693
694pub fn dbg_object_id(name: u8) -> ObjectId {
696 ObjectId::new([name; ObjectId::LENGTH])
697}
698
699#[derive(PartialEq, Eq, Clone, Debug, thiserror::Error)]
700pub enum ObjectIdParseError {
701 #[error("ObjectId hex literal must start with 0x")]
702 HexLiteralPrefixMissing,
703
704 #[error("Could not convert from bytes slice")]
705 TryFromSlice,
706}
707
708impl fmt::Display for ObjectType {
709 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
710 match self {
711 ObjectType::Package => write!(f, "{PACKAGE}"),
712 ObjectType::Struct(t) => write!(
713 f,
714 "{}",
715 to_iota_struct_tag_string(t).map_err(fmt::Error::custom)?
716 ),
717 }
718 }
719}