Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add import_account_by_id #733

Open
wants to merge 4 commits into
base: tomyrd-authentication-refactor
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## 0.8.0 (TBD)

### Features

* Added support to import public accounts to `Client` (#733).

### Changes

* Add check for empty pay to id notes (#714).
Expand Down
63 changes: 61 additions & 2 deletions crates/rust-client/src/account/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,18 @@
//!
//! For more details on accounts, refer to the [Account] documentation.

use alloc::vec::Vec;
use alloc::{string::ToString, vec::Vec};

use miden_objects::{crypto::rand::FeltRng, Word};
use miden_lib::account::{auth::RpoFalcon512, wallets::BasicWallet};
use miden_objects::{
block::BlockHeader,
crypto::{dsa::rpo_falcon512::PublicKey, rand::FeltRng},
AccountError, Word,
};

use super::Client;
use crate::{
rpc::domain::account::AccountDetails,
store::{AccountRecord, AccountStatus},
ClientError,
};
Expand Down Expand Up @@ -163,6 +169,25 @@ impl<R: FeltRng> Client<R> {
}
}

/// Imports a new account from the node to the client's store. The account needs to be public
/// and is fetched from the node by its ID. If the account was already being tracked, it's
/// state will be overwritten.
///
/// # Errors
/// - If the account is private.
pub async fn import_account_by_id(&mut self, account_id: AccountId) -> Result<(), ClientError> {
let account_details = self.rpc_api.get_account_update(account_id).await?;

let account = match account_details {
AccountDetails::Private(..) => {
return Err(ClientError::AccountIsPrivate(account_id));
},
AccountDetails::Public(account, ..) => account,
};

self.add_account(&account, None, true).await
}

// ACCOUNT DATA RETRIEVAL
// --------------------------------------------------------------------------------------------

Expand Down Expand Up @@ -228,6 +253,40 @@ impl<R: FeltRng> Client<R> {
}
}

// UTILITY FUNCTIONS
// ================================================================================================

/// Builds an regular account ID from the provided parameters.
pub fn build_wallet_id(
init_seed: [u8; 32],
public_key: PublicKey,
storage_mode: AccountStorageMode,
is_mutable: bool,
anchor_block: BlockHeader,
) -> Result<AccountId, ClientError> {
let account_type = if is_mutable {
AccountType::RegularAccountUpdatableCode
} else {
AccountType::RegularAccountImmutableCode
};

let accound_id_anchor = (&anchor_block).try_into().map_err(|_| {
ClientError::AccountError(AccountError::AssumptionViolated(
"Provided block header is not an anchor block".to_string(),
))
})?;

let (account, _) = AccountBuilder::new(init_seed)
.anchor(accound_id_anchor)
.account_type(account_type)
.storage_mode(storage_mode)
.with_component(RpoFalcon512::new(public_key))
.with_component(BasicWallet)
.build()?;

Ok(account.id())
}

// TESTS
// ================================================================================================

Expand Down
2 changes: 2 additions & 0 deletions crates/rust-client/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ pub enum ClientError {
AccountLocked(AccountId),
#[error("network account hash {0} doesn't match the imported account hash")]
AccountHashMismatch(Digest),
#[error("account with id {0} is private")]
AccountIsPrivate(AccountId),
#[error("account nonce is too low to import")]
AccountNonceTooLow,
#[error("asset error")]
Expand Down
20 changes: 16 additions & 4 deletions tests/integration/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,10 @@ pub fn get_client_config() -> (Endpoint, u64, PathBuf, PathBuf) {

let timeout_ms = rpc_config_toml["timeout"].as_integer().unwrap() as u64;

(endpoint, timeout_ms, create_test_store_path(), temp_dir())
let auth_path = temp_dir().join(format!("keystore-{}", Uuid::new_v4()));
std::fs::create_dir_all(&auth_path).unwrap();

(endpoint, timeout_ms, create_test_store_path(), auth_path)
}

pub fn create_test_store_path() -> std::path::PathBuf {
Expand All @@ -104,15 +107,24 @@ pub async fn insert_new_wallet<R: FeltRng>(
client: &mut Client<R>,
storage_mode: AccountStorageMode,
keystore: &FilesystemKeyStore,
) -> Result<(Account, Word, SecretKey), ClientError> {
let mut init_seed = [0u8; 32];
client.rng().fill_bytes(&mut init_seed);

insert_new_wallet_with_seed(client, storage_mode, keystore, init_seed).await
}

pub async fn insert_new_wallet_with_seed<R: FeltRng>(
client: &mut Client<R>,
storage_mode: AccountStorageMode,
keystore: &FilesystemKeyStore,
init_seed: [u8; 32],
) -> Result<(Account, Word, SecretKey), ClientError> {
let key_pair = SecretKey::with_rng(client.rng());
let pub_key = key_pair.public_key();

keystore.add_key(&AuthSecretKey::RpoFalcon512(key_pair.clone())).unwrap();

let mut init_seed = [0u8; 32];
client.rng().fill_bytes(&mut init_seed);

let anchor_block = client.get_latest_epoch_block().await.unwrap();

let (account, seed) = AccountBuilder::new(init_seed)
Expand Down
65 changes: 65 additions & 0 deletions tests/integration/onchain_tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use miden_client::{
account::build_wallet_id,
auth::AuthSecretKey,
authenticator::keystore::KeyStore,
store::{InputNoteState, NoteFilter},
Expand Down Expand Up @@ -344,3 +345,67 @@ async fn test_onchain_notes_sync_with_tag() {
assert_eq!(received_note.note(), &note);
assert!(client_3.get_input_notes(NoteFilter::All).await.unwrap().is_empty());
}

#[tokio::test]
async fn test_import_account_by_id() {
let (mut client_1, keystore_1) = create_test_client().await;
let (mut client_2, keystore_2) = create_test_client().await;
wait_for_node(&mut client_1).await;

let mut user_seed = [0u8; 32];
client_1.rng().fill_bytes(&mut user_seed);

let (faucet_account_header, ..) =
insert_new_fungible_faucet(&mut client_1, AccountStorageMode::Public, &keystore_1)
.await
.unwrap();

let (first_regular_account, _, secret_key) = insert_new_wallet_with_seed(
&mut client_1,
AccountStorageMode::Public,
&keystore_1,
user_seed,
)
.await
.unwrap();

let target_account_id = first_regular_account.id();
let faucet_account_id = faucet_account_header.id();

// First mint and consume in the first client
println!("First client consuming note");
let note =
mint_note(&mut client_1, target_account_id, faucet_account_id, NoteType::Public).await;

consume_notes(&mut client_1, target_account_id, &[note]).await;

// Mint a note for the second client
let note =
mint_note(&mut client_1, target_account_id, faucet_account_id, NoteType::Public).await;

// Import the public account by id
let anchor_block = client_1.get_latest_epoch_block().await.unwrap();
let built_wallet_id = build_wallet_id(
user_seed,
secret_key.public_key(),
AccountStorageMode::Public,
false,
anchor_block,
)
.unwrap();
assert_eq!(built_wallet_id, first_regular_account.id());
client_2.import_account_by_id(built_wallet_id).await.unwrap();
keystore_2.add_key(&AuthSecretKey::RpoFalcon512(secret_key)).unwrap();

// Now use the wallet in the second client to consume the generated note
println!("Second client consuming note");
client_2.sync_state().await.unwrap();
consume_notes(&mut client_2, target_account_id, &[note]).await;
assert_account_has_single_asset(
&client_2,
target_account_id,
faucet_account_id,
MINT_AMOUNT * 2,
)
.await;
}
Loading