Skip to content

Commit

Permalink
Rename Client to Gateway (MystenLabs#813)
Browse files Browse the repository at this point in the history
  • Loading branch information
lxfind authored Mar 13, 2022
1 parent 371e328 commit 3a40bfc
Show file tree
Hide file tree
Showing 9 changed files with 106 additions and 120 deletions.
8 changes: 2 additions & 6 deletions sui/src/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use serde::Deserialize;
use serde::Serialize;

use sui_core::authority_client::AuthorityClient;
use sui_core::client::{ClientAddressManager, GatewayClient};
use sui_core::gateway_state::{GatewayClient, GatewayState};
use sui_network::network::NetworkClient;
use sui_network::transport;
use sui_types::base_types::AuthorityName;
Expand Down Expand Up @@ -64,11 +64,7 @@ impl GatewayType {
let path = config.db_folder_path.clone();
let committee = config.make_committee();
let authority_clients = config.make_authority_clients();
Box::new(ClientAddressManager::new(
path,
committee,
authority_clients,
))
Box::new(GatewayState::new(path, committee, authority_clients))
}
_ => {
panic!("Unsupported gateway type")
Expand Down
12 changes: 6 additions & 6 deletions sui/src/rest_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ async fn sui_start(
for address in addresses.iter() {
wallet_context
.gateway
.sync_client_state(*address)
.sync_account_state(*address)
.await
.map_err(|err| {
custom_http_error(
Expand Down Expand Up @@ -458,7 +458,7 @@ async fn get_addresses(
// TODO: Speed up sync operations by kicking them off concurrently.
// Also need to investigate if this should be an automatic sync or manually triggered.
for address in addresses.iter() {
if let Err(err) = wallet_context.gateway.sync_client_state(*address).await {
if let Err(err) = wallet_context.gateway.sync_account_state(*address).await {
*server_context.wallet_context.lock().unwrap() = Some(wallet_context);
return Err(custom_http_error(
StatusCode::FAILED_DEPENDENCY,
Expand Down Expand Up @@ -668,7 +668,7 @@ struct ObjectInfoResponse {
owner: String,
/** Sequence number of the object */
version: String,
/** Hex code as string representing the objet id */
/** Hex code as string representing the object id */
id: String,
/** Boolean representing if the object is mutable */
readonly: String,
Expand Down Expand Up @@ -755,7 +755,7 @@ associated with the transaction that verifies the transaction.
#[derive(Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
struct TransactionResponse {
/** Integer representing the acutal cost of the transaction */
/** Integer representing the actual cost of the transaction */
gas_used: u64,
/** JSON representation of the list of resulting effects on the object */
object_effects_summary: serde_json::Value,
Expand Down Expand Up @@ -881,7 +881,7 @@ struct PublishRequest {

/**
Publish move module. It will perform proper verification and linking to make
sure the pacakge is valid. If some modules have initializers, these initializers
sure the package is valid. If some modules have initializers, these initializers
will also be executed in Move (which means new Move objects can be created in
the process of publishing a Move package). Gas budget is required because of the
need to execute module initializers.
Expand Down Expand Up @@ -1016,7 +1016,7 @@ async fn sync(
get_wallet_context(server_context.wallet_context.lock().unwrap().take())?;

// Attempt to create a new account state, but continue if it already exists.
if let Err(err) = wallet_context.gateway.sync_client_state(address).await {
if let Err(err) = wallet_context.gateway.sync_account_state(address).await {
*server_context.wallet_context.lock().unwrap() = Some(wallet_context);
return Err(custom_http_error(
StatusCode::FAILED_DEPENDENCY,
Expand Down
8 changes: 4 additions & 4 deletions sui/src/wallet_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ use structopt::clap::AppSettings;
use structopt::StructOpt;
use tracing::info;

use sui_core::client::client_responses::{MergeCoinResponse, SplitCoinResponse};
use sui_core::client::{AsyncTransactionSigner, GatewayClient};
use sui_core::gateway_state::gateway_responses::{MergeCoinResponse, SplitCoinResponse};
use sui_core::gateway_state::{AsyncTransactionSigner, GatewayClient};
use sui_framework::build_move_package_to_bytes;
use sui_types::base_types::{decode_bytes_hex, ObjectID, ObjectRef, SuiAddress};
use sui_types::crypto::{Signable, Signature};
Expand Down Expand Up @@ -358,7 +358,7 @@ impl WalletCommands {
}

WalletCommands::SyncClientState { address } => {
context.gateway.sync_client_state(*address).await?;
context.gateway.sync_account_state(*address).await?;
WalletCommandResult::SyncClientState
}
WalletCommands::NewAddress => {
Expand All @@ -368,7 +368,7 @@ impl WalletCommands {
WalletCommandResult::NewAddress(address)
}
WalletCommands::Gas { address } => {
context.gateway.sync_client_state(*address).await?;
context.gateway.sync_account_state(*address).await?;
let object_refs = context.gateway.get_owned_objects(*address);

// TODO: We should ideally fetch the objects from local cache
Expand Down
81 changes: 38 additions & 43 deletions sui_core/src/client.rs → sui_core/src/gateway_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use std::{
pin::Pin,
};

use self::client_responses::{MergeCoinResponse, SplitCoinResponse};
use self::gateway_responses::{MergeCoinResponse, SplitCoinResponse};

/// A trait for supplying transaction signature asynchronously.
///
Expand All @@ -42,7 +42,7 @@ use self::client_responses::{MergeCoinResponse, SplitCoinResponse};
/// # Example
/// ```
/// use signature::Error;
/// use sui_core::client::AsyncTransactionSigner;
/// use sui_core::gateway_state::AsyncTransactionSigner;
/// use sui_types::base_types::SuiAddress;
/// use sui_types::crypto::Signature;
/// use sui_types::messages::TransactionData;
Expand All @@ -55,15 +55,15 @@ use self::client_responses::{MergeCoinResponse, SplitCoinResponse};
/// impl AsyncTransactionSigner for ExampleTransactionSigner {
/// async fn sign(&self, address: &SuiAddress, data: TransactionData) -> Result<Signature, Error> {
/// // 1. Validate the transaction data
///
///
/// // 2. Create a signature if the transaction data is valid
/// let signature = Signature::new(&data, &self.signer);
/// // 3. return the signature
/// Ok(signature)
/// }
/// }
/// ```
/// This trait is typically use with [`StableSyncTransactionSigner`] to supply signature to the [`Client`] trait
/// This trait is typically use with [`StableSyncTransactionSigner`] to supply signature to the [`GatewayAPI`] trait
#[async_trait]
pub trait AsyncTransactionSigner {
async fn sign(
Expand All @@ -80,20 +80,20 @@ pub trait AsyncTransactionSigner {
/// Typically instantiated with Box::pin(tx_signer) where tx_signer is a [`AsyncTransactionSigner`]
pub type StableSyncTransactionSigner = Pin<Box<dyn AsyncTransactionSigner + Send + Sync>>;

pub mod client_responses;
pub mod client_store;
pub mod gateway_responses;
pub mod gateway_store;

pub type AsyncResult<'a, T, E> = future::BoxFuture<'a, Result<T, E>>;

pub type GatewayClient = Box<dyn Client + Sync + Send>;
pub type GatewayClient = Box<dyn GatewayAPI + Sync + Send>;

pub struct ClientAddressManager<A> {
pub struct GatewayState<A> {
authorities: AuthorityAggregator<A>,
store: client_store::ClientAddressManagerStore,
address_states: BTreeMap<SuiAddress, ClientState>,
store: gateway_store::GatewayStore,
address_states: BTreeMap<SuiAddress, AccountState>,
}

impl<A> ClientAddressManager<A>
impl<A> GatewayState<A>
where
A: AuthorityAPI + Send + Sync + 'static + Clone,
{
Expand All @@ -104,30 +104,30 @@ where
authority_clients: BTreeMap<AuthorityName, A>,
) -> Self {
Self {
store: client_store::ClientAddressManagerStore::open(path),
store: gateway_store::GatewayStore::open(path),
authorities: AuthorityAggregator::new(committee, authority_clients),
address_states: BTreeMap::new(),
}
}

fn get_or_create_account(&mut self, address: SuiAddress) -> SuiResult<&ClientState> {
let client_state = match self.address_states.entry(address) {
fn get_or_create_account(&mut self, address: SuiAddress) -> SuiResult<&AccountState> {
let account_state = match self.address_states.entry(address) {
Entry::Vacant(e) => {
let single_store = match self.store.get_managed_address(address)? {
Some(store) => store,
None => self.store.manage_new_address(address)?,
};
let state = ClientState::new_for_manager(address, single_store);
let state = AccountState::new_for_manager(address, single_store);
e.insert(state)
}
Entry::Occupied(o) => o.into_mut(),
};
Ok(client_state)
Ok(account_state)
}

/// Get all the states
#[cfg(test)]
pub fn get_managed_address_states(&self) -> &BTreeMap<SuiAddress, ClientState> {
pub fn get_managed_address_states(&self) -> &BTreeMap<SuiAddress, AccountState> {
&self.address_states
}

Expand All @@ -142,16 +142,16 @@ where
}
}

pub struct ClientState {
/// Our Sui address.
pub struct AccountState {
/// Sui address of this account.
address: SuiAddress,
/// Persistent store for client
store: client_store::ClientSingleAddressStore,
/// Persistent store for this account.
store: gateway_store::AccountStore,
}

// Operations are considered successful when they successfully reach a quorum of authorities.
#[async_trait]
pub trait Client {
pub trait GatewayAPI {
/// Send coin object to a Sui address.
async fn transfer_coin(
&mut self,
Expand All @@ -162,10 +162,10 @@ pub trait Client {
tx_signer: StableSyncTransactionSigner,
) -> Result<(CertifiedTransaction, TransactionEffects), anyhow::Error>;

/// Synchronise client state with a random authorities, updates all object_ids and certificates
/// Synchronise account state with a random authorities, updates all object_ids and certificates
/// from account_addr, request only goes out to one authority.
/// this method doesn't guarantee data correctness, client will have to handle potential byzantine authority
async fn sync_client_state(&mut self, account_addr: SuiAddress) -> Result<(), anyhow::Error>;
/// this method doesn't guarantee data correctness, caller will have to handle potential byzantine authority
async fn sync_account_state(&mut self, account_addr: SuiAddress) -> Result<(), anyhow::Error>;

/// Call move functions in the module in the given package, with args supplied
async fn move_call(
Expand Down Expand Up @@ -241,24 +241,19 @@ pub trait Client {
) -> Result<BTreeSet<ObjectRef>, SuiError>;
}

impl ClientState {
impl AccountState {
/// It is recommended that one call sync and download_owned_objects
/// right after constructor to fetch missing info form authorities
/// TODO: client should manage multiple addresses instead of each addr having DBs
/// https://github.com/MystenLabs/sui/issues/332
#[cfg(test)]
pub fn new(path: PathBuf, address: SuiAddress) -> Self {
ClientState {
AccountState {
address,
store: client_store::ClientSingleAddressStore::new(path),
store: gateway_store::AccountStore::new(path),
}
}

pub fn new_for_manager(
address: SuiAddress,
store: client_store::ClientSingleAddressStore,
) -> Self {
ClientState { address, store }
pub fn new_for_manager(address: SuiAddress, store: gateway_store::AccountStore) -> Self {
AccountState { address, store }
}

pub fn address(&self) -> SuiAddress {
Expand Down Expand Up @@ -397,7 +392,7 @@ impl ClientState {
}

#[cfg(test)]
pub fn store(&self) -> &client_store::ClientSingleAddressStore {
pub fn store(&self) -> &gateway_store::AccountStore {
&self.store
}

Expand All @@ -409,7 +404,7 @@ impl ClientState {
.collect()
}

/// This function verifies that the objects in the specfied transaction are locked by the given transaction
/// This function verifies that the objects in the specified transaction are locked by the given transaction
/// We use this to ensure that a transaction can indeed unlock or lock certain objects in the transaction
/// This means either exactly all the objects are owned by this transaction, or by no transaction
/// The caller has to explicitly find which objects are locked
Expand All @@ -435,7 +430,7 @@ impl ClientState {

/// Locks the objects for the given transaction
/// It is important to check that the object is not locked before locking again
/// One should call can_lock_or_unlock before locking as this overwites the previous lock
/// One should call can_lock_or_unlock before locking as this overwrites the previous lock
/// If the object is already locked, ensure it is unlocked by calling unlock_pending_transaction_objects
/// Client runs sequentially right now so access to this is safe
/// Double-locking can cause equivocation. TODO: https://github.com/MystenLabs/sui/issues/335
Expand Down Expand Up @@ -473,7 +468,7 @@ impl ClientState {
}
}

impl<A> ClientAddressManager<A>
impl<A> GatewayState<A>
where
A: AuthorityAPI + Send + Sync + 'static + Clone,
{
Expand Down Expand Up @@ -552,7 +547,7 @@ where
let account = self.get_or_create_account(address)?;
// The cert should be included in the response
let parent_tx_digest = cert.transaction.digest();
// TODO: certicates should ideally be inserted to the shared store.
// TODO: certificates should ideally be inserted to the shared store.
account.insert_certificate(&parent_tx_digest, &cert)?;

let mut objs_to_download = Vec::new();
Expand Down Expand Up @@ -651,7 +646,7 @@ where
}

#[async_trait]
impl<A> Client for ClientAddressManager<A>
impl<A> GatewayAPI for GatewayState<A>
where
A: AuthorityAPI + Send + Sync + Clone + 'static,
{
Expand All @@ -668,7 +663,7 @@ where
self.get_object_info(object_id)
.await?
.object()?
.is_transfer_elegible()?;
.is_transfer_eligible()?;

let account = self.get_or_create_account(signer)?;
let gas_payment = account.latest_object_ref(&gas_payment)?;
Expand All @@ -681,7 +676,7 @@ where
Ok((certificate, effects))
}

async fn sync_client_state(&mut self, account_addr: SuiAddress) -> Result<(), anyhow::Error> {
async fn sync_account_state(&mut self, account_addr: SuiAddress) -> Result<(), anyhow::Error> {
self.try_complete_pending_transactions(account_addr).await?;

let (active_object_certs, _deleted_refs_certs) = self
Expand Down
File renamed without changes.
Loading

0 comments on commit 3a40bfc

Please sign in to comment.