From 39d9339a64f6edf9ff7f00b457fec61e10621333 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Garillot?= Date: Fri, 11 Feb 2022 11:28:13 -0500 Subject: [PATCH] chore: replace FastPay -> Sui --- CONTRIBUTING.md | 2 +- fastpay/src/bench.rs | 6 +- fastpay/src/config.rs | 20 ++-- fastpay/src/wallet_commands.rs | 22 ++--- fastpay_core/src/authority.rs | 86 ++++++++--------- fastpay_core/src/authority/authority_store.rs | 47 ++++------ fastpay_core/src/authority/temporary_store.rs | 8 +- fastpay_core/src/authority_aggregator.rs | 74 +++++++-------- fastpay_core/src/authority_client.rs | 30 +++--- fastpay_core/src/authority_server.rs | 4 +- fastpay_core/src/client.rs | 61 ++++++------ fastpay_core/src/client/client_store.rs | 2 +- fastpay_core/src/generate_format.rs | 6 +- fastpay_core/src/safe_client.rs | 38 ++++---- .../src/unit_tests/authority_tests.rs | 26 +++--- fastpay_core/src/unit_tests/client_tests.rs | 49 +++++----- fastx_programmability/adapter/src/adapter.rs | 93 +++++++++---------- fastx_programmability/adapter/src/genesis.rs | 4 +- .../adapter/src/unit_tests/adapter_tests.rs | 90 +++++++----------- fastx_programmability/framework/src/lib.rs | 12 +-- .../src/global_storage_access_verifier.rs | 6 +- .../verifier/src/id_immutable_verifier.rs | 6 +- .../verifier/src/id_leak_verifier.rs | 16 ++-- fastx_programmability/verifier/src/lib.rs | 6 +- .../verifier/src/struct_with_key_verifier.rs | 6 +- .../verifier/src/verifier.rs | 4 +- fastx_types/src/base_types.rs | 52 +++++------ fastx_types/src/error.rs | 14 +-- fastx_types/src/gas.rs | 12 +-- fastx_types/src/gas_coin.rs | 16 ++-- fastx_types/src/messages.rs | 61 ++++++------ fastx_types/src/object.rs | 50 +++++----- fastx_types/src/serialize.rs | 22 ++--- fastx_types/src/unit_tests/serialize_tests.rs | 2 +- network_utils/src/network.rs | 8 +- 35 files changed, 450 insertions(+), 511 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e2bbeb6c8cad4..868c0d09c882c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,7 +10,7 @@ $ cargo test ## Coding Guidelines for Rust code -For detailed guidance on how to contribute to the Rust code in the Fastpay repository refer to [Coding Guidelines](https://developers.libra.org/docs/coding-guidelines). +For detailed guidance on how to contribute to the Rust code in the Sui repository refer to [Coding Guidelines](https://developers.libra.org/docs/coding-guidelines). ## Pull Requests diff --git a/fastpay/src/bench.rs b/fastpay/src/bench.rs index 2d36305eabdbb..72ddefc6b5e12 100644 --- a/fastpay/src/bench.rs +++ b/fastpay/src/bench.rs @@ -30,8 +30,8 @@ use strum_macros::EnumString; #[derive(Debug, Clone, StructOpt)] #[structopt( - name = "FastPay Benchmark", - about = "Local end-to-end test and benchmark of the FastPay protocol" + name = "Sui Benchmark", + about = "Local end-to-end test and benchmark of the Sui protocol" )] struct ClientServerBenchmark { /// Hostname @@ -43,7 +43,7 @@ struct ClientServerBenchmark { /// Base port number #[structopt(long, default_value = "9555")] port: u16, - /// Size of the FastPay committee + /// Size of the Sui committee #[structopt(long, default_value = "10")] committee_size: usize, /// Maximum number of requests in flight (0 for blocking client) diff --git a/fastpay/src/config.rs b/fastpay/src/config.rs index 77917db771fe4..31f36e2383ca6 100644 --- a/fastpay/src/config.rs +++ b/fastpay/src/config.rs @@ -29,7 +29,7 @@ pub struct AuthorityConfig { serialize_with = "address_as_hex", deserialize_with = "address_from_hex" )] - pub address: FastPayAddress, + pub address: SuiAddress, pub host: String, pub base_port: u16, pub database_path: String, @@ -104,7 +104,7 @@ pub struct UserAccount { serialize_with = "address_as_hex", deserialize_with = "address_from_hex" )] - pub address: FastPayAddress, + pub address: SuiAddress, pub key: KeyPair, pub object_refs: BTreeMap, pub gas_object_ids: BTreeSet, // Every id in gas_object_ids should also be in object_ids. @@ -114,7 +114,7 @@ pub struct UserAccount { impl UserAccount { pub fn new( - address: FastPayAddress, + address: SuiAddress, key: KeyPair, object_refs: Vec, gas_object_ids: Vec, @@ -195,13 +195,13 @@ impl MoveCallConfig { } pub struct AccountsConfig { - accounts: BTreeMap, + accounts: BTreeMap, } impl AccountsConfig { /// Beware: this removes the account from the `AccountConfig` map! /// better make sure we only use this once per account! - pub fn remove(&mut self, address: &FastPayAddress) -> Option { + pub fn remove(&mut self, address: &SuiAddress) -> Option { self.accounts.remove(address) } @@ -226,7 +226,7 @@ impl AccountsConfig { self.accounts.values_mut() } - pub fn addresses(&mut self) -> impl Iterator { + pub fn addresses(&mut self) -> impl Iterator { self.accounts.keys() } @@ -284,7 +284,7 @@ impl AccountsConfig { #[derive(Serialize, Deserialize)] pub struct InitialStateConfigEntry { - pub address: FastPayAddress, + pub address: SuiAddress, pub objects: Vec, } #[derive(Serialize, Deserialize)] @@ -334,7 +334,7 @@ pub struct AccountInfo { serialize_with = "address_as_hex", deserialize_with = "address_from_hex" )] - pub address: FastPayAddress, + pub address: SuiAddress, pub key_pair: KeyPair, } @@ -344,7 +344,7 @@ pub struct AuthorityInfo { serialize_with = "address_as_hex", deserialize_with = "address_from_hex" )] - pub address: FastPayAddress, + pub address: SuiAddress, pub host: String, pub base_port: u16, } @@ -355,7 +355,7 @@ pub struct AuthorityPrivateInfo { serialize_with = "address_as_hex", deserialize_with = "address_from_hex" )] - pub address: FastPayAddress, + pub address: SuiAddress, pub key_pair: KeyPair, pub host: String, pub port: u16, diff --git a/fastpay/src/wallet_commands.rs b/fastpay/src/wallet_commands.rs index 4b839f7dadb96..7264e1416cf3e 100644 --- a/fastpay/src/wallet_commands.rs +++ b/fastpay/src/wallet_commands.rs @@ -5,14 +5,14 @@ use fastpay_core::authority_client::AuthorityClient; use fastpay_core::client::{Client, ClientState}; use fastx_network::network::NetworkClient; use fastx_types::base_types::{ - decode_address_hex, encode_address_hex, get_key_pair, AuthorityName, FastPayAddress, ObjectID, - PublicKeyBytes, + decode_address_hex, encode_address_hex, get_key_pair, AuthorityName, ObjectID, PublicKeyBytes, + SuiAddress, }; use fastx_types::committee::Committee; use fastx_types::messages::{ExecutionStatus, OrderEffects}; use crate::utils::Config; -use fastx_types::error::FastPayError; +use fastx_types::error::SuiError; use move_core_types::identifier::Identifier; use move_core_types::language_storage::TypeTag; use move_core_types::parser::{parse_transaction_argument, parse_type_tag}; @@ -327,7 +327,7 @@ fn make_authority_clients( pub struct WalletContext { pub config: WalletConfig, - pub client_states: BTreeMap>, + pub client_states: BTreeMap>, } impl WalletContext { @@ -338,7 +338,7 @@ impl WalletContext { } } - pub fn find_owner(&self, object_id: &ObjectID) -> Result { + pub fn find_owner(&self, object_id: &ObjectID) -> Result { self.client_states .iter() .find_map(|(owner, client_state)| { @@ -349,14 +349,14 @@ impl WalletContext { } }) .copied() - .ok_or(FastPayError::ObjectNotFound { + .ok_or(SuiError::ObjectNotFound { object_id: *object_id, }) } pub fn get_or_create_client_state( &mut self, - owner: &FastPayAddress, + owner: &SuiAddress, ) -> Result<&mut ClientState, anyhow::Error> { Ok(if !self.client_states.contains_key(owner) { let new_client = self.create_client_state(owner)?; @@ -368,8 +368,8 @@ impl WalletContext { fn create_client_state( &self, - owner: &FastPayAddress, - ) -> Result, FastPayError> { + owner: &SuiAddress, + ) -> Result, SuiError> { let client_info = self.get_account_info(owner)?; let voting_rights = self @@ -395,11 +395,11 @@ impl WalletContext { ) } - pub fn get_account_info(&self, address: &FastPayAddress) -> Result<&AccountInfo, FastPayError> { + pub fn get_account_info(&self, address: &SuiAddress) -> Result<&AccountInfo, SuiError> { self.config .accounts .iter() .find(|info| &info.address == address) - .ok_or(FastPayError::AccountNotFound) + .ok_or(SuiError::AccountNotFound) } } diff --git a/fastpay_core/src/authority.rs b/fastpay_core/src/authority.rs index 278126bc02844..1d7b51c595e43 100644 --- a/fastpay_core/src/authority.rs +++ b/fastpay_core/src/authority.rs @@ -5,7 +5,7 @@ use fastx_adapter::{adapter, genesis}; use fastx_types::{ base_types::*, committee::Committee, - error::{FastPayError, FastPayResult}, + error::{SuiError, SuiResult}, fp_bail, fp_ensure, gas, messages::*, object::{Data, Object}, @@ -45,7 +45,7 @@ pub struct AuthorityState { // Fixed size, static, identity of the authority /// The name of this authority. pub name: AuthorityName, - /// Committee of this FastPay instance. + /// Committee of this Sui instance. pub committee: Committee, /// The signature key of the authority. pub secret: StableSyncSigner, @@ -73,12 +73,12 @@ impl AuthorityState { object_kind: InputObjectKind, object: &Object, mutable_object_ids: &HashSet, - ) -> FastPayResult { + ) -> SuiResult { match object_kind { InputObjectKind::MovePackage(package_id) => { fp_ensure!( object.data.try_as_package().is_some(), - FastPayError::MoveObjectAsPackage { + SuiError::MoveObjectAsPackage { object_id: package_id } ); @@ -86,13 +86,13 @@ impl AuthorityState { InputObjectKind::MoveObject((object_id, sequence_number, object_digest)) => { fp_ensure!( sequence_number <= SequenceNumber::max(), - FastPayError::InvalidSequenceNumber + SuiError::InvalidSequenceNumber ); // Check that the seq number is the same fp_ensure!( object.version() == sequence_number, - FastPayError::UnexpectedSequenceNumber { + SuiError::UnexpectedSequenceNumber { object_id, expected_sequence: object.version(), } @@ -101,7 +101,7 @@ impl AuthorityState { // Check the digest matches fp_ensure!( object.digest() == object_digest, - FastPayError::InvalidObjectDigest { + SuiError::InvalidObjectDigest { object_id, expected_digest: object_digest } @@ -111,7 +111,7 @@ impl AuthorityState { // Gas object must not be immutable. fp_ensure!( &object_id != order.gas_payment_object_id(), - FastPayError::InsufficientGas { + SuiError::InsufficientGas { error: "Gas object should not be immutable".to_string() } ); @@ -126,13 +126,10 @@ impl AuthorityState { match &object.owner { // TODO: More detailed error message for IncorrectSigner. Authenticator::Address(addr) => { - fp_ensure!(order.sender() == addr, FastPayError::IncorrectSigner); + fp_ensure!(order.sender() == addr, SuiError::IncorrectSigner); } Authenticator::Object(id) => { - fp_ensure!( - mutable_object_ids.contains(id), - FastPayError::IncorrectSigner - ); + fp_ensure!(mutable_object_ids.contains(id), SuiError::IncorrectSigner); } }; @@ -146,22 +143,19 @@ impl AuthorityState { /// Check all the objects used in the order against the database, and ensure /// that they are all the correct version and number. - async fn check_locks( - &self, - order: &Order, - ) -> Result, FastPayError> { + async fn check_locks(&self, order: &Order) -> Result, SuiError> { let input_objects = order.input_objects(); let mut all_objects = Vec::with_capacity(input_objects.len()); // There is at least one input fp_ensure!( !input_objects.is_empty(), - FastPayError::ObjectInputArityViolation + SuiError::ObjectInputArityViolation ); // Ensure that there are no duplicate inputs let mut used = HashSet::new(); if !input_objects.iter().all(|o| used.insert(o.object_id())) { - return Err(FastPayError::DuplicateObjectRefInput); + return Err(SuiError::DuplicateObjectRefInput); } let ids: Vec<_> = input_objects.iter().map(|kind| kind.object_id()).collect(); @@ -195,19 +189,16 @@ impl AuthorityState { // If any errors with the locks were detected, we return all errors to give the client // a chance to update the authority if possible. if !errors.is_empty() { - return Err(FastPayError::LockErrors { errors }); + return Err(SuiError::LockErrors { errors }); } - fp_ensure!( - !all_objects.is_empty(), - FastPayError::ObjectInputArityViolation - ); + fp_ensure!(!all_objects.is_empty(), SuiError::ObjectInputArityViolation); Ok(all_objects) } /// Initiate a new order. - pub async fn handle_order(&self, order: Order) -> Result { + pub async fn handle_order(&self, order: Order) -> Result { // Check the sender's signature. order.check_signature()?; let transaction_digest = order.digest(); @@ -244,7 +235,7 @@ impl AuthorityState { pub async fn handle_confirmation_order( &self, confirmation_order: ConfirmationOrder, - ) -> Result { + ) -> Result { let certificate = confirmation_order.certificate; let order = certificate.order.clone(); let transaction_digest = order.digest(); @@ -299,7 +290,7 @@ impl AuthorityState { order: Order, mut inputs: Vec, tx_ctx: &mut TxContext, - ) -> FastPayResult<(AuthorityTemporaryStore, ExecutionStatus)> { + ) -> SuiResult<(AuthorityTemporaryStore, ExecutionStatus)> { let mut temporary_store = AuthorityTemporaryStore::new(self, &inputs, tx_ctx.digest()); // unwraps here are safe because we built `inputs` let mut gas_object = inputs.pop().unwrap(); @@ -353,13 +344,13 @@ impl AuthorityState { fn transfer( temporary_store: &mut AuthorityTemporaryStore, mut inputs: Vec, - recipient: FastPayAddress, + recipient: SuiAddress, mut gas_object: Object, - ) -> FastPayResult { + ) -> SuiResult { if !inputs.len() == 1 { return Ok(ExecutionStatus::Failure { gas_used: gas::MIN_OBJ_TRANSFER_GAS, - error: Box::new(FastPayError::ObjectInputArityViolation), + error: Box::new(SuiError::ObjectInputArityViolation), }); } @@ -378,7 +369,7 @@ impl AuthorityState { if output_object.is_read_only() { return Ok(ExecutionStatus::Failure { gas_used: gas::MIN_OBJ_TRANSFER_GAS, - error: Box::new(FastPayError::CannotTransferReadOnlyObject), + error: Box::new(SuiError::CannotTransferReadOnlyObject), }); } @@ -390,21 +381,21 @@ impl AuthorityState { pub async fn handle_order_info_request( &self, request: OrderInfoRequest, - ) -> Result { + ) -> Result { self.make_order_info(&request.transaction_digest).await } pub async fn handle_account_info_request( &self, request: AccountInfoRequest, - ) -> Result { + ) -> Result { self.make_account_info(request.account) } pub async fn handle_object_info_request( &self, request: ObjectInfoRequest, - ) -> Result { + ) -> Result { // Only add a certificate if it is requested let ref_and_digest = if let Some(seq) = request.request_sequence_number { // Get the Transaction Digest that created the object @@ -428,7 +419,7 @@ impl AuthorityState { } else { // Get the cert from the transaction digest Some(self.read_certificate(&transaction_digest).await?.ok_or( - FastPayError::CertificateNotfound { + SuiError::CertificateNotfound { certificate_digest: transaction_digest, }, )?) @@ -509,7 +500,7 @@ impl AuthorityState { } } - async fn get_object(&self, object_id: &ObjectID) -> Result, FastPayError> { + async fn get_object(&self, object_id: &ObjectID) -> Result, SuiError> { self._database.get_object(object_id) } @@ -523,14 +514,11 @@ impl AuthorityState { async fn make_order_info( &self, transaction_digest: &TransactionDigest, - ) -> Result { + ) -> Result { self._database.get_order_info(transaction_digest) } - fn make_account_info( - &self, - account: FastPayAddress, - ) -> Result { + fn make_account_info(&self, account: SuiAddress) -> Result { self._database .get_account_objects(account) .map(|object_ids| AccountInfoResponse { @@ -553,7 +541,7 @@ impl AuthorityState { &self, mutable_input_objects: &[ObjectRef], signed_order: SignedOrder, - ) -> Result<(), FastPayError> { + ) -> Result<(), SuiError> { self._database .set_order_lock(mutable_input_objects, signed_order) } @@ -563,7 +551,7 @@ impl AuthorityState { temporary_store: AuthorityTemporaryStore, certificate: CertifiedOrder, signed_effects: SignedOrderEffects, - ) -> Result { + ) -> Result { self._database .update_state(temporary_store, certificate, signed_effects) } @@ -572,7 +560,7 @@ impl AuthorityState { pub async fn get_order_lock( &self, object_ref: &ObjectRef, - ) -> Result, FastPayError> { + ) -> Result, SuiError> { self._database.get_order_lock(object_ref) } @@ -582,7 +570,7 @@ impl AuthorityState { pub async fn read_certificate( &self, digest: &TransactionDigest, - ) -> Result, FastPayError> { + ) -> Result, SuiError> { self._database.read_certificate(digest) } @@ -595,7 +583,7 @@ impl AuthorityState { pub async fn get_objects( &self, _objects: &[ObjectID], - ) -> Result>, FastPayError> { + ) -> Result>, SuiError> { self._database.get_objects(_objects) } @@ -605,7 +593,7 @@ impl AuthorityState { &self, object_id: ObjectID, seq: Option, - ) -> Result, FastPayError> { + ) -> Result, SuiError> { { self._database.get_parent_iterator(object_id, seq) } @@ -614,7 +602,7 @@ impl AuthorityState { pub async fn get_latest_parent_entry( &self, object_id: ObjectID, - ) -> Result, FastPayError> { + ) -> Result, SuiError> { self._database.get_latest_parent_entry(object_id) } @@ -623,7 +611,7 @@ impl AuthorityState { fn get_unwrapped_object_ids( &self, written: &BTreeMap, - ) -> Result, FastPayError> { + ) -> Result, SuiError> { // For each mutated object, we first find out whether there was a transaction // that deleted this object in the past. let parents = self._database.multi_get_parents( diff --git a/fastpay_core/src/authority/authority_store.rs b/fastpay_core/src/authority/authority_store.rs index 8a6092f59fd27..7f9fa8be8f58c 100644 --- a/fastpay_core/src/authority/authority_store.rs +++ b/fastpay_core/src/authority/authority_store.rs @@ -22,7 +22,7 @@ pub struct AuthorityStore { order_lock: DBMap>, /// This is a an index of object references to currently existing objects, indexed by the - /// composite key of the FastPayAddress of their owner and the object ID of the object. + /// composite key of the SuiAddress of their owner and the object ID of the object. /// This composite index allows an efficient iterator to list all objected currently owned /// by a specific user, and their object reference. owner_index: DBMap<(Authenticator, ObjectID), ObjectRef>, @@ -108,10 +108,7 @@ impl AuthorityStore { // Methods to read the store - pub fn get_account_objects( - &self, - account: FastPayAddress, - ) -> Result, FastPayError> { + pub fn get_account_objects(&self, account: SuiAddress) -> Result, SuiError> { let auth = Authenticator::Address(account); Ok(self .owner_index @@ -126,7 +123,7 @@ impl AuthorityStore { pub fn get_order_info( &self, transaction_digest: &TransactionDigest, - ) -> Result { + ) -> Result { Ok(OrderInfoResponse { signed_order: self.signed_orders.get(transaction_digest)?, certified_order: self.certificates.get(transaction_digest)?, @@ -135,24 +132,21 @@ impl AuthorityStore { } /// Read an object and return it, or Err(ObjectNotFound) if the object was not found. - pub fn get_object(&self, object_id: &ObjectID) -> Result, FastPayError> { + pub fn get_object(&self, object_id: &ObjectID) -> Result, SuiError> { self.objects.get(object_id).map_err(|e| e.into()) } /// Get many objects - pub fn get_objects(&self, _objects: &[ObjectID]) -> Result>, FastPayError> { + pub fn get_objects(&self, _objects: &[ObjectID]) -> Result>, SuiError> { self.objects.multi_get(_objects).map_err(|e| e.into()) } /// Read a lock or returns Err(OrderLockDoesNotExist) if the lock does not exist. - pub fn get_order_lock( - &self, - object_ref: &ObjectRef, - ) -> Result, FastPayError> { + pub fn get_order_lock(&self, object_ref: &ObjectRef) -> Result, SuiError> { let order_option = self .order_lock .get(object_ref)? - .ok_or(FastPayError::OrderLockDoesNotExist)?; + .ok_or(SuiError::OrderLockDoesNotExist)?; match order_option { Some(tx_digest) => Ok(Some( @@ -168,16 +162,13 @@ impl AuthorityStore { pub fn read_certificate( &self, digest: &TransactionDigest, - ) -> Result, FastPayError> { + ) -> Result, SuiError> { self.certificates.get(digest).map_err(|e| e.into()) } /// Read the transactionDigest that is the parent of an object reference /// (ie. the transaction that created an object at this version.) - pub fn parent( - &self, - object_ref: &ObjectRef, - ) -> Result, FastPayError> { + pub fn parent(&self, object_ref: &ObjectRef) -> Result, SuiError> { self.parent_sync.get(object_ref).map_err(|e| e.into()) } @@ -185,7 +176,7 @@ impl AuthorityStore { pub fn multi_get_parents( &self, object_refs: &[ObjectRef], - ) -> Result>, FastPayError> { + ) -> Result>, SuiError> { self.parent_sync .multi_get(object_refs) .map_err(|e| e.into()) @@ -197,7 +188,7 @@ impl AuthorityStore { &self, object_id: ObjectID, seq: Option, - ) -> Result, FastPayError> { + ) -> Result, SuiError> { let seq_inner = seq.unwrap_or_else(|| SequenceNumber::from(0)); let obj_dig_inner = ObjectDigest::new([0; 32]); @@ -219,7 +210,7 @@ impl AuthorityStore { // Methods to mutate the store /// Insert an object - pub fn insert_object(&self, object: Object) -> Result<(), FastPayError> { + pub fn insert_object(&self, object: Object) -> Result<(), SuiError> { self.objects.insert(&object.id(), &object)?; // Update the index @@ -238,7 +229,7 @@ impl AuthorityStore { /// Initialize a lock to an object reference to None, but keep it /// as it is if a value is already present. - pub fn init_order_lock(&self, object_ref: ObjectRef) -> Result<(), FastPayError> { + pub fn init_order_lock(&self, object_ref: ObjectRef) -> Result<(), SuiError> { self.order_lock.get_or_insert(&object_ref, || None)?; Ok(()) } @@ -253,7 +244,7 @@ impl AuthorityStore { &self, mutable_input_objects: &[ObjectRef], signed_order: SignedOrder, - ) -> Result<(), FastPayError> { + ) -> Result<(), SuiError> { let tx_digest = signed_order.order.digest(); let lock_batch = self .order_lock @@ -279,7 +270,7 @@ impl AuthorityStore { for (obj_ref, lock) in mutable_input_objects.iter().zip(locks) { // The object / version must exist, and therefore lock initialized. - let lock = lock.ok_or(FastPayError::OrderLockDoesNotExist)?; + let lock = lock.ok_or(SuiError::OrderLockDoesNotExist)?; if let Some(previous_tx_digest) = lock { if previous_tx_digest != tx_digest { @@ -288,7 +279,7 @@ impl AuthorityStore { .expect("If we have a lock we should have an order."); // TODO: modify ConflictingOrder to only return the order digest here. - return Err(FastPayError::ConflictingOrder { + return Err(SuiError::ConflictingOrder { pending_order: prev_order.order, }); } @@ -311,7 +302,7 @@ impl AuthorityStore { temporary_store: AuthorityTemporaryStore, certificate: CertifiedOrder, signed_effects: SignedOrderEffects, - ) -> Result { + ) -> Result { // Extract the new state from the execution // TODO: events are already stored in the TxDigest -> TransactionEffects store. Is that enough? let (objects, active_inputs, written, deleted, _events) = temporary_store.into_inner(); @@ -414,7 +405,7 @@ impl AuthorityStore { // TODO: maybe we could just check if the certificate is there instead? let locks = self.order_lock.multi_get(&active_inputs[..])?; for object_lock in locks { - object_lock.ok_or(FastPayError::OrderLockDoesNotExist)?; + object_lock.ok_or(SuiError::OrderLockDoesNotExist)?; } // Atomic write of all locks & other data @@ -444,7 +435,7 @@ impl AuthorityStore { pub fn get_latest_parent_entry( &self, object_id: ObjectID, - ) -> Result, FastPayError> { + ) -> Result, SuiError> { let mut iterator = self .parent_sync .iter() diff --git a/fastpay_core/src/authority/temporary_store.rs b/fastpay_core/src/authority/temporary_store.rs index 58bf046500681..cf32584fa0218 100644 --- a/fastpay_core/src/authority/temporary_store.rs +++ b/fastpay_core/src/authority/temporary_store.rs @@ -255,7 +255,7 @@ impl Storage for AuthorityTemporaryStore { } impl ModuleResolver for AuthorityTemporaryStore { - type Error = FastPayError; + type Error = SuiError; fn get_module(&self, module_id: &ModuleId) -> Result>, Self::Error> { match self.read_object(module_id.address()) { Some(o) => match &o.data { @@ -263,7 +263,7 @@ impl ModuleResolver for AuthorityTemporaryStore { .get(module_id.name().as_str()) .cloned() .map(|m| m.into_vec())), - _ => Err(FastPayError::BadObjectType { + _ => Err(SuiError::BadObjectType { error: "Expected module object".to_string(), }), }, @@ -273,7 +273,7 @@ impl ModuleResolver for AuthorityTemporaryStore { } impl ResourceResolver for AuthorityTemporaryStore { - type Error = FastPayError; + type Error = SuiError; fn get_resource( &self, @@ -286,7 +286,7 @@ impl ResourceResolver for AuthorityTemporaryStore { None => return Ok(None), Some(x) => { if !x.is_read_only() { - fp_bail!(FastPayError::ExecutionInvariantViolation); + fp_bail!(SuiError::ExecutionInvariantViolation); } x } diff --git a/fastpay_core/src/authority_aggregator.rs b/fastpay_core/src/authority_aggregator.rs index 91c63b337a9dd..99d646178f35a 100644 --- a/fastpay_core/src/authority_aggregator.rs +++ b/fastpay_core/src/authority_aggregator.rs @@ -8,7 +8,7 @@ use fastx_types::object::{Object, ObjectRead}; use fastx_types::{ base_types::*, committee::Committee, - error::{FastPayError, FastPayResult}, + error::{SuiError, SuiResult}, messages::*, }; use futures::{future, StreamExt}; @@ -30,7 +30,7 @@ mod client_tests; pub type AsyncResult<'a, T, E> = future::BoxFuture<'a, Result>; pub struct AuthorityAggregator { - /// Our FastPay committee. + /// Our Sui committee. pub committee: Committee, /// How to talk to this committee. authority_clients: BTreeMap>, @@ -72,7 +72,7 @@ where cert: ConfirmationOrder, source_authority: AuthorityName, destination_authority: AuthorityName, - ) -> Result<(), FastPayError> { + ) -> Result<(), SuiError> { let source_client = self.authority_clients[&source_authority].clone(); let destination_client = self.authority_clients[&destination_authority].clone(); @@ -95,7 +95,7 @@ where .await { Ok(_) => continue, - Err(FastPayError::LockErrors { .. }) => {} + Err(SuiError::LockErrors { .. }) => {} Err(e) => return Err(e), } @@ -108,7 +108,7 @@ where // to update its dependencies, so we should just admit failure. let cert_digest = target_cert.certificate.order.digest(); if attempted_certificates.contains(&cert_digest) { - return Err(FastPayError::AuthorityInformationUnavailable); + return Err(SuiError::AuthorityInformationUnavailable); } attempted_certificates.insert(cert_digest); @@ -147,7 +147,7 @@ where missing_certificates.push(target_cert); let signed_effects = &order_info .signed_effects - .ok_or(FastPayError::AuthorityInformationUnavailable)?; + .ok_or(SuiError::AuthorityInformationUnavailable)?; for returned_digest in &signed_effects.effects.dependencies { // We check that we are not processing twice the same certificate, as @@ -165,11 +165,11 @@ where let returned_certificate = inner_order_info .certified_order - .ok_or(FastPayError::AuthorityInformationUnavailable)?; + .ok_or(SuiError::AuthorityInformationUnavailable)?; // Check & Add it to the list of certificates to sync returned_certificate.check(&self.committee).map_err(|_| { - FastPayError::ByzantineAuthoritySuspicion { + SuiError::ByzantineAuthoritySuspicion { authority: source_authority, } })?; @@ -194,7 +194,7 @@ where destination_authority: AuthorityName, timeout_period: Duration, retries: usize, - ) -> Result<(), FastPayError> { + ) -> Result<(), SuiError> { // Extract the set of authorities that should have this certificate // and its full history. We should be able to use these are source authorities. let mut candidate_source_authorties: HashSet = cert @@ -250,7 +250,7 @@ where // Eventually we should add more information to this error about the destination // and maybe event the certificiate. - Err(FastPayError::AuthorityUpdateFailure) + Err(SuiError::AuthorityUpdateFailure) } /// This function takes an initial state, than executes an asynchronous function (FMap) for each @@ -280,15 +280,15 @@ where reduce_result: FReduce, // The initial timeout applied to all initial_timeout: Duration, - ) -> Result + ) -> Result where - FMap: FnOnce(AuthorityName, &'a SafeClient) -> AsyncResult<'a, V, FastPayError> + Clone, + FMap: FnOnce(AuthorityName, &'a SafeClient) -> AsyncResult<'a, V, SuiError> + Clone, FReduce: Fn( S, AuthorityName, usize, - Result, - ) -> AsyncResult<'a, ReduceOutput, FastPayError>, + Result, + ) -> AsyncResult<'a, ReduceOutput, SuiError>, { // TODO: shuffle here according to stake let authority_clients = &self.authority_clients; @@ -343,7 +343,7 @@ where >, HashMap, ), - FastPayError, + SuiError, > { let initial_state = ((0usize, 0usize), Vec::new()); let threshold = self.committee.quorum_threshold(); @@ -372,7 +372,7 @@ where // since either there are too many faulty authorities or we are not connected to the network. total_stake.1 += weight; if total_stake.1 > validity { - return Err(FastPayError::TooManyIncorrectAuthorities); + return Err(SuiError::TooManyIncorrectAuthorities); } } @@ -462,9 +462,9 @@ where /// Clients should use `sync_all_owned_objects` instead. async fn get_all_owned_objects( &self, - address: FastPayAddress, + address: SuiAddress, timeout_after_quorum: Duration, - ) -> Result<(BTreeMap>, Vec), FastPayError> { + ) -> Result<(BTreeMap>, Vec), SuiError> { let initial_state = ( (0usize, 0usize), BTreeMap::>::new(), @@ -508,7 +508,7 @@ where state.0 .1 += weight; if state.0 .1 > validity { - return Err(FastPayError::TooManyIncorrectAuthorities); + return Err(SuiError::TooManyIncorrectAuthorities); } } @@ -542,7 +542,7 @@ where Vec<(Object, Option)>, Vec<(ObjectRef, Option)>, ), - FastPayError, + SuiError, > { let mut active_objects = Vec::new(); let mut deleted_objects = Vec::new(); @@ -644,14 +644,14 @@ where /// deleted object references. pub async fn sync_all_owned_objects( &self, - address: FastPayAddress, + address: SuiAddress, timeout_after_quorum: Duration, ) -> Result< ( Vec<(Object, Option)>, Vec<(ObjectRef, Option)>, ), - FastPayError, + SuiError, > { // Contact a quorum of authorities, and return all objects they report we own. let (object_map, _authority_list) = self @@ -674,7 +674,7 @@ where &self, order: Order, timeout_after_quorum: Duration, - ) -> Result { + ) -> Result { // Find out which objects are required by this order and // ensure they are synced on authorities. let required_ids: Vec = order @@ -697,7 +697,7 @@ where // A certificate if we manage to make or find one certificate: Option, // The list of errors gathered at any point - errors: Vec, + errors: Vec, // Tally of stake for good vs bad responses. good_stake: usize, bad_stake: usize, @@ -759,18 +759,18 @@ where state.bad_stake += weight; // This is the bad stake counter if state.bad_stake > validity { // Too many errors - return Err(FastPayError::QuorumNotReached { + return Err(SuiError::QuorumNotReached { errors: state.errors, }); } } // In case we don't get an error but also don't get a valid value _ => { - state.errors.push(FastPayError::ErrorWhileProcessingOrder); + state.errors.push(SuiError::ErrorWhileProcessingOrder); state.bad_stake += weight; // This is the bad stake counter if state.bad_stake > validity { // Too many errors - return Err(FastPayError::QuorumNotReached { + return Err(SuiError::QuorumNotReached { errors: state.errors, }); } @@ -791,9 +791,7 @@ where .await?; // If we have some certificate return it, or return an error. - state - .certificate - .ok_or(FastPayError::ErrorWhileProcessingOrder) + state.certificate.ok_or(SuiError::ErrorWhileProcessingOrder) } /// Process a certificate assuming that 2f+1 authorites already are up to date. @@ -806,7 +804,7 @@ where &self, certificate: CertifiedOrder, timeout_after_quorum: Duration, - ) -> Result { + ) -> Result { struct ProcessCertificateState { effects_map: HashMap<[u8; 32], (usize, OrderEffects)>, bad_stake: usize, @@ -884,7 +882,7 @@ where // If instead we have more than f bad responses, then we fail. state.bad_stake += weight; if state.bad_stake > validity { - return Err(FastPayError::ErrorWhileRequestingCertificate); + return Err(SuiError::ErrorWhileRequestingCertificate); } Ok(ReduceOutput::Continue(state)) @@ -904,16 +902,16 @@ where } // If none has, fail. - Err(FastPayError::ErrorWhileRequestingCertificate) + Err(SuiError::ErrorWhileRequestingCertificate) } #[cfg(test)] async fn request_certificate( &self, - _sender: FastPayAddress, + _sender: SuiAddress, object_id: ObjectID, _sequence_number: SequenceNumber, - ) -> Result { + ) -> Result { let (object_map, transaction_map) = self .get_object_by_id(object_id, Duration::from_secs(10)) .await?; @@ -1044,7 +1042,7 @@ where pub fn fetch_objects_from_authorities( &self, object_refs: BTreeSet, - ) -> Receiver> { + ) -> Receiver> { let (sender, receiver) = tokio::sync::mpsc::channel(OBJECT_DOWNLOAD_CHANNEL_BOUND); for object_ref in object_refs { let sender = sender.clone(); @@ -1067,7 +1065,7 @@ where authority_clients: BTreeMap>, object_ref: ObjectRef, timeout: Duration, - sender: tokio::sync::mpsc::Sender>, + sender: tokio::sync::mpsc::Sender>, ) { let object_id = object_ref.0; // Prepare the request @@ -1084,7 +1082,7 @@ where })) .await; - let mut ret_val: Result = Err(FastPayError::ObjectFetchFailed { + let mut ret_val: Result = Err(SuiError::ObjectFetchFailed { object_id, err: "No authority returned the correct object".to_string(), }); diff --git a/fastpay_core/src/authority_client.rs b/fastpay_core/src/authority_client.rs index 9dbaca56f6abb..0f9fa56ddc170 100644 --- a/fastpay_core/src/authority_client.rs +++ b/fastpay_core/src/authority_client.rs @@ -3,36 +3,36 @@ use async_trait::async_trait; use fastx_network::network::NetworkClient; -use fastx_types::{error::FastPayError, messages::*, serialize::*}; +use fastx_types::{error::SuiError, messages::*, serialize::*}; #[async_trait] pub trait AuthorityAPI { - /// Initiate a new order to a FastPay or Primary account. - async fn handle_order(&self, order: Order) -> Result; + /// Initiate a new order to a Sui or Primary account. + async fn handle_order(&self, order: Order) -> Result; - /// Confirm an order to a FastPay or Primary account. + /// Confirm an order to a Sui or Primary account. async fn handle_confirmation_order( &self, order: ConfirmationOrder, - ) -> Result; + ) -> Result; /// Handle Account information requests for this account. async fn handle_account_info_request( &self, request: AccountInfoRequest, - ) -> Result; + ) -> Result; /// Handle Object information requests for this account. async fn handle_object_info_request( &self, request: ObjectInfoRequest, - ) -> Result; + ) -> Result; /// Handle Object information requests for this account. async fn handle_order_info_request( &self, request: OrderInfoRequest, - ) -> Result; + ) -> Result; } #[derive(Clone)] @@ -46,17 +46,17 @@ impl AuthorityClient { #[async_trait] impl AuthorityAPI for AuthorityClient { - /// Initiate a new transfer to a FastPay or Primary account. - async fn handle_order(&self, order: Order) -> Result { + /// Initiate a new transfer to a Sui or Primary account. + async fn handle_order(&self, order: Order) -> Result { let response = self.0.send_recv_bytes(serialize_order(&order)).await?; deserialize_order_info(response) } - /// Confirm a transfer to a FastPay or Primary account. + /// Confirm a transfer to a Sui or Primary account. async fn handle_confirmation_order( &self, order: ConfirmationOrder, - ) -> Result { + ) -> Result { let response = self .0 .send_recv_bytes(serialize_cert(&order.certificate)) @@ -67,7 +67,7 @@ impl AuthorityAPI for AuthorityClient { async fn handle_account_info_request( &self, request: AccountInfoRequest, - ) -> Result { + ) -> Result { let response = self .0 .send_recv_bytes(serialize_account_info_request(&request)) @@ -78,7 +78,7 @@ impl AuthorityAPI for AuthorityClient { async fn handle_object_info_request( &self, request: ObjectInfoRequest, - ) -> Result { + ) -> Result { let response = self .0 .send_recv_bytes(serialize_object_info_request(&request)) @@ -90,7 +90,7 @@ impl AuthorityAPI for AuthorityClient { async fn handle_order_info_request( &self, request: OrderInfoRequest, - ) -> Result { + ) -> Result { let response = self .0 .send_recv_bytes(serialize_order_info_request(&request)) diff --git a/fastpay_core/src/authority_server.rs b/fastpay_core/src/authority_server.rs index ba3e49e288e43..1e730b2c8455d 100644 --- a/fastpay_core/src/authority_server.rs +++ b/fastpay_core/src/authority_server.rs @@ -50,7 +50,7 @@ impl MessageHandler for AuthorityServer { Box::pin(async move { let result = deserialize_message(buffer); let reply = match result { - Err(_) => Err(FastPayError::InvalidDecoding), + Err(_) => Err(SuiError::InvalidDecoding), Ok(result) => { match result { SerializedMessage::Order(message) => self @@ -89,7 +89,7 @@ impl MessageHandler for AuthorityServer { .handle_order_info_request(*message) .await .map(|info| Some(serialize_order_info(&info))), - _ => Err(FastPayError::UnexpectedMessage), + _ => Err(SuiError::UnexpectedMessage), } } }; diff --git a/fastpay_core/src/client.rs b/fastpay_core/src/client.rs index 8f9fc2f1e10c5..1ba1db1fc26f1 100644 --- a/fastpay_core/src/client.rs +++ b/fastpay_core/src/client.rs @@ -5,7 +5,7 @@ use crate::{authority_aggregator::AuthorityAggregator, authority_client::Authori use async_trait::async_trait; use fastx_framework::build_move_package_to_bytes; use fastx_types::{ - base_types::*, committee::Committee, error::FastPayError, fp_ensure, messages::*, + base_types::*, committee::Committee, error::SuiError, fp_ensure, messages::*, object::ObjectRead, }; use futures::future; @@ -39,8 +39,8 @@ use fastx_types::FASTX_FRAMEWORK_ADDRESS; pub type AsyncResult<'a, T, E> = future::BoxFuture<'a, Result>; pub struct ClientState { - /// Our FastPay address. - address: FastPayAddress, + /// Our Sui address. + address: SuiAddress, /// Our signature key. secret: StableSyncSigner, /// Authority entry point. @@ -57,11 +57,11 @@ pub trait Client { &mut self, object_id: ObjectID, gas_payment: ObjectID, - recipient: FastPayAddress, + recipient: SuiAddress, ) -> Result<(CertifiedOrder, OrderEffects), anyhow::Error>; /// Try to complete all pending orders once. Return if any fails - async fn try_complete_pending_orders(&mut self) -> Result<(), FastPayError>; + async fn try_complete_pending_orders(&mut self) -> Result<(), SuiError>; /// Synchronise client state with a random authorities, updates all object_ids and certificates, request only goes out to one authority. /// this method doesn't guarantee data correctness, client will have to handle potential byzantine authority @@ -94,7 +94,7 @@ pub trait Client { /// Get all object we own. fn get_owned_objects(&self) -> Vec; - async fn download_owned_objects_not_in_db(&self) -> Result, FastPayError>; + async fn download_owned_objects_not_in_db(&self) -> Result, SuiError>; } impl ClientState { @@ -104,11 +104,11 @@ impl ClientState { /// https://github.com/MystenLabs/fastnft/issues/332 pub fn new( path: PathBuf, - address: FastPayAddress, + address: SuiAddress, secret: StableSyncSigner, committee: Committee, authority_clients: BTreeMap, - ) -> Result { + ) -> Result { Ok(ClientState { address, secret, @@ -117,14 +117,11 @@ impl ClientState { }) } - pub fn address(&self) -> FastPayAddress { + pub fn address(&self) -> SuiAddress { self.address } - pub fn next_sequence_number( - &self, - object_id: &ObjectID, - ) -> Result { + pub fn next_sequence_number(&self, object_id: &ObjectID) -> Result { if self.store.object_sequence_numbers.contains_key(object_id)? { Ok(self .store @@ -132,16 +129,16 @@ impl ClientState { .get(object_id)? .expect("Unable to get sequence number")) } else { - Err(FastPayError::ObjectNotFound { + Err(SuiError::ObjectNotFound { object_id: *object_id, }) } } - pub fn object_ref(&self, object_id: ObjectID) -> Result { + pub fn object_ref(&self, object_id: ObjectID) -> Result { self.store .object_refs .get(&object_id)? - .ok_or(FastPayError::ObjectNotFound { object_id }) + .ok_or(SuiError::ObjectNotFound { object_id }) } pub fn object_refs(&self) -> BTreeMap { @@ -174,7 +171,7 @@ impl ClientState { &mut self, object_ref: &ObjectRef, parent_tx_digest: &TransactionDigest, - ) -> Result<(), FastPayError> { + ) -> Result<(), SuiError> { let (object_id, seq, _) = object_ref; let mut tx_digests = self.store.object_certs.get(object_id)?.unwrap_or_default(); tx_digests.push(*parent_tx_digest); @@ -201,7 +198,7 @@ impl ClientState { Ok(()) } - pub fn remove_object_info(&mut self, object_id: &ObjectID) -> Result<(), FastPayError> { + pub fn remove_object_info(&mut self, object_id: &ObjectID) -> Result<(), SuiError> { // Multi table atomic delete using batches let batch = self .store @@ -271,7 +268,7 @@ where let next_sequence_number = self.next_sequence_number(&object_id).unwrap_or_default(); fp_ensure!( object_kind.version() >= next_sequence_number, - FastPayError::UnexpectedSequenceNumber { + SuiError::UnexpectedSequenceNumber { object_id, expected_sequence: next_sequence_number, } @@ -300,7 +297,7 @@ where /// The caller has to explicitly find which objects are locked /// TODO: always return true for immutable objects https://github.com/MystenLabs/fastnft/issues/305 /// TODO: this function can fail. Need to handle it https://github.com/MystenLabs/fastnft/issues/383 - fn can_lock_or_unlock(&self, order: &Order) -> Result { + fn can_lock_or_unlock(&self, order: &Order) -> Result { let iter_matches = self.store.pending_orders.multi_get( &order .input_objects() @@ -324,9 +321,9 @@ where /// If the object is already locked, ensure it is unlocked by calling unlock_pending_order_objects /// Client runs sequentially right now so access to this is safe /// Double-locking can cause equivocation. TODO: https://github.com/MystenLabs/fastnft/issues/335 - pub fn lock_pending_order_objects(&self, order: &Order) -> Result<(), FastPayError> { + pub fn lock_pending_order_objects(&self, order: &Order) -> Result<(), SuiError> { if !self.can_lock_or_unlock(order)? { - return Err(FastPayError::ConcurrentTransactionError); + return Err(SuiError::ConcurrentTransactionError); } self.store .pending_orders @@ -340,9 +337,9 @@ where } /// Unlocks the objects for the given order /// Unlocking an already unlocked object, is a no-op and does not Err - fn unlock_pending_order_objects(&self, order: &Order) -> Result<(), FastPayError> { + fn unlock_pending_order_objects(&self, order: &Order) -> Result<(), SuiError> { if !self.can_lock_or_unlock(order)? { - return Err(FastPayError::ConcurrentTransactionError); + return Err(SuiError::ConcurrentTransactionError); } self.store .pending_orders @@ -354,7 +351,7 @@ where &mut self, cert: CertifiedOrder, effects: OrderEffects, - ) -> Result<(CertifiedOrder, OrderEffects), FastPayError> { + ) -> Result<(CertifiedOrder, OrderEffects), SuiError> { // The cert should be included in the response let parent_tx_digest = cert.order.digest(); self.store.certificates.insert(&parent_tx_digest, &cert)?; @@ -408,7 +405,7 @@ where async fn download_objects_not_in_db( &self, object_refs: Vec, - ) -> Result, FastPayError> { + ) -> Result, SuiError> { // Check the DB // This could be expensive. Might want to use object_ref table // We want items that are NOT in the table @@ -451,19 +448,19 @@ where &mut self, object_id: ObjectID, gas_payment: ObjectID, - recipient: FastPayAddress, + recipient: SuiAddress, ) -> Result<(CertifiedOrder, OrderEffects), anyhow::Error> { let object_ref = self .store .object_refs .get(&object_id)? - .ok_or(FastPayError::ObjectNotFound { object_id })?; + .ok_or(SuiError::ObjectNotFound { object_id })?; let gas_payment = self.store .object_refs .get(&gas_payment)? - .ok_or(FastPayError::ObjectNotFound { + .ok_or(SuiError::ObjectNotFound { object_id: gas_payment, })?; @@ -487,7 +484,7 @@ where Ok((certificate, effects)) } - async fn try_complete_pending_orders(&mut self) -> Result<(), FastPayError> { + async fn try_complete_pending_orders(&mut self) -> Result<(), SuiError> { // Orders are idempotent so no need to prevent multiple executions let unique_pending_orders: HashSet<_> = self .store @@ -499,7 +496,7 @@ where // TODO: https://github.com/MystenLabs/fastnft/issues/330 for order in unique_pending_orders { self.execute_transaction(order.clone()).await.map_err(|e| { - FastPayError::ErrorWhileProcessingTransactionOrder { err: e.to_string() } + SuiError::ErrorWhileProcessingTransactionOrder { err: e.to_string() } })?; } Ok(()) @@ -588,7 +585,7 @@ where self.store.object_sequence_numbers.keys().collect() } - async fn download_owned_objects_not_in_db(&self) -> Result, FastPayError> { + async fn download_owned_objects_not_in_db(&self) -> Result, SuiError> { let object_refs: Vec = self.store.object_refs.iter().map(|q| q.1).collect(); self.download_objects_not_in_db(object_refs).await } diff --git a/fastpay_core/src/client/client_store.rs b/fastpay_core/src/client/client_store.rs index 4797b76fdca15..77a0203d6bd8a 100644 --- a/fastpay_core/src/client/client_store.rs +++ b/fastpay_core/src/client/client_store.rs @@ -66,7 +66,7 @@ impl ClientStore { &self, object_refs: BTreeMap, certificates: BTreeMap, - ) -> Result<(), FastPayError> { + ) -> Result<(), SuiError> { self.certificates .batch() .insert_batch(&self.certificates, certificates.iter())? diff --git a/fastpay_core/src/generate_format.rs b/fastpay_core/src/generate_format.rs index b5870c6e51312..085ff5da0b480 100644 --- a/fastpay_core/src/generate_format.rs +++ b/fastpay_core/src/generate_format.rs @@ -14,7 +14,7 @@ fn get_registry() -> Result { // 2. Trace the main entry point(s) + every enum separately. tracer.trace_type::(&samples)?; - tracer.trace_type::(&samples)?; + tracer.trace_type::(&samples)?; tracer.trace_type::(&samples)?; tracer.registry() } @@ -30,8 +30,8 @@ enum Action { #[derive(Debug, StructOpt)] #[structopt( - name = "FastPay format generator", - about = "Trace serde (de)serialization to generate format descriptions for FastPay types" + name = "Sui format generator", + about = "Trace serde (de)serialization to generate format descriptions for Sui types" )] struct Options { #[structopt(possible_values = &Action::variants(), default_value = "Print", case_insensitive = true)] diff --git a/fastpay_core/src/safe_client.rs b/fastpay_core/src/safe_client.rs index caffb4c3f18da..2f5d48de3dcd9 100644 --- a/fastpay_core/src/safe_client.rs +++ b/fastpay_core/src/safe_client.rs @@ -6,7 +6,7 @@ use async_trait::async_trait; use fastx_types::{base_types::*, committee::*, fp_ensure}; use fastx_types::{ - error::{FastPayError, FastPayResult}, + error::{SuiError, SuiResult}, messages::*, }; @@ -14,11 +14,11 @@ use fastx_types::{ pub struct SafeClient { authority_client: C, committee: Committee, - address: FastPayAddress, + address: SuiAddress, } impl SafeClient { - pub fn new(authority_client: C, committee: Committee, address: FastPayAddress) -> Self { + pub fn new(authority_client: C, committee: Committee, address: SuiAddress) -> Self { Self { authority_client, committee, @@ -31,21 +31,21 @@ impl SafeClient { &self, digest: TransactionDigest, response: &OrderInfoResponse, - ) -> FastPayResult { + ) -> SuiResult { if let Some(signed_order) = &response.signed_order { // Check the order signature signed_order.check(&self.committee)?; // Check it has the right signer fp_ensure!( signed_order.authority == self.address, - FastPayError::ByzantineAuthoritySuspicion { + SuiError::ByzantineAuthoritySuspicion { authority: self.address } ); // Check it's the right order fp_ensure!( signed_order.order.digest() == digest, - FastPayError::ByzantineAuthoritySuspicion { + SuiError::ByzantineAuthoritySuspicion { authority: self.address } ); @@ -57,7 +57,7 @@ impl SafeClient { // Check it's the right order fp_ensure!( certificate.order.digest() == digest, - FastPayError::ByzantineAuthoritySuspicion { + SuiError::ByzantineAuthoritySuspicion { authority: self.address } ); @@ -71,14 +71,14 @@ impl SafeClient { // Checks it concerns the right tx fp_ensure!( signed_effects.effects.transaction_digest == digest, - FastPayError::ByzantineAuthoritySuspicion { + SuiError::ByzantineAuthoritySuspicion { authority: self.address } ); // Check it has the right signer fp_ensure!( signed_effects.authority == self.address, - FastPayError::ByzantineAuthoritySuspicion { + SuiError::ByzantineAuthoritySuspicion { authority: self.address } ); @@ -91,7 +91,7 @@ impl SafeClient { &self, request: &ObjectInfoRequest, response: &ObjectInfoResponse, - ) -> FastPayResult { + ) -> SuiResult { // If we get a certificate make sure it is a valid certificate if let Some(certificate) = &response.parent_certificate { certificate.check(&self.committee)?; @@ -102,7 +102,7 @@ impl SafeClient { if let Some(object_ref) = &response.requested_object_reference { fp_ensure!( object_ref.1 == *requested_version, - FastPayError::ByzantineAuthoritySuspicion { + SuiError::ByzantineAuthoritySuspicion { authority: self.address } ); @@ -116,7 +116,7 @@ impl SafeClient { // Check it has the right signer fp_ensure!( signed_order.authority == self.address, - FastPayError::ByzantineAuthoritySuspicion { + SuiError::ByzantineAuthoritySuspicion { authority: self.address } ); @@ -132,19 +132,19 @@ impl AuthorityAPI for SafeClient where C: AuthorityAPI + Send + Sync + Clone + 'static, { - /// Initiate a new transfer to a FastPay or Primary account. - async fn handle_order(&self, order: Order) -> Result { + /// Initiate a new transfer to a Sui or Primary account. + async fn handle_order(&self, order: Order) -> Result { let digest = order.digest(); let order_info = self.authority_client.handle_order(order).await?; self.check_order_response(digest, &order_info)?; Ok(order_info) } - /// Confirm a transfer to a FastPay or Primary account. + /// Confirm a transfer to a Sui or Primary account. async fn handle_confirmation_order( &self, order: ConfirmationOrder, - ) -> Result { + ) -> Result { let digest = order.certificate.order.digest(); let order_info = self .authority_client @@ -157,7 +157,7 @@ where async fn handle_account_info_request( &self, request: AccountInfoRequest, - ) -> Result { + ) -> Result { self.authority_client .handle_account_info_request(request) .await @@ -166,7 +166,7 @@ where async fn handle_object_info_request( &self, request: ObjectInfoRequest, - ) -> Result { + ) -> Result { let response = self .authority_client .handle_object_info_request(request.clone()) @@ -179,7 +179,7 @@ where async fn handle_order_info_request( &self, request: OrderInfoRequest, - ) -> Result { + ) -> Result { let digest = request.transaction_digest; let order_info = self .authority_client diff --git a/fastpay_core/src/unit_tests/authority_tests.rs b/fastpay_core/src/unit_tests/authority_tests.rs index e37f3651664e7..ed9869c4c74ec 100644 --- a/fastpay_core/src/unit_tests/authority_tests.rs +++ b/fastpay_core/src/unit_tests/authority_tests.rs @@ -164,7 +164,7 @@ async fn test_handle_transfer_order_unknown_sender() { fn test_handle_transfer_order_bad_sequence_number() { let (sender, sender_key) = get_key_pair(); let object_id: ObjectID = random_object_id(); - let recipient = Address::FastPay(dbg_addr(2)); + let recipient = Address::Sui(dbg_addr(2)); let authority_state = init_state_with_object(sender, object_id); let transfer_order = init_transfer_order(sender, &sender_key, recipient, object_id); @@ -304,7 +304,7 @@ async fn test_handle_transfer_zero_balance() { async fn send_and_confirm_order( authority: &AuthorityState, order: Order, -) -> Result { +) -> Result { // Make the initial request let response = authority.handle_order(order.clone()).await?; let vote = response.signed_order.unwrap(); @@ -645,11 +645,11 @@ async fn test_handle_confirmation_order_unknown_sender() { let object = Object::with_id_owner_for_testing( ObjectID::random(), - FastPayAddress::random_for_testing_only(), + SuiAddress::random_for_testing_only(), ); let gas_object = Object::with_id_owner_for_testing( ObjectID::random(), - FastPayAddress::random_for_testing_only(), + SuiAddress::random_for_testing_only(), ); let certified_transfer_order = init_certified_transfer_order( @@ -1655,7 +1655,7 @@ async fn init_state() -> AuthorityState { } #[cfg(test)] -async fn init_state_with_ids>( +async fn init_state_with_ids>( objects: I, ) -> AuthorityState { let state = init_state().await; @@ -1681,15 +1681,15 @@ async fn init_state_with_objects>(objects: I) -> } #[cfg(test)] -async fn init_state_with_object_id(address: FastPayAddress, object: ObjectID) -> AuthorityState { +async fn init_state_with_object_id(address: SuiAddress, object: ObjectID) -> AuthorityState { init_state_with_ids(std::iter::once((address, object))).await } #[cfg(test)] fn init_transfer_order( - sender: FastPayAddress, + sender: SuiAddress, secret: &KeyPair, - recipient: FastPayAddress, + recipient: SuiAddress, object_ref: ObjectRef, gas_object_ref: ObjectRef, ) -> Order { @@ -1704,9 +1704,9 @@ fn init_transfer_order( #[cfg(test)] fn init_certified_transfer_order( - sender: FastPayAddress, + sender: SuiAddress, secret: &KeyPair, - recipient: FastPayAddress, + recipient: SuiAddress, object_ref: ObjectRef, gas_object_ref: ObjectRef, authority_state: &AuthorityState, @@ -1752,7 +1752,7 @@ async fn call_move( type_args: Vec, object_arg_ids: Vec, pure_args: Vec>, -) -> FastPayResult { +) -> SuiResult { let gas_object = authority.get_object(gas_object_id).await.unwrap(); let gas_object_ref = gas_object.unwrap().to_object_reference(); let mut object_args = vec![]; @@ -1792,7 +1792,7 @@ async fn call_framework_code( type_args: Vec, object_arg_ids: Vec, pure_args: Vec>, -) -> FastPayResult { +) -> SuiResult { let (genesis_package_objects, _) = genesis::clone_genesis_data(); let package_object_ref = get_genesis_package_by_module(&genesis_package_objects, module); @@ -1816,7 +1816,7 @@ async fn create_move_object( gas_object_id: &ObjectID, sender: &PublicKeyBytes, sender_key: &KeyPair, -) -> FastPayResult { +) -> SuiResult { call_framework_code( authority, gas_object_id, diff --git a/fastpay_core/src/unit_tests/client_tests.rs b/fastpay_core/src/unit_tests/client_tests.rs index 94f7b9f421475..5d2e800ebe9fd 100644 --- a/fastpay_core/src/unit_tests/client_tests.rs +++ b/fastpay_core/src/unit_tests/client_tests.rs @@ -18,7 +18,7 @@ use std::{ use tokio::runtime::Runtime; use typed_store::Map; -use fastx_types::error::FastPayError::ObjectNotFound; +use fastx_types::error::SuiError::ObjectNotFound; use move_core_types::account_address::AccountAddress; use std::env; use std::fs; @@ -43,7 +43,7 @@ struct LocalAuthorityClient(Arc>); #[async_trait] impl AuthorityAPI for LocalAuthorityClient { - async fn handle_order(&self, order: Order) -> Result { + async fn handle_order(&self, order: Order) -> Result { let state = self.0.clone(); let result = state.lock().await.handle_order(order).await; result @@ -52,7 +52,7 @@ impl AuthorityAPI for LocalAuthorityClient { async fn handle_confirmation_order( &self, order: ConfirmationOrder, - ) -> Result { + ) -> Result { let state = self.0.clone(); let result = state.lock().await.handle_confirmation_order(order).await; result @@ -61,7 +61,7 @@ impl AuthorityAPI for LocalAuthorityClient { async fn handle_account_info_request( &self, request: AccountInfoRequest, - ) -> Result { + ) -> Result { let state = self.0.clone(); let result = state @@ -75,7 +75,7 @@ impl AuthorityAPI for LocalAuthorityClient { async fn handle_object_info_request( &self, request: ObjectInfoRequest, - ) -> Result { + ) -> Result { let state = self.0.clone(); let x = state.lock().await.handle_object_info_request(request).await; x @@ -85,7 +85,7 @@ impl AuthorityAPI for LocalAuthorityClient { async fn handle_order_info_request( &self, request: OrderInfoRequest, - ) -> Result { + ) -> Result { let state = self.0.clone(); let result = state.lock().await.handle_order_info_request(request).await; @@ -134,9 +134,9 @@ async fn extract_cert( #[cfg(test)] fn order_create( - src: FastPayAddress, + src: SuiAddress, secret: &dyn signature::Signer, - dest: FastPayAddress, + dest: SuiAddress, value: u64, framework_obj_ref: ObjectRef, gas_object_ref: ObjectRef, @@ -163,9 +163,9 @@ fn order_create( #[cfg(test)] fn order_transfer( - src: FastPayAddress, + src: SuiAddress, secret: &dyn signature::Signer, - dest: FastPayAddress, + dest: SuiAddress, object_ref: ObjectRef, framework_obj_ref: ObjectRef, gas_object_ref: ObjectRef, @@ -188,7 +188,7 @@ fn order_transfer( #[cfg(test)] fn order_set( - src: FastPayAddress, + src: SuiAddress, secret: &dyn signature::Signer, object_ref: ObjectRef, value: u64, @@ -213,7 +213,7 @@ fn order_set( #[cfg(test)] fn order_delete( - src: FastPayAddress, + src: SuiAddress, secret: &dyn signature::Signer, object_ref: ObjectRef, framework_obj_ref: ObjectRef, @@ -469,7 +469,7 @@ fn test_initiating_valid_transfer() { .unwrap(); assert_eq!( sender.next_sequence_number(&object_id_1), - Err(FastPayError::ObjectNotFound { + Err(SuiError::ObjectNotFound { object_id: object_id_1 }) ); @@ -1393,7 +1393,7 @@ fn test_transfer_object_error() { assert!(result.is_err()); assert!(matches!( result.unwrap_err().downcast_ref(), - Some(FastPayError::ObjectNotFound { .. }) + Some(SuiError::ObjectNotFound { .. }) )); // Test 2: Object not known to authorities @@ -1445,7 +1445,7 @@ fn test_transfer_object_error() { // Fabricate a fake pending transfer let transfer = Transfer { sender: sender.address(), - recipient: FastPayAddress::random_for_testing_only(), + recipient: SuiAddress::random_for_testing_only(), object_ref: (object_id, Default::default(), ObjectDigest::new([0; 32])), gas_payment: (gas_object, Default::default(), ObjectDigest::new([0; 32])), }; @@ -1686,12 +1686,12 @@ async fn test_map_reducer() { 0usize, |_name, _client| Box::pin(async move { Ok(()) }), |_accumulated_state, _authority_name, _authority_weight, _result| { - Box::pin(async move { Err(FastPayError::TooManyIncorrectAuthorities) }) + Box::pin(async move { Err(SuiError::TooManyIncorrectAuthorities) }) }, Duration::from_millis(1000), ) .await; - assert!(Err(FastPayError::TooManyIncorrectAuthorities) == res); + assert!(Err(SuiError::TooManyIncorrectAuthorities) == res); // Test: mapper errors do not get propagated up, reducer works let res = client1 @@ -1700,14 +1700,13 @@ async fn test_map_reducer() { 0usize, |_name, _client| { Box::pin(async move { - let res: Result = - Err(FastPayError::TooManyIncorrectAuthorities); + let res: Result = Err(SuiError::TooManyIncorrectAuthorities); res }) }, |mut accumulated_state, _authority_name, _authority_weight, result| { Box::pin(async move { - assert!(Err(FastPayError::TooManyIncorrectAuthorities) == result); + assert!(Err(SuiError::TooManyIncorrectAuthorities) == result); accumulated_state += 1; Ok(ReduceOutput::Continue(accumulated_state)) }) @@ -1751,7 +1750,7 @@ async fn test_map_reducer() { }) }, |_accumulated_state, _authority_name, _authority_weight, _result| { - Box::pin(async move { Err(FastPayError::TooManyIncorrectAuthorities) }) + Box::pin(async move { Err(SuiError::TooManyIncorrectAuthorities) }) }, Duration::from_millis(10), ) @@ -2242,7 +2241,7 @@ async fn test_transfer_pending_orders() { .await; assert!(result.is_err()); // assert!(matches!(result.unwrap_err().downcast_ref(), - // Some(FastPayError::QuorumNotReached {errors, ..}) if matches!(errors.as_slice(), [FastPayError::ObjectNotFound{..}, ..]))); + // Some(SuiError::QuorumNotReached {errors, ..}) if matches!(errors.as_slice(), [SuiError::ObjectNotFound{..}, ..]))); // Pending order should be cleared assert!(sender_state.store().pending_orders.is_empty()); @@ -2264,7 +2263,7 @@ async fn test_transfer_pending_orders() { .await; assert!(result.is_err()); //assert!(matches!(result.unwrap_err().downcast_ref(), - // Some(FastPayError::QuorumNotReached {errors, ..}) if matches!(errors.as_slice(), [FastPayError::LockErrors{..}, ..]))); + // Some(SuiError::QuorumNotReached {errors, ..}) if matches!(errors.as_slice(), [SuiError::LockErrors{..}, ..]))); // Pending order should be cleared assert!(sender_state.store().pending_orders.is_empty()); @@ -2274,7 +2273,7 @@ async fn test_transfer_pending_orders() { // Fabricate a fake pending transfer let transfer = Transfer { sender: sender_state.address(), - recipient: FastPayAddress::random_for_testing_only(), + recipient: SuiAddress::random_for_testing_only(), object_ref: (object_id, Default::default(), ObjectDigest::new([0; 32])), gas_payment: (gas_object, Default::default(), ObjectDigest::new([0; 32])), }; @@ -2292,7 +2291,7 @@ async fn test_transfer_pending_orders() { assert!(result.is_err()); assert!(matches!( result.unwrap_err().downcast_ref(), - Some(FastPayError::ConcurrentTransactionError) + Some(SuiError::ConcurrentTransactionError) )); // clear the pending orders sender_state.store().pending_orders.clear().unwrap(); diff --git a/fastx_programmability/adapter/src/adapter.rs b/fastx_programmability/adapter/src/adapter.rs index b44bd2371816a..41397a58abd63 100644 --- a/fastx_programmability/adapter/src/adapter.rs +++ b/fastx_programmability/adapter/src/adapter.rs @@ -7,10 +7,10 @@ use crate::bytecode_rewriter::ModuleHandleRewriter; use fastx_framework::EventType; use fastx_types::{ base_types::{ - Authenticator, FastPayAddress, ObjectID, TransactionDigest, TxContext, - TX_CONTEXT_MODULE_NAME, TX_CONTEXT_STRUCT_NAME, + Authenticator, ObjectID, SuiAddress, TransactionDigest, TxContext, TX_CONTEXT_MODULE_NAME, + TX_CONTEXT_STRUCT_NAME, }, - error::{FastPayError, FastPayResult}, + error::{SuiError, SuiResult}, event::Event, gas, messages::ExecutionStatus, @@ -57,9 +57,9 @@ macro_rules! exec_failure { #[path = "unit_tests/adapter_tests.rs"] mod adapter_tests; -pub fn new_move_vm(natives: NativeFunctionTable) -> Result, FastPayError> { +pub fn new_move_vm(natives: NativeFunctionTable) -> Result, SuiError> { Ok(Arc::new( - MoveVM::new(natives).map_err(|_| FastPayError::ExecutionInvariantViolation)?, + MoveVM::new(natives).map_err(|_| SuiError::ExecutionInvariantViolation)?, )) } @@ -84,7 +84,7 @@ pub fn execute + ModuleResolver FastPayResult { +) -> SuiResult { let mut object_owner_map = HashMap::new(); for object in object_args.iter().filter(|obj| !obj.is_read_only()) { if let Authenticator::Object(owner_object_id) = object.owner { @@ -156,19 +156,18 @@ fn execute_internal< gas_budget: u64, ctx: &mut TxContext, for_publish: bool, -) -> FastPayResult { +) -> SuiResult { // TODO: Update Move gas constants to reflect the gas fee on fastx. let cost_table = &move_vm_types::gas_schedule::INITIAL_COST_SCHEDULE; - let mut gas_status = match get_gas_status(cost_table, Some(gas_budget)).map_err(|e| { - FastPayError::GasBudgetTooHigh { + let mut gas_status = + match get_gas_status(cost_table, Some(gas_budget)).map_err(|e| SuiError::GasBudgetTooHigh { error: e.to_string(), - } - }) { - Ok(ok) => ok, - Err(err) => { - exec_failure!(gas::MIN_MOVE_CALL_GAS, err); - } - }; + }) { + Ok(ok) => ok, + Err(err) => { + exec_failure!(gas::MIN_MOVE_CALL_GAS, err); + } + }; let session = vm.new_session(state_view); match session.execute_function_for_effects( module_id, @@ -230,7 +229,7 @@ fn execute_internal< } ExecutionResult::Fail { error, gas_used } => exec_failure!( gas_used, - FastPayError::AbortedExecution { + SuiError::AbortedExecution { error: error.to_string(), } ), @@ -243,11 +242,11 @@ pub fn publish + ModuleResolver>, - sender: FastPayAddress, + sender: SuiAddress, ctx: &mut TxContext, gas_budget: u64, mut gas_object: Object, -) -> FastPayResult { +) -> SuiResult { let result = module_bytes .iter() .map(|b| CompiledModule::deserialize(b)) @@ -257,7 +256,7 @@ pub fn publish + ModuleResolver { exec_failure!( gas::MIN_MOVE_PUBLISH_GAS, - FastPayError::ModuleDeserializationFailure { + SuiError::ModuleDeserializationFailure { error: err.to_string(), } ); @@ -268,7 +267,7 @@ pub fn publish + ModuleResolver Result { +) -> Result { // Run the Move bytecode verifier and linker. // It is important to do this before running the FastX verifier, since the fastX // verifier may assume well-formedness conditions enforced by the Move verifier hold @@ -401,7 +400,7 @@ pub fn verify_and_link< .collect(); session .publish_module_bundle(new_module_bytes, package_id, &mut gas_status) - .map_err(|e| FastPayError::ModulePublishFailure { + .map_err(|e| SuiError::ModulePublishFailure { error: e.to_string(), })?; @@ -422,20 +421,20 @@ pub fn verify_and_link< pub fn generate_package_id( modules: &mut [CompiledModule], ctx: &mut TxContext, -) -> Result { +) -> Result { let mut sub_map = BTreeMap::new(); let package_id = ctx.fresh_id(); for module in modules.iter() { let old_module_id = module.self_id(); let old_address = *old_module_id.address(); if old_address != AccountAddress::ZERO { - return Err(FastPayError::ModulePublishFailure { + return Err(SuiError::ModulePublishFailure { error: "Publishing modules with non-zero address is not allowed".to_string(), }); } let new_module_id = ModuleId::new(package_id, old_module_id.name().to_owned()); if sub_map.insert(old_module_id, new_module_id).is_some() { - return Err(FastPayError::ModulePublishFailure { + return Err(SuiError::ModulePublishFailure { error: "Publishing two modules with the same ID".to_string(), }); } @@ -468,7 +467,7 @@ fn process_successful_execution< events: Vec, ctx: &TxContext, mut object_owner_map: HashMap, -) -> (u64, u64, FastPayResult) { +) -> (u64, u64, SuiResult) { for (mut obj, new_contents) in mutable_refs { // update contents and increment sequence number obj.data @@ -486,7 +485,7 @@ fn process_successful_execution< .expect("Safe because event_type is derived from an EventType enum") { EventType::TransferToAddress => handle_transfer( - Authenticator::Address(FastPayAddress::try_from(recipient.borrow()).unwrap()), + Authenticator::Address(SuiAddress::try_from(recipient.borrow()).unwrap()), type_, event_bytes, false, /* should_freeze */ @@ -497,7 +496,7 @@ fn process_successful_execution< &mut object_owner_map, ), EventType::TransferToAddressAndFreeze => handle_transfer( - Authenticator::Address(FastPayAddress::try_from(recipient.borrow()).unwrap()), + Authenticator::Address(SuiAddress::try_from(recipient.borrow()).unwrap()), type_, event_bytes, true, /* should_freeze */ @@ -564,7 +563,7 @@ fn handle_transfer< gas_used: &mut u64, state_view: &mut S, object_owner_map: &mut HashMap, -) -> FastPayResult { +) -> SuiResult { match type_ { TypeTag::Struct(s_type) => { let mut move_obj = MoveObject::new(s_type, contents); @@ -601,7 +600,7 @@ fn handle_transfer< parent = *object_owner_map.get(&parent).unwrap(); } if parent == obj_id { - return Err(FastPayError::CircularObjectOwnership); + return Err(SuiError::CircularObjectOwnership); } object_owner_map.insert(obj_id, owner_object_id); } @@ -632,20 +631,20 @@ fn resolve_and_type_check( object_args: Vec, mut pure_args: Vec>, ctx: &TxContext, -) -> Result { +) -> Result { // resolve the function we are calling let (function_signature, module_id) = match package_object.data { Data::Package(modules) => { let bytes = modules .get(module.as_str()) - .ok_or(FastPayError::ModuleNotFound { + .ok_or(SuiError::ModuleNotFound { module_name: module.to_string(), })?; let m = CompiledModule::deserialize(bytes).expect( "Unwrap safe because FastX serializes/verifies modules before publishing them", ); ( - Function::new_from_name(&m, function).ok_or(FastPayError::FunctionNotFound { + Function::new_from_name(&m, function).ok_or(SuiError::FunctionNotFound { error: format!( "Could not resolve function '{}' in module {}", function, @@ -656,20 +655,20 @@ fn resolve_and_type_check( ) } Data::Move(_) => { - return Err(FastPayError::ModuleLoadFailure { + return Err(SuiError::ModuleLoadFailure { error: "Expected a module object, but found a Move object".to_string(), }) } }; // check validity conditions on the invoked function if !function_signature.return_.is_empty() { - return Err(FastPayError::InvalidFunctionSignature { + return Err(SuiError::InvalidFunctionSignature { error: "Invoked function must not return a value".to_string(), }); } // check arity of type and value arguments if function_signature.type_parameters.len() != type_args.len() { - return Err(FastPayError::InvalidFunctionSignature { + return Err(SuiError::InvalidFunctionSignature { error: format!( "Expected {:?} type arguments, but found {:?}", function_signature.type_parameters.len(), @@ -680,7 +679,7 @@ fn resolve_and_type_check( // total number of args is |objects| + |pure_args| + 1 for the the `TxContext` object let num_args = object_args.len() + pure_args.len() + 1; if function_signature.parameters.len() != num_args { - return Err(FastPayError::InvalidFunctionSignature { + return Err(SuiError::InvalidFunctionSignature { error: format!( "Expected {:?} arguments calling function '{}', but found {:?}", function_signature.parameters.len(), @@ -692,7 +691,7 @@ fn resolve_and_type_check( // check that the last arg is `&mut TxContext` let last_param = &function_signature.parameters[function_signature.parameters.len() - 1]; if !is_param_tx_context(last_param) { - return Err(FastPayError::InvalidFunctionSignature { + return Err(SuiError::InvalidFunctionSignature { error: format!( "Expected last parameter of function signature to be &mut {}::{}::{}, but found {}", FASTX_FRAMEWORK_ADDRESS, TX_CONTEXT_MODULE_NAME, TX_CONTEXT_STRUCT_NAME, last_param @@ -722,7 +721,7 @@ fn resolve_and_type_check( match ¶m_type { Type::MutableReference(inner_t) => { if m.is_read_only() { - return Err(FastPayError::TypeError { + return Err(SuiError::TypeError { error: format!( "Argument {} is expected to be mutable, immutable object found", idx @@ -741,7 +740,7 @@ fn resolve_and_type_check( } Type::Struct { .. } => { if m.is_read_only() { - return Err(FastPayError::TypeError { + return Err(SuiError::TypeError { error: format!( "Argument {} is expected to be mutable, immutable object found", idx @@ -754,7 +753,7 @@ fn resolve_and_type_check( debug_assert!(res.is_none()) } t => { - return Err(FastPayError::TypeError { + return Err(SuiError::TypeError { error: format!( "Found object argument {}, but function expects {}", m.type_, t @@ -764,7 +763,7 @@ fn resolve_and_type_check( } } Data::Package(_) => { - return Err(FastPayError::TypeError { + return Err(SuiError::TypeError { error: format!("Found module argument, but function expects {}", param_type), }) } @@ -779,7 +778,7 @@ fn resolve_and_type_check( &function_signature.parameters[args.len()..function_signature.parameters.len() - 1] { if !is_primitive(param_type) { - return Err(FastPayError::TypeError { + return Err(SuiError::TypeError { error: format!("Expected primitive type, but found {}", param_type), }); } @@ -816,10 +815,10 @@ fn is_param_tx_context(param: &Type) -> bool { false } -fn type_check_struct(arg_type: &StructTag, param_type: &Type) -> Result<(), FastPayError> { +fn type_check_struct(arg_type: &StructTag, param_type: &Type) -> Result<(), SuiError> { if let Some(param_struct_type) = param_type.clone().into_struct_tag() { if arg_type != ¶m_struct_type { - Err(FastPayError::TypeError { + Err(SuiError::TypeError { error: format!( "Expected argument of type {}, but found type {}", param_struct_type, arg_type @@ -829,7 +828,7 @@ fn type_check_struct(arg_type: &StructTag, param_type: &Type) -> Result<(), Fast Ok(()) } } else { - Err(FastPayError::TypeError { + Err(SuiError::TypeError { error: format!( "Expected argument of type {}, but found struct type {}", param_type, arg_type diff --git a/fastx_programmability/adapter/src/genesis.rs b/fastx_programmability/adapter/src/genesis.rs index 190709bd41f51..a528dd9a893af 100644 --- a/fastx_programmability/adapter/src/genesis.rs +++ b/fastx_programmability/adapter/src/genesis.rs @@ -3,7 +3,7 @@ use fastx_framework::{self}; use fastx_types::{ - base_types::{Authenticator, FastPayAddress, TransactionDigest}, + base_types::{Authenticator, SuiAddress, TransactionDigest}, object::Object, FASTX_FRAMEWORK_ADDRESS, MOVE_STDLIB_ADDRESS, }; @@ -29,7 +29,7 @@ fn create_genesis_module_objects() -> Genesis { let std_modules = fastx_framework::get_move_stdlib_modules(); let native_functions = fastx_framework::natives::all_natives(MOVE_STDLIB_ADDRESS, FASTX_FRAMEWORK_ADDRESS); - let owner = FastPayAddress::default(); + let owner = SuiAddress::default(); let objects = vec![ Object::new_package( fastx_modules, diff --git a/fastx_programmability/adapter/src/unit_tests/adapter_tests.rs b/fastx_programmability/adapter/src/unit_tests/adapter_tests.rs index fb5315b1890a6..088f78fcc61de 100644 --- a/fastx_programmability/adapter/src/unit_tests/adapter_tests.rs +++ b/fastx_programmability/adapter/src/unit_tests/adapter_tests.rs @@ -4,7 +4,7 @@ use crate::{adapter, genesis}; use fastx_types::{ base_types::{self, SequenceNumber}, - error::FastPayResult, + error::SuiResult, gas_coin::GAS, object::Data, storage::Storage, @@ -172,7 +172,7 @@ fn call( type_args: Vec, object_args: Vec, pure_args: Vec>, -) -> FastPayResult { +) -> SuiResult { let package = storage.find_package(module_name).unwrap(); let vm = adapter::new_move_vm(native_functions.clone()).expect("No errors"); @@ -202,10 +202,8 @@ fn test_object_basics() { let mut storage = InMemoryStorage::new(genesis_objects); // 0. Create a gas object for gas payment. - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); storage.write_object(gas_object.clone()); storage.flush(); @@ -363,7 +361,7 @@ fn test_object_basics() { /// Ensure that the object's version is consistent #[test] fn test_wrap_unwrap() { - let addr = base_types::FastPayAddress::default(); + let addr = base_types::SuiAddress::default(); let (genesis_objects, native_functions) = genesis::clone_genesis_data(); let mut storage = InMemoryStorage::new(genesis_objects); @@ -467,10 +465,8 @@ fn test_move_call_insufficient_gas() { let mut storage = InMemoryStorage::new(genesis_objects); // 0. Create a gas object for gas payment. - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); storage.write_object(gas_object.clone()); storage.flush(); @@ -507,7 +503,7 @@ fn test_publish_module_insufficient_gas() { let gas_object = Object::with_id_owner_gas_for_testing( ObjectID::random(), SequenceNumber::from(1), - base_types::FastPayAddress::default(), + base_types::SuiAddress::default(), 30, ); storage.write_object(gas_object.clone()); @@ -524,7 +520,7 @@ fn test_publish_module_insufficient_gas() { &mut storage, natives, module_bytes, - base_types::FastPayAddress::default(), + base_types::SuiAddress::default(), &mut tx_context, GAS_BUDGET, gas_object, @@ -547,10 +543,8 @@ fn test_transfer_and_freeze() { let mut storage = InMemoryStorage::new(genesis_objects); // 0. Create a gas object for gas payment. - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); storage.write_object(gas_object.clone()); storage.flush(); @@ -652,10 +646,8 @@ fn test_move_call_args_type_mismatch() { let mut storage = InMemoryStorage::new(genesis_objects); // 0. Create a gas object for gas payment. - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); storage.write_object(gas_object.clone()); storage.flush(); @@ -711,10 +703,8 @@ fn test_move_call_incorrect_function() { let mut storage = InMemoryStorage::new(genesis_objects); // 0. Create a gas object for gas payment. - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); storage.write_object(gas_object.clone()); storage.flush(); @@ -779,10 +769,8 @@ fn test_publish_module_linker_error() { let mut storage = InMemoryStorage::new(genesis_objects); // 0. Create a gas object for gas payment. - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); storage.write_object(gas_object.clone()); storage.flush(); @@ -819,7 +807,7 @@ fn test_publish_module_linker_error() { &mut storage, natives, module_bytes, - base_types::FastPayAddress::default(), + base_types::SuiAddress::default(), &mut tx_context, GAS_BUDGET, gas_object, @@ -840,10 +828,8 @@ fn test_publish_module_non_zero_address() { let mut storage = InMemoryStorage::new(genesis_objects); // 0. Create a gas object for gas payment. - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); storage.write_object(gas_object.clone()); storage.flush(); @@ -862,7 +848,7 @@ fn test_publish_module_non_zero_address() { &mut storage, natives, module_bytes, - base_types::FastPayAddress::default(), + base_types::SuiAddress::default(), &mut tx_context, GAS_BUDGET, gas_object, @@ -876,7 +862,7 @@ fn test_publish_module_non_zero_address() { #[test] fn test_coin_transfer() { - let addr = base_types::FastPayAddress::default(); + let addr = base_types::SuiAddress::default(); let (genesis_objects, native_functions) = genesis::clone_genesis_data(); @@ -946,7 +932,7 @@ fn publish_from_src( storage, natives.clone(), all_module_bytes, - base_types::FastPayAddress::default(), + base_types::SuiAddress::default(), &mut tx_context, gas_budget, gas_object, @@ -960,10 +946,8 @@ fn test_simple_call() { let mut storage = InMemoryStorage::new(genesis_objects); // crate gas object for payment - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); // publish modules at a given path publish_from_src( @@ -1021,10 +1005,8 @@ fn test_publish_init() { let mut storage = InMemoryStorage::new(genesis_objects); // crate gas object for payment - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); // publish modules at a given path publish_from_src( @@ -1060,10 +1042,8 @@ fn test_publish_init_public() { let mut storage = InMemoryStorage::new(genesis_objects); // crate gas object for payment - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); // publish modules at a given path publish_from_src( @@ -1086,10 +1066,8 @@ fn test_publish_init_ret() { let mut storage = InMemoryStorage::new(genesis_objects); // crate gas object for payment - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); // publish modules at a given path publish_from_src( @@ -1112,10 +1090,8 @@ fn test_publish_init_param() { let mut storage = InMemoryStorage::new(genesis_objects); // crate gas object for payment - let gas_object = Object::with_id_owner_for_testing( - ObjectID::random(), - base_types::FastPayAddress::default(), - ); + let gas_object = + Object::with_id_owner_for_testing(ObjectID::random(), base_types::SuiAddress::default()); // publish modules at a given path publish_from_src( diff --git a/fastx_programmability/framework/src/lib.rs b/fastx_programmability/framework/src/lib.rs index f57a938e285a4..fe29e3b509566 100644 --- a/fastx_programmability/framework/src/lib.rs +++ b/fastx_programmability/framework/src/lib.rs @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs // SPDX-License-Identifier: Apache-2.0 -use fastx_types::error::{FastPayError, FastPayResult}; +use fastx_types::error::{SuiError, SuiResult}; use fastx_verifier::verifier as fastx_bytecode_verifier; use move_binary_format::CompiledModule; use move_core_types::{account_address::AccountAddress, ident_str}; @@ -58,7 +58,7 @@ pub fn get_move_stdlib_modules() -> Vec { /// This is useful for when publishing /// If we are building the FastX framework, `is_framework` will be true; /// Otherwise `is_framework` should be false (e.g. calling from client). -pub fn build_move_package_to_bytes(path: &Path) -> Result>, FastPayError> { +pub fn build_move_package_to_bytes(path: &Path) -> Result>, SuiError> { build_move_package( path, BuildConfig { @@ -84,9 +84,9 @@ pub fn build_move_package( path: &Path, build_config: BuildConfig, is_framework: bool, -) -> FastPayResult> { +) -> SuiResult> { match build_config.compile_package(path, &mut Vec::new()) { - Err(error) => Err(FastPayError::ModuleBuildFailure { + Err(error) => Err(SuiError::ModuleBuildFailure { error: error.to_string(), }), Ok(package) => { @@ -97,7 +97,7 @@ pub fn build_move_package( .iter() .find(|m| m.self_id().address() != &AccountAddress::ZERO) { - return Err(FastPayError::ModulePublishFailure { + return Err(SuiError::ModulePublishFailure { error: format!( "Modules must all have 0x0 as their addresses. Violated by module {:?}", m.self_id() @@ -123,7 +123,7 @@ pub fn build_move_package( && m.self_id().address() == &AccountAddress::ZERO }) { - return Err(FastPayError::ModulePublishFailure { error: format!("Denpendent modules must have been published on-chain with non-0 addresses, unlike module {:?}", m.self_id()) }); + return Err(SuiError::ModulePublishFailure { error: format!("Denpendent modules must have been published on-chain with non-0 addresses, unlike module {:?}", m.self_id()) }); } Ok(package .transitive_compiled_modules() diff --git a/fastx_programmability/verifier/src/global_storage_access_verifier.rs b/fastx_programmability/verifier/src/global_storage_access_verifier.rs index b4f09008b0e09..29fec519cb224 100644 --- a/fastx_programmability/verifier/src/global_storage_access_verifier.rs +++ b/fastx_programmability/verifier/src/global_storage_access_verifier.rs @@ -2,19 +2,19 @@ // SPDX-License-Identifier: Apache-2.0 use crate::verification_failure; -use fastx_types::error::FastPayResult; +use fastx_types::error::SuiResult; use move_binary_format::{ binary_views::BinaryIndexedView, file_format::{Bytecode, CompiledModule}, }; -pub fn verify_module(module: &CompiledModule) -> FastPayResult { +pub fn verify_module(module: &CompiledModule) -> SuiResult { verify_global_storage_access(module) } /// Global storage in fastx is handled by fastx instead of within Move. /// Hence we want to forbid any global storage access in Move. -fn verify_global_storage_access(module: &CompiledModule) -> FastPayResult { +fn verify_global_storage_access(module: &CompiledModule) -> SuiResult { let view = BinaryIndexedView::Module(module); for func_def in &module.function_defs { if func_def.code.is_none() { diff --git a/fastx_programmability/verifier/src/id_immutable_verifier.rs b/fastx_programmability/verifier/src/id_immutable_verifier.rs index 6f3d02b68c820..a54939b8caa6d 100644 --- a/fastx_programmability/verifier/src/id_immutable_verifier.rs +++ b/fastx_programmability/verifier/src/id_immutable_verifier.rs @@ -8,17 +8,17 @@ //! an ID field. use crate::verification_failure; -use fastx_types::error::FastPayResult; +use fastx_types::error::SuiResult; use move_binary_format::{ binary_views::BinaryIndexedView, file_format::{Bytecode, CompiledModule, FieldHandleIndex}, }; -pub fn verify_module(module: &CompiledModule) -> FastPayResult { +pub fn verify_module(module: &CompiledModule) -> SuiResult { verify_id_immutable(module) } -fn verify_id_immutable(module: &CompiledModule) -> FastPayResult { +fn verify_id_immutable(module: &CompiledModule) -> SuiResult { let view = BinaryIndexedView::Module(module); for func_def in &module.function_defs { if func_def.code.is_none() { diff --git a/fastx_programmability/verifier/src/id_leak_verifier.rs b/fastx_programmability/verifier/src/id_leak_verifier.rs index 3d92fff4fcb5c..97e0eea8fa0fb 100644 --- a/fastx_programmability/verifier/src/id_leak_verifier.rs +++ b/fastx_programmability/verifier/src/id_leak_verifier.rs @@ -15,7 +15,7 @@ use crate::verification_failure; use fastx_types::{ - error::{FastPayError, FastPayResult}, + error::{SuiError, SuiResult}, FASTX_FRAMEWORK_ADDRESS, }; use move_binary_format::{ @@ -47,11 +47,11 @@ impl AbstractValue { } } -pub fn verify_module(module: &CompiledModule) -> FastPayResult { +pub fn verify_module(module: &CompiledModule) -> SuiResult { verify_id_leak(module) } -fn verify_id_leak(module: &CompiledModule) -> FastPayResult { +fn verify_id_leak(module: &CompiledModule) -> SuiResult { let binary_view = BinaryIndexedView::Module(module); for (index, func_def) in module.function_defs.iter().enumerate() { let code = match func_def.code.as_ref() { @@ -68,8 +68,8 @@ fn verify_id_leak(module: &CompiledModule) -> FastPayResult { for (_block_id, BlockInvariant { post, .. }) in inv_map { match post { BlockPostcondition::Error(err) => match err { - FastPayError::ModuleVerificationFailure { error } => { - return Err(FastPayError::ModuleVerificationFailure { + SuiError::ModuleVerificationFailure { error } => { + return Err(SuiError::ModuleVerificationFailure { error: format!( "ID leak detected in function {}: {}", binary_view.identifier_at(handle.name), @@ -147,7 +147,7 @@ impl<'a> IDLeakAnalysis<'a> { impl<'a> TransferFunctions for IDLeakAnalysis<'a> { type State = AbstractState; - type AnalysisError = FastPayError; + type AnalysisError = SuiError; fn execute( &mut self, @@ -177,7 +177,7 @@ fn is_call_safe_to_leak(verifier: &IDLeakAnalysis, function_handle: &FunctionHan == "delete" } -fn call(verifier: &mut IDLeakAnalysis, function_handle: &FunctionHandle) -> FastPayResult { +fn call(verifier: &mut IDLeakAnalysis, function_handle: &FunctionHandle) -> SuiResult { let guaranteed_safe = is_call_safe_to_leak(verifier, function_handle); let parameters = verifier .binary_view @@ -240,7 +240,7 @@ fn execute_inner( state: &mut AbstractState, bytecode: &Bytecode, _: CodeOffset, -) -> FastPayResult { +) -> SuiResult { // TODO: Better dianostics with location match bytecode { Bytecode::Pop => { diff --git a/fastx_programmability/verifier/src/lib.rs b/fastx_programmability/verifier/src/lib.rs index cd63f48cc435c..e4ddc9b46b4b8 100644 --- a/fastx_programmability/verifier/src/lib.rs +++ b/fastx_programmability/verifier/src/lib.rs @@ -8,8 +8,8 @@ pub mod id_immutable_verifier; pub mod id_leak_verifier; pub mod struct_with_key_verifier; -use fastx_types::error::FastPayError; +use fastx_types::error::SuiError; -fn verification_failure(error: String) -> FastPayError { - FastPayError::ModuleVerificationFailure { error } +fn verification_failure(error: String) -> SuiError { + SuiError::ModuleVerificationFailure { error } } diff --git a/fastx_programmability/verifier/src/struct_with_key_verifier.rs b/fastx_programmability/verifier/src/struct_with_key_verifier.rs index e73148a2e4864..62c1ef9e5aa02 100644 --- a/fastx_programmability/verifier/src/struct_with_key_verifier.rs +++ b/fastx_programmability/verifier/src/struct_with_key_verifier.rs @@ -2,18 +2,18 @@ // SPDX-License-Identifier: Apache-2.0 use crate::verification_failure; -use fastx_types::{error::FastPayResult, fp_ensure, FASTX_FRAMEWORK_ADDRESS}; +use fastx_types::{error::SuiResult, fp_ensure, FASTX_FRAMEWORK_ADDRESS}; use move_binary_format::{ access::ModuleAccess, binary_views::BinaryIndexedView, file_format::{CompiledModule, SignatureToken}, }; -pub fn verify_module(module: &CompiledModule) -> FastPayResult { +pub fn verify_module(module: &CompiledModule) -> SuiResult { verify_key_structs(module) } -fn verify_key_structs(module: &CompiledModule) -> FastPayResult { +fn verify_key_structs(module: &CompiledModule) -> SuiResult { let view = BinaryIndexedView::Module(module); let struct_defs = &module.struct_defs; for def in struct_defs { diff --git a/fastx_programmability/verifier/src/verifier.rs b/fastx_programmability/verifier/src/verifier.rs index d051acc3f75e1..a456b19a4e718 100644 --- a/fastx_programmability/verifier/src/verifier.rs +++ b/fastx_programmability/verifier/src/verifier.rs @@ -3,7 +3,7 @@ //! This module contains the public APIs supported by the bytecode verifier. -use fastx_types::error::FastPayResult; +use fastx_types::error::SuiResult; use move_binary_format::file_format::CompiledModule; use crate::{ @@ -12,7 +12,7 @@ use crate::{ }; /// Helper for a "canonical" verification of a module. -pub fn verify_module(module: &CompiledModule) -> FastPayResult { +pub fn verify_module(module: &CompiledModule) -> SuiResult { struct_with_key_verifier::verify_module(module)?; global_storage_access_verifier::verify_module(module)?; id_immutable_verifier::verify_module(module)?; diff --git a/fastx_types/src/base_types.rs b/fastx_types/src/base_types.rs index 6674aba8a6480..a9721aefb390b 100644 --- a/fastx_types/src/base_types.rs +++ b/fastx_types/src/base_types.rs @@ -1,6 +1,6 @@ // Copyright (c) Facebook, Inc. and its affiliates. // SPDX-License-Identifier: Apache-2.0 -use crate::error::FastPayError; +use crate::error::SuiError; use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; @@ -47,10 +47,10 @@ impl PublicKeyBytes { self.0.to_vec() } - pub fn to_public_key(&self) -> Result { + pub fn to_public_key(&self) -> Result { // TODO(https://github.com/MystenLabs/fastnft/issues/101): Do better key validation // to ensure the bytes represent a point on the curve. - PublicKey::from_bytes(self.as_ref()).map_err(|_| FastPayError::InvalidAuthenticator) + PublicKey::from_bytes(self.as_ref()).map_err(|_| SuiError::InvalidAuthenticator) } // for testing @@ -69,17 +69,17 @@ impl AsRef<[u8]> for PublicKeyBytes { // TODO(https://github.com/MystenLabs/fastnft/issues/101): more robust key validation impl TryFrom<&[u8]> for PublicKeyBytes { - type Error = FastPayError; + type Error = SuiError; - fn try_from(bytes: &[u8]) -> Result { + fn try_from(bytes: &[u8]) -> Result { let arr: [u8; dalek::PUBLIC_KEY_LENGTH] = bytes .try_into() - .map_err(|_| FastPayError::InvalidAuthenticator)?; + .map_err(|_| SuiError::InvalidAuthenticator)?; Ok(Self(arr)) } } -pub type FastPayAddress = PublicKeyBytes; +pub type SuiAddress = PublicKeyBytes; pub type AuthorityName = PublicKeyBytes; // Define digests and object IDs. For now, ID's are the same as Move account addresses @@ -98,12 +98,12 @@ pub type ObjectRef = (ObjectID, SequenceNumber, ObjectDigest); // Refer details to https://github.com/MystenLabs/fastnft/pull/292. #[derive(Eq, PartialEq, Debug, Clone, Copy, Deserialize, PartialOrd, Ord, Serialize, Hash)] pub enum Authenticator { - Address(FastPayAddress), + Address(SuiAddress), Object(ObjectID), } impl Authenticator { - pub fn is_address(&self, address: &FastPayAddress) -> bool { + pub fn is_address(&self, address: &SuiAddress) -> bool { match self { Self::Address(addr) => addr == address, Self::Object(_) => false, @@ -142,7 +142,7 @@ pub struct TxContext { } impl TxContext { - pub fn new(sender: &FastPayAddress, digest: TransactionDigest) -> Self { + pub fn new(sender: &SuiAddress, digest: TransactionDigest) -> Self { Self { sender: sender.to_vec(), digest: digest.0.to_vec(), @@ -171,9 +171,9 @@ impl TxContext { /// when mutable context is passed over some boundary via /// serialize/deserialize and this is the reason why this method /// consumes the other contex.. - pub fn update_state(&mut self, other: TxContext) -> Result<(), FastPayError> { + pub fn update_state(&mut self, other: TxContext) -> Result<(), SuiError> { if self.sender != other.sender || self.digest != other.digest { - return Err(FastPayError::InvalidTxUpdate); + return Err(SuiError::InvalidTxUpdate); } self.ids_created = other.ids_created; Ok(()) @@ -182,7 +182,7 @@ impl TxContext { // for testing pub fn random_for_testing_only() -> Self { Self::new( - &FastPayAddress::random_for_testing_only(), + &SuiAddress::random_for_testing_only(), TransactionDigest::random(), ) } @@ -235,13 +235,13 @@ impl ObjectDigest { } // TODO: get_key_pair() and get_key_pair_from_bytes() should return KeyPair only. -pub fn get_key_pair() -> (FastPayAddress, KeyPair) { +pub fn get_key_pair() -> (SuiAddress, KeyPair) { let mut csprng = OsRng; let keypair = dalek::Keypair::generate(&mut csprng); (PublicKeyBytes(keypair.public.to_bytes()), KeyPair(keypair)) } -pub fn get_key_pair_from_bytes(bytes: &[u8]) -> (FastPayAddress, KeyPair) { +pub fn get_key_pair_from_bytes(bytes: &[u8]) -> (SuiAddress, KeyPair) { let keypair = dalek::Keypair::from_bytes(bytes).unwrap(); (PublicKeyBytes(keypair.public.to_bytes()), KeyPair(keypair)) } @@ -328,7 +328,7 @@ pub fn decode_address(s: &str) -> Result { Ok(PublicKeyBytes(address)) } -pub fn dbg_addr(name: u8) -> FastPayAddress { +pub fn dbg_addr(name: u8) -> SuiAddress { let addr = [name; dalek::PUBLIC_KEY_LENGTH]; PublicKeyBytes(addr) } @@ -433,10 +433,10 @@ impl SequenceNumber { Self(self.0 + 1) } - pub fn decrement(self) -> Result { + pub fn decrement(self) -> Result { let val = self.0.checked_sub(1); match val { - None => Err(FastPayError::SequenceUnderflow), + None => Err(SuiError::SequenceUnderflow), Some(val) => Ok(Self(val)), } } @@ -494,7 +494,7 @@ impl Signature { Signature(signature) } - pub fn check(&self, value: &T, author: FastPayAddress) -> Result<(), FastPayError> + pub fn check(&self, value: &T, author: SuiAddress) -> Result<(), SuiError> where T: Signable>, { @@ -503,7 +503,7 @@ impl Signature { let public_key = author.to_public_key()?; public_key .verify(&message, &self.0) - .map_err(|error| FastPayError::InvalidSignature { + .map_err(|error| SuiError::InvalidSignature { error: format!("{}", error), }) } @@ -512,10 +512,10 @@ impl Signature { value: &'a T, votes: I, key_cache: &HashMap, - ) -> Result<(), FastPayError> + ) -> Result<(), SuiError> where T: Signable>, - I: IntoIterator, + I: IntoIterator, { let mut msg = Vec::new(); value.write(&mut msg); @@ -531,7 +531,7 @@ impl Signature { } } dalek::verify_batch(&messages[..], &signatures[..], &public_keys[..]).map_err(|error| { - FastPayError::InvalidSignature { + SuiError::InvalidSignature { error: format!("{}", error), } }) @@ -546,12 +546,12 @@ pub fn sha3_hash>(signable: &S) -> [u8; 32] { } impl TryFrom<&[u8]> for TransactionDigest { - type Error = FastPayError; + type Error = SuiError; - fn try_from(bytes: &[u8]) -> Result { + fn try_from(bytes: &[u8]) -> Result { let arr: [u8; TRANSACTION_DIGEST_LENGTH] = bytes .try_into() - .map_err(|_| FastPayError::InvalidTransactionDigest)?; + .map_err(|_| SuiError::InvalidTransactionDigest)?; Ok(Self(arr)) } } diff --git a/fastx_types/src/error.rs b/fastx_types/src/error.rs index e0f16427f43bc..e5152485e571b 100644 --- a/fastx_types/src/error.rs +++ b/fastx_types/src/error.rs @@ -27,13 +27,13 @@ macro_rules! fp_ensure { pub(crate) use fp_ensure; #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, Hash)] -/// Custom error type for FastPay. +/// Custom error type for Sui. #[allow(clippy::large_enum_variant)] -pub enum FastPayError { +pub enum SuiError { // Object misuse issues #[error("Error acquiring lock for object(s): {:?}", errors)] - LockErrors { errors: Vec }, + LockErrors { errors: Vec }, #[error("Attempt to transfer read-only object.")] CannotTransferReadOnlyObject, #[error("A move package is expected, instead a move object is passed: {object_id}")] @@ -200,7 +200,7 @@ pub enum FastPayError { "Failed to achieve quorum between authorities, cause by : {:#?}", errors.iter().map(| e | e.to_string()).collect::>() )] - QuorumNotReached { errors: Vec }, + QuorumNotReached { errors: Vec }, // Errors returned by authority and client read API's #[error("Failure serializing object in the requested format")] @@ -218,11 +218,11 @@ pub enum FastPayError { AccountNotFound, } -pub type FastPayResult = Result; +pub type SuiResult = Result; -impl std::convert::From for FastPayError { +impl std::convert::From for SuiError { fn from(error: PartialVMError) -> Self { - FastPayError::ModuleVerificationFailure { + SuiError::ModuleVerificationFailure { error: error.to_string(), } } diff --git a/fastx_types/src/gas.rs b/fastx_types/src/gas.rs index 04df1f8db9a7d..f67f73d66d8a8 100644 --- a/fastx_types/src/gas.rs +++ b/fastx_types/src/gas.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 use crate::{ - error::{FastPayError, FastPayResult}, + error::{SuiError, SuiResult}, gas_coin::GasCoin, messages::{Order, OrderKind}, object::Object, @@ -12,7 +12,7 @@ use std::convert::TryFrom; macro_rules! ok_or_gas_error { ($cond:expr, $e:expr) => { if !($cond) { - Err(FastPayError::InsufficientGas { error: $e }) + Err(SuiError::InsufficientGas { error: $e }) } else { Ok(()) } @@ -23,7 +23,7 @@ pub const MIN_MOVE_CALL_GAS: u64 = 10; pub const MIN_MOVE_PUBLISH_GAS: u64 = 10; pub const MIN_OBJ_TRANSFER_GAS: u64 = 8; -pub fn check_gas_requirement(order: &Order, gas_object: &Object) -> FastPayResult { +pub fn check_gas_requirement(order: &Order, gas_object: &Object) -> SuiResult { match &order.kind { OrderKind::Transfer(t) => { debug_assert_eq!(t.gas_payment.0, gas_object.id()); @@ -69,7 +69,7 @@ pub fn check_gas_requirement(order: &Order, gas_object: &Object) -> FastPayResul } /// Try subtract the gas balance of \p gas_object by \p amount. -pub fn try_deduct_gas(gas_object: &mut Object, amount: u64) -> FastPayResult { +pub fn try_deduct_gas(gas_object: &mut Object, amount: u64) -> SuiResult { // The object must be a gas coin as we have checked in order handle phase. let gas_coin = GasCoin::try_from(&*gas_object).unwrap(); let balance = gas_coin.value(); @@ -83,7 +83,7 @@ pub fn try_deduct_gas(gas_object: &mut Object, amount: u64) -> FastPayResult { Ok(()) } -pub fn check_gas_balance(gas_object: &Object, amount: u64) -> FastPayResult { +pub fn check_gas_balance(gas_object: &Object, amount: u64) -> SuiResult { let balance = get_gas_balance(gas_object)?; ok_or_gas_error!( balance >= amount, @@ -98,7 +98,7 @@ pub fn deduct_gas(gas_object: &mut Object, amount: u64) { try_deduct_gas(gas_object, amount).unwrap(); } -pub fn get_gas_balance(gas_object: &Object) -> FastPayResult { +pub fn get_gas_balance(gas_object: &Object) -> SuiResult { Ok(GasCoin::try_from(gas_object)?.value()) } diff --git a/fastx_types/src/gas_coin.rs b/fastx_types/src/gas_coin.rs index d6fccf6142afe..84e201af3236d 100644 --- a/fastx_types/src/gas_coin.rs +++ b/fastx_types/src/gas_coin.rs @@ -12,7 +12,7 @@ use std::convert::{TryFrom, TryInto}; use crate::{ base_types::{ObjectID, SequenceNumber}, coin::Coin, - error::{FastPayError, FastPayResult}, + error::{SuiError, SuiResult}, id::ID, object::{Data, MoveObject, Object}, FASTX_FRAMEWORK_ADDRESS, @@ -71,16 +71,16 @@ impl GasCoin { } } impl TryFrom<&MoveObject> for GasCoin { - type Error = FastPayError; + type Error = SuiError; - fn try_from(value: &MoveObject) -> FastPayResult { + fn try_from(value: &MoveObject) -> SuiResult { if value.type_ != GasCoin::type_() { - return Err(FastPayError::TypeError { + return Err(SuiError::TypeError { error: format!("Gas object type is not a gas coin: {}", value.type_), }); } let gas_coin: GasCoin = - bcs::from_bytes(value.contents()).map_err(|err| FastPayError::TypeError { + bcs::from_bytes(value.contents()).map_err(|err| SuiError::TypeError { error: format!("Unable to deserialize gas object: {:?}", err), })?; Ok(gas_coin) @@ -88,12 +88,12 @@ impl TryFrom<&MoveObject> for GasCoin { } impl TryFrom<&Object> for GasCoin { - type Error = FastPayError; + type Error = SuiError; - fn try_from(value: &Object) -> FastPayResult { + fn try_from(value: &Object) -> SuiResult { match &value.data { Data::Move(obj) => obj.try_into(), - Data::Package(_) => Err(FastPayError::TypeError { + Data::Package(_) => Err(SuiError::TypeError { error: format!("Gas object type is not a gas coin: {:?}", value), }), } diff --git a/fastx_types/src/messages.rs b/fastx_types/src/messages.rs index 754b5793fe32a..2ee0cb3b8397a 100644 --- a/fastx_types/src/messages.rs +++ b/fastx_types/src/messages.rs @@ -19,15 +19,15 @@ use std::{ #[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)] pub struct Transfer { - pub sender: FastPayAddress, - pub recipient: FastPayAddress, + pub sender: SuiAddress, + pub recipient: SuiAddress, pub object_ref: ObjectRef, pub gas_payment: ObjectRef, } #[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)] pub struct MoveCall { - pub sender: FastPayAddress, + pub sender: SuiAddress, // TODO: For package object, we only need object id, as it's always read-only. pub package: ObjectRef, pub module: Identifier, @@ -41,7 +41,7 @@ pub struct MoveCall { #[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)] pub struct MoveModulePublish { - pub sender: FastPayAddress, + pub sender: SuiAddress, pub gas_payment: ObjectRef, pub modules: Vec>, pub gas_budget: u64, @@ -107,11 +107,11 @@ pub struct ConfirmationOrder { #[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)] pub struct AccountInfoRequest { - pub account: FastPayAddress, + pub account: SuiAddress, } -impl From for AccountInfoRequest { - fn from(account: FastPayAddress) -> Self { +impl From for AccountInfoRequest { + fn from(account: SuiAddress) -> Self { AccountInfoRequest { account } } } @@ -147,7 +147,7 @@ impl From for ObjectInfoRequest { #[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)] pub struct AccountInfoResponse { pub object_ids: Vec, - pub owner: FastPayAddress, + pub owner: SuiAddress, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -210,14 +210,9 @@ pub struct OrderInfoResponse { #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] pub enum ExecutionStatus { // Gas used in the success case. - Success { - gas_used: u64, - }, + Success { gas_used: u64 }, // Gas used in the failed case, and the error. - Failure { - gas_used: u64, - error: Box, - }, + Failure { gas_used: u64, error: Box }, } impl ExecutionStatus { @@ -230,7 +225,7 @@ impl ExecutionStatus { } } - pub fn unwrap_err(self) -> (u64, FastPayError) { + pub fn unwrap_err(self) -> (u64, SuiError) { match self { ExecutionStatus::Success { .. } => { panic!("Unable to unwrap() on {:?}", self); @@ -330,10 +325,10 @@ impl InputObjectKind { } } - pub fn object_not_found_error(&self) -> FastPayError { + pub fn object_not_found_error(&self) -> SuiError { match *self { - Self::MovePackage(package_id) => FastPayError::DependentPackageNotFound { package_id }, - Self::MoveObject((object_id, _, _)) => FastPayError::ObjectNotFound { object_id }, + Self::MovePackage(package_id) => SuiError::DependentPackageNotFound { package_id }, + Self::MoveObject((object_id, _, _)) => SuiError::ObjectNotFound { object_id }, } } } @@ -346,7 +341,7 @@ impl Order { #[allow(clippy::too_many_arguments)] pub fn new_move_call( - sender: FastPayAddress, + sender: SuiAddress, package: ObjectRef, module: Identifier, function: Identifier, @@ -372,7 +367,7 @@ impl Order { } pub fn new_module( - sender: FastPayAddress, + sender: SuiAddress, gas_payment: ObjectRef, modules: Vec>, gas_budget: u64, @@ -394,7 +389,7 @@ impl Order { Self::new(OrderKind::Transfer(transfer), secret) } - pub fn check_signature(&self) -> Result<(), FastPayError> { + pub fn check_signature(&self) -> Result<(), SuiError> { self.signature.check(&self.kind, *self.sender()) } @@ -485,7 +480,7 @@ impl Order { } // TODO: make sender a field of Order - pub fn sender(&self) -> &FastPayAddress { + pub fn sender(&self) -> &SuiAddress { use OrderKind::*; match &self.kind { Transfer(t) => &t.sender, @@ -516,10 +511,10 @@ impl SignedOrder { } /// Verify the signature and return the non-zero voting right of the authority. - pub fn check(&self, committee: &Committee) -> Result { + pub fn check(&self, committee: &Committee) -> Result { self.order.check_signature()?; let weight = committee.weight(&self.authority); - fp_ensure!(weight > 0, FastPayError::UnknownSigner); + fp_ensure!(weight > 0, SuiError::UnknownSigner); self.signature.check(&self.order.kind, self.authority)?; Ok(weight) } @@ -534,7 +529,7 @@ pub struct SignatureAggregator<'a> { impl<'a> SignatureAggregator<'a> { /// Start aggregating signatures for the given value into a certificate. - pub fn try_new(order: Order, committee: &'a Committee) -> Result { + pub fn try_new(order: Order, committee: &'a Committee) -> Result { order.check_signature()?; Ok(Self::new_unsafe(order, committee)) } @@ -559,17 +554,17 @@ impl<'a> SignatureAggregator<'a> { &mut self, authority: AuthorityName, signature: Signature, - ) -> Result, FastPayError> { + ) -> Result, SuiError> { signature.check(&self.partial.order.kind, authority)?; // Check that each authority only appears once. fp_ensure!( !self.used_authorities.contains(&authority), - FastPayError::CertificateAuthorityReuse + SuiError::CertificateAuthorityReuse ); self.used_authorities.insert(authority); // Update weight. let voting_rights = self.committee.weight(&authority); - fp_ensure!(voting_rights > 0, FastPayError::UnknownSigner); + fp_ensure!(voting_rights > 0, SuiError::UnknownSigner); self.weight += voting_rights; // Update certificate. self.partial.signatures.push((authority, signature)); @@ -584,7 +579,7 @@ impl<'a> SignatureAggregator<'a> { impl CertifiedOrder { /// Verify the certificate. - pub fn check(&self, committee: &Committee) -> Result<(), FastPayError> { + pub fn check(&self, committee: &Committee) -> Result<(), SuiError> { // Check the quorum. let mut weight = 0; let mut used_authorities = HashSet::new(); @@ -592,17 +587,17 @@ impl CertifiedOrder { // Check that each authority only appears once. fp_ensure!( !used_authorities.contains(authority), - FastPayError::CertificateAuthorityReuse + SuiError::CertificateAuthorityReuse ); used_authorities.insert(*authority); // Update weight. let voting_rights = committee.weight(authority); - fp_ensure!(voting_rights > 0, FastPayError::UnknownSigner); + fp_ensure!(voting_rights > 0, SuiError::UnknownSigner); weight += voting_rights; } fp_ensure!( weight >= committee.quorum_threshold(), - FastPayError::CertificateRequiresQuorum + SuiError::CertificateRequiresQuorum ); // All that is left is checking signatures! let inner_sig = (*self.order.sender(), self.order.signature); diff --git a/fastx_types/src/object.rs b/fastx_types/src/object.rs index 8b15b834cd25c..b5820fe119e19 100644 --- a/fastx_types/src/object.rs +++ b/fastx_types/src/object.rs @@ -19,11 +19,11 @@ use std::fmt::{Debug, Display, Formatter}; use move_binary_format::CompiledModule; use move_core_types::{account_address::AccountAddress, language_storage::StructTag}; -use crate::error::FastPayError; +use crate::error::SuiError; use crate::{ base_types::{ - sha3_hash, Authenticator, BcsSignable, FastPayAddress, ObjectDigest, ObjectID, ObjectRef, - SequenceNumber, TransactionDigest, + sha3_hash, Authenticator, BcsSignable, ObjectDigest, ObjectID, ObjectRef, SequenceNumber, + SuiAddress, TransactionDigest, }, gas_coin::GasCoin, }; @@ -144,14 +144,14 @@ impl MoveObject { &self, format: ObjectFormatOptions, resolver: &impl GetModule, - ) -> Result { + ) -> Result { let type_ = TypeTag::Struct(self.type_.clone()); let layout = if format.include_types { TypeLayoutBuilder::build_with_types(&type_, resolver) } else { TypeLayoutBuilder::build_with_fields(&type_, resolver) } - .map_err(|_e| FastPayError::ObjectSerializationError)?; + .map_err(|_e| SuiError::ObjectSerializationError)?; match layout { MoveTypeLayout::Struct(l) => Ok(l), _ => unreachable!( @@ -161,10 +161,10 @@ impl MoveObject { } /// Convert `self` to the JSON representation dictated by `layout`. - pub fn to_json(&self, layout: &MoveStructLayout) -> Result { + pub fn to_json(&self, layout: &MoveStructLayout) -> Result { let move_value = MoveStruct::simple_deserialize(&self.contents, layout) - .map_err(|_e| FastPayError::ObjectSerializationError)?; - serde_json::to_value(&move_value).map_err(|_e| FastPayError::ObjectSerializationError) + .map_err(|_e| SuiError::ObjectSerializationError)?; + serde_json::to_value(&move_value).map_err(|_e| SuiError::ObjectSerializationError) } } @@ -222,7 +222,7 @@ impl Data { &self, format: ObjectFormatOptions, resolver: &impl GetModule, - ) -> Result { + ) -> Result { use Data::*; match self { Move(m) => { @@ -236,10 +236,10 @@ impl Data { .expect("Adapter publish flow ensures that this bytecode deserializes"); let view = BinaryIndexedView::Module(&module); let d = Disassembler::from_view(view, Spanned::unsafe_no_loc(()).loc) - .map_err(|_e| FastPayError::ObjectSerializationError)?; + .map_err(|_e| SuiError::ObjectSerializationError)?; let bytecode_str = d .disassemble() - .map_err(|_e| FastPayError::ObjectSerializationError)?; + .map_err(|_e| SuiError::ObjectSerializationError)?; disassembled.insert(name.to_string(), Value::String(bytecode_str)); } Ok(Value::Object(disassembled)) @@ -340,7 +340,7 @@ impl Object { /// Change the owner of `self` to `new_owner` pub fn transfer(&mut self, new_owner: Authenticator) { - // TODO: these should be raised FastPayError's instead of panic's + // TODO: these should be raised SuiError's instead of panic's assert!(!self.is_read_only(), "Cannot transfer an immutable object"); match &mut self.data { Data::Move(m) => { @@ -359,7 +359,7 @@ impl Object { pub fn with_id_owner_gas_for_testing( id: ObjectID, version: SequenceNumber, - owner: FastPayAddress, + owner: SuiAddress, gas: u64, ) -> Self { let data = Data::Move(MoveObject { @@ -374,7 +374,7 @@ impl Object { } } - pub fn with_id_owner_for_testing(id: ObjectID, owner: FastPayAddress) -> Self { + pub fn with_id_owner_for_testing(id: ObjectID, owner: SuiAddress) -> Self { // For testing, we provide sufficient gas by default. Self::with_id_owner_gas_for_testing(id, SequenceNumber::new(), owner, GAS_VALUE_FOR_TESTING) } @@ -383,7 +383,7 @@ impl Object { pub fn with_id_owner_gas_coin_object_for_testing( id: ObjectID, version: SequenceNumber, - owner: FastPayAddress, + owner: SuiAddress, value: u64, ) -> Self { let obj = GasCoin::new(id, version, value); @@ -407,12 +407,12 @@ impl Object { &self, format: ObjectFormatOptions, resolver: &impl GetModule, - ) -> Result { + ) -> Result { let contents = self.data.to_json(format, resolver)?; - let owner = serde_json::to_value(&self.owner) - .map_err(|_e| FastPayError::ObjectSerializationError)?; + let owner = + serde_json::to_value(&self.owner).map_err(|_e| SuiError::ObjectSerializationError)?; let previous_transaction = serde_json::to_value(&self.previous_transaction) - .map_err(|_e| FastPayError::ObjectSerializationError)?; + .map_err(|_e| SuiError::ObjectSerializationError)?; Ok(json!({ "contents": contents, "owner": owner, "tx_digest": previous_transaction })) } } @@ -426,20 +426,20 @@ pub enum ObjectRead { impl ObjectRead { /// Returns a reference to the object if there is any, otherwise an Err if /// the object does exist or is deleted. - pub fn object(&self) -> Result<&Object, FastPayError> { + pub fn object(&self) -> Result<&Object, SuiError> { match &self { - Self::Deleted(oref) => Err(FastPayError::ObjectDeleted { object_ref: *oref }), - Self::NotExists(id) => Err(FastPayError::ObjectNotFound { object_id: *id }), + Self::Deleted(oref) => Err(SuiError::ObjectDeleted { object_ref: *oref }), + Self::NotExists(id) => Err(SuiError::ObjectNotFound { object_id: *id }), Self::Exists(_, o) => Ok(o), } } /// Returns the object ref if there is an object, otherwise an Err if /// the object does exist or is deleted. - pub fn reference(&self) -> Result { + pub fn reference(&self) -> Result { match &self { - Self::Deleted(oref) => Err(FastPayError::ObjectDeleted { object_ref: *oref }), - Self::NotExists(id) => Err(FastPayError::ObjectNotFound { object_id: *id }), + Self::Deleted(oref) => Err(SuiError::ObjectDeleted { object_ref: *oref }), + Self::NotExists(id) => Err(SuiError::ObjectNotFound { object_id: *id }), Self::Exists(oref, _) => Ok(*oref), } } diff --git a/fastx_types/src/serialize.rs b/fastx_types/src/serialize.rs index 2600a7a95cba9..dac63b2e88933 100644 --- a/fastx_types/src/serialize.rs +++ b/fastx_types/src/serialize.rs @@ -16,7 +16,7 @@ pub enum SerializedMessage { Order(Box), Vote(Box), Cert(Box), - Error(Box), + Error(Box), AccountInfoReq(Box), AccountInfoResp(Box), ObjectInfoReq(Box), @@ -34,7 +34,7 @@ enum ShallowSerializedMessage<'a> { Order(&'a Order), Vote(&'a SignedOrder), Cert(&'a CertifiedOrder), - Error(&'a FastPayError), + Error(&'a SuiError), AccountInfoReq(&'a AccountInfoRequest), AccountInfoResp(&'a AccountInfoResponse), ObjectInfoReq(&'a ObjectInfoRequest), @@ -76,7 +76,7 @@ where serialize_into(writer, &ShallowSerializedMessage::Order(value)) } -pub fn serialize_error(value: &FastPayError) -> Vec { +pub fn serialize_error(value: &SuiError) -> Vec { serialize(&ShallowSerializedMessage::Error(value)) } @@ -143,32 +143,28 @@ where bincode::deserialize_from(reader).map_err(|err| format_err!("{}", err)) } -pub fn deserialize_object_info( - message: SerializedMessage, -) -> Result { +pub fn deserialize_object_info(message: SerializedMessage) -> Result { match message { SerializedMessage::ObjectInfoResp(resp) => Ok(*resp), SerializedMessage::Error(error) => Err(*error), - _ => Err(FastPayError::UnexpectedMessage), + _ => Err(SuiError::UnexpectedMessage), } } pub fn deserialize_account_info( message: SerializedMessage, -) -> Result { +) -> Result { match message { SerializedMessage::AccountInfoResp(resp) => Ok(*resp), SerializedMessage::Error(error) => Err(*error), - _ => Err(FastPayError::UnexpectedMessage), + _ => Err(SuiError::UnexpectedMessage), } } -pub fn deserialize_order_info( - message: SerializedMessage, -) -> Result { +pub fn deserialize_order_info(message: SerializedMessage) -> Result { match message { SerializedMessage::OrderResp(resp) => Ok(*resp), SerializedMessage::Error(error) => Err(*error), - _ => Err(FastPayError::UnexpectedMessage), + _ => Err(SuiError::UnexpectedMessage), } } diff --git a/fastx_types/src/unit_tests/serialize_tests.rs b/fastx_types/src/unit_tests/serialize_tests.rs index 7ad8ecb10abea..420c3a855b440 100644 --- a/fastx_types/src/unit_tests/serialize_tests.rs +++ b/fastx_types/src/unit_tests/serialize_tests.rs @@ -35,7 +35,7 @@ fn compare_object_info_responses(o1: &ObjectInfoResponse, o2: &ObjectInfoRespons #[test] fn test_error() { - let err = FastPayError::UnknownSigner; + let err = SuiError::UnknownSigner; let buf = serialize_error(&err); let result = deserialize_message(buf.as_slice()); assert!(result.is_ok()); diff --git a/network_utils/src/network.rs b/network_utils/src/network.rs index 20c50802de7aa..83aec08a4a869 100644 --- a/network_utils/src/network.rs +++ b/network_utils/src/network.rs @@ -46,9 +46,9 @@ impl NetworkClient { time::timeout(self.recv_timeout, stream.read_data()).await? } - pub async fn send_recv_bytes(&self, buf: Vec) -> Result { + pub async fn send_recv_bytes(&self, buf: Vec) -> Result { match self.send_recv_bytes_internal(buf).await { - Err(error) => Err(FastPayError::ClientIoError { + Err(error) => Err(SuiError::ClientIoError { error: format!("{}", error), }), Ok(response) => { @@ -56,8 +56,8 @@ impl NetworkClient { match deserialize_message(&response[..]) { Ok(SerializedMessage::Error(error)) => Err(*error), Ok(message) => Ok(message), - Err(_) => Err(FastPayError::InvalidDecoding), - // _ => Err(FastPayError::UnexpectedMessage), + Err(_) => Err(SuiError::InvalidDecoding), + // _ => Err(SuiError::UnexpectedMessage), } } }