Skip to content

Commit

Permalink
refactor for miden 0.6
Browse files Browse the repository at this point in the history
  • Loading branch information
harsh-ps-2003 committed Nov 13, 2024
1 parent 6f246c7 commit 926ab91
Show file tree
Hide file tree
Showing 11 changed files with 185 additions and 159 deletions.
15 changes: 8 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ authors = ["Harsh Pratap Singh <[email protected]>"]
testing = ["miden-tx/testing"]

[dependencies]
miden-client = { version = "0.5", features = ["concurrent", "testing", "sqlite", "tonic"] }
miden-crypto = { version = "0.10", default-features = false }
miden-lib = { version = "0.5", default-features = false }
miden-objects = { version = "0.5.1", default-features = false }
miden-tx = { version = "0.5", features = ["testing"] }
miden-cli = { version = "0.5" }
miden-client = { version = "0.6", features = ["concurrent", "testing", "sqlite", "tonic"] }
miden-crypto = { version = "0.12", default-features = false }
miden-lib = { version = "0.6", default-features = false }
miden-objects = { version = "0.6.1", default-features = false }
miden-tx = { version = "0.6", features = ["testing"] }
miden-air = { version = "0.11", default-features = false }
miden-cli = { version = "0.6" }

rusqlite = { version = "0.31", features = ["vtab", "array", "bundled"]}
rusqlite = { version = "0.32", features = ["vtab", "array", "bundled"]}
rand = "0.8"
tonic = { version = "0.12.3" }
tokio = { version = "1.40.0", features = ["rt-multi-thread", "net", "macros"] }
Expand Down
78 changes: 34 additions & 44 deletions src/accounts/accounts.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use super::{data_to_word, public_key_to_string, word_to_data, word_to_masm, OracleData};
use miden_client::{
rpc::NodeRpcClient, store::Store, transactions::request::TransactionRequest, Client,
};
use miden_client::{rpc::NodeRpcClient, store::Store, transactions::TransactionRequest, Client};
use miden_crypto::{
dsa::rpo_falcon512::{PublicKey, SecretKey},
rand::FeltRng,
Expand All @@ -10,8 +8,8 @@ use miden_crypto::{
use miden_lib::{transaction::TransactionKernel, AuthScheme};
use miden_objects::{
accounts::{
Account, AccountCode, AccountId, AccountStorage, AccountStorageType, AccountType,
AuthSecretKey, SlotItem,
Account, AccountBuilder, AccountCode, AccountComponent, AccountId, AccountStorage,
AccountStorageMode, AccountType, AuthSecretKey, StorageSlot,
},
assembly::{Assembler, Library, LibraryNamespace, LibraryPath},
transaction::{TransactionArgs, TransactionScript},
Expand All @@ -23,6 +21,8 @@ use miden_tx::{
};
use rand::rngs::OsRng;
use std::collections::BTreeMap;
use std::error::Error as StdError;
use std::fmt;
use std::str::FromStr;
use std::sync::Arc;
use std::{
Expand Down Expand Up @@ -130,37 +130,32 @@ pub fn get_oracle_account(
init_seed: [u8; 32],
auth_scheme: AuthScheme,
account_type: AccountType,
account_storage_type: AccountStorageType,
account_storage_type: AccountStorageMode,
data_provider_public_key: PublicKey,
) -> Result<(Account, Word), AccountError> {
let (auth_scheme_procedure, storage_slot_0_data): (&str, Word) = match auth_scheme {
AuthScheme::RpoFalcon512 { pub_key } => ("auth_tx_rpo_falcon512", pub_key.into()),
};

let assembler = TransactionKernel::assembler();
let library = assembler.assemble_library([SOURCE_CODE]).unwrap();

let oracle_account_code = AccountCode::compile(SOURCE_CODE, assembler).unwrap();

let account_storage = AccountStorage::new(
let component = AccountComponent::new(
library,
vec![
SlotItem::new_value(0, 0, storage_slot_0_data),
SlotItem::new_value(1, 0, data_provider_public_key.into()),
StorageSlot::Value(storage_slot_0_data),
StorageSlot::Value(data_provider_public_key.into()),
],
BTreeMap::new(),
)?;

let account_seed = AccountId::get_account_seed(
init_seed,
account_type,
account_storage_type,
oracle_account_code.commitment(),
account_storage.root(),
)?;
let (account, seed) = AccountBuilder::new()
.init_seed(init_seed)
.account_type(account_type)
.storage_mode(account_storage_type)
.with_component(component)
.build()?;

Ok((
Account::new(account_seed, oracle_account_code, account_storage)?,
account_seed,
))
Ok((account, seed))
}

/// Helper function to create a transaction script
Expand Down Expand Up @@ -191,41 +186,36 @@ pub fn create_transaction_script(
}

/// Helper function to execute a transaction
async fn execute_transaction<N, R, S, A>(
client: &mut Client<N, R, S, A>,
async fn execute_transaction<R: FeltRng>(
client: &mut Client<R>,
account_id: AccountId,
tx_script: TransactionScript,
) -> Result<String, Box<dyn std::error::Error>>
where
N: NodeRpcClient,
R: FeltRng,
S: Store,
A: TransactionAuthenticator,
{
) -> Result<String, Box<dyn StdError>> {
let tx_request = TransactionRequest::new();
let request = TransactionRequest::with_custom_script(tx_request, tx_script)
.map_err(|err| err.to_string())?;
let transaction_execution_result = client.new_transaction(account_id, request)?;
.map_err(|e| Box::new(e) as Box<dyn StdError>)?;

let transaction_execution_result = client
.new_transaction(account_id, request)
.await
.map_err(|e| format!("Transaction execution failed: {}", e))?;

let transaction_id = transaction_execution_result.executed_transaction().id();

client
.submit_transaction(transaction_execution_result)
.await?;
.await
.map_err(|e| format!("Transaction submission failed: {}", e))?;

Ok(transaction_id.to_string())
}

pub async fn push_data_to_oracle_account<N, R, S, A>(
client: &mut Client<N, R, S, A>,
pub async fn push_data_to_oracle_account<R: FeltRng>(
client: &mut Client<R>,
account: Account,
data: OracleData,
data_provider_public_key: &PublicKey,
) -> Result<(), Box<dyn std::error::Error>>
where
N: NodeRpcClient,
R: FeltRng,
S: Store,
A: TransactionAuthenticator,
{
) -> Result<(), Box<dyn StdError>> {
let word = data_to_word(&data);

let push_tx_script_code = format!(
Expand Down
82 changes: 45 additions & 37 deletions src/accounts/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,31 @@ use miden_objects::assembly::{Library, LibraryNamespace};
use miden_objects::{
accounts::{
account_id::testing::ACCOUNT_ID_REGULAR_ACCOUNT_IMMUTABLE_CODE_ON_CHAIN, Account,
AccountCode, AccountId, AccountStorage, AccountStorageType, SlotItem,
AccountCode, AccountComponent, AccountId, AccountStorage, AccountStorageMode, AccountType,
AuthSecretKey, StorageSlot,
},
assets::AssetVault,
crypto::utils::Serializable,
transaction::{ExecutedTransaction, ProvenTransaction, TransactionArgs},
AccountError,
};
use miden_objects::{crypto::dsa::rpo_falcon512, ONE};
use miden_tx::auth::BasicAuthenticator;
use miden_tx::{
testing::TransactionContextBuilder, ProvingOptions, TransactionExecutor, TransactionProver,
TransactionVerifier, TransactionVerifierError,
testing::TransactionContextBuilder, LocalTransactionProver, ProvingOptions,
TransactionExecutor, TransactionProver, TransactionVerifier, TransactionVerifierError,
};
use rand::rngs::StdRng;
use rand_chacha::{rand_core::SeedableRng, ChaCha20Rng};
use std::{collections::BTreeMap, path::Path};
use std::{collections::BTreeMap, path::Path, sync::Arc};

#[test]
fn oracle_account_creation_and_pushing_data_to_read() {
#[tokio::test]
async fn oracle_account_creation_and_pushing_data_to_read() {
let (oracle_pub_key, oracle_auth) = get_new_pk_and_authenticator();
let data_provider_private_key = SecretKey::new();
let data_provider_public_key = data_provider_private_key.public_key();

let oracle_account = get_oracle_account(data_provider_public_key, oracle_pub_key);
let oracle_account = get_oracle_account(data_provider_public_key, oracle_pub_key).unwrap();

println!("Oracle account: {:?}", oracle_account.code().procedures());

Expand All @@ -51,8 +55,8 @@ fn oracle_account_creation_and_pushing_data_to_read() {
let mut word = data_to_word(&oracle_data);
word[0] = Felt::new(1);

let tx_context = TransactionContextBuilder::new(oracle_account.clone()).build();
let executor = TransactionExecutor::new(tx_context.clone(), Some(oracle_auth.clone()));
let tx_context = Arc::new(TransactionContextBuilder::new(oracle_account.clone()).build());
let executor = TransactionExecutor::new(tx_context, Some(Arc::new(oracle_auth)));

let push_tx_script_code = format!(
"{}",
Expand All @@ -78,12 +82,15 @@ fn oracle_account_creation_and_pushing_data_to_read() {
let txn_args = TransactionArgs::with_tx_script(push_tx_script);
let executed_transaction = executor
.execute_transaction(oracle_account.id(), 4, &[], txn_args)
.await
.unwrap();

// check that now the account has the data stored in its storage at slot 2
println!("Account Delta: {:?}", executed_transaction.account_delta());

assert!(prove_and_verify_transaction(executed_transaction.clone()).is_ok());
assert!(prove_and_verify_transaction(executed_transaction.clone())
.await
.is_ok());

// let read_tx_script_code = format!(
// "{}",
Expand Down Expand Up @@ -154,16 +161,7 @@ fn test_oracle_data_conversion() {
// }
// }

fn get_new_pk_and_authenticator() -> (
Word,
std::rc::Rc<miden_tx::auth::BasicAuthenticator<rand::rngs::StdRng>>,
) {
use std::rc::Rc;

use miden_objects::accounts::AuthSecretKey;
use miden_tx::auth::BasicAuthenticator;
use rand::rngs::StdRng;

fn get_new_pk_and_authenticator() -> (Word, BasicAuthenticator<StdRng>) {
let seed = [0_u8; 32];
let mut rng = ChaCha20Rng::from_seed(seed);

Expand All @@ -173,18 +171,17 @@ fn get_new_pk_and_authenticator() -> (
let authenticator =
BasicAuthenticator::<StdRng>::new(&[(pub_key, AuthSecretKey::RpoFalcon512(sec_key))]);

(pub_key, Rc::new(authenticator))
(pub_key, authenticator)
}

fn prove_and_verify_transaction(
async fn prove_and_verify_transaction(
executed_transaction: ExecutedTransaction,
) -> Result<(), TransactionVerifierError> {
let executed_transaction_id = executed_transaction.id();
// Prove the transaction

let proof_options = ProvingOptions::default();
let prover = TransactionProver::new(proof_options);
let proven_transaction = prover.prove_transaction(executed_transaction).unwrap();
let prover = LocalTransactionProver::new(proof_options);
let proven_transaction = prover.prove(executed_transaction.into()).await.unwrap();

assert_eq!(proven_transaction.id(), executed_transaction_id);

Expand All @@ -198,7 +195,10 @@ fn prove_and_verify_transaction(
verifier.verify(proven_transaction)
}

fn get_oracle_account(data_provider_public_key: PublicKey, oracle_public_key: Word) -> Account {
fn get_oracle_account(
data_provider_public_key: PublicKey,
oracle_public_key: Word,
) -> Result<Account, AccountError> {
let account_owner_public_key = PublicKey::new(oracle_public_key);
let oracle_account_id =
AccountId::try_from(ACCOUNT_ID_REGULAR_ACCOUNT_IMMUTABLE_CODE_ON_CHAIN).unwrap();
Expand Down Expand Up @@ -260,22 +260,30 @@ fn get_oracle_account(data_provider_public_key: PublicKey, oracle_public_key: Wo
end
"
);
let oracle_account_code = AccountCode::compile(source_code, assembler).unwrap();

let account_storage = AccountStorage::new(
let library = assembler.assemble_library([source_code]).unwrap();

let component = AccountComponent::new(
library,
vec![
SlotItem::new_value(0, 0, account_owner_public_key.into()),
SlotItem::new_value(1, 0, data_provider_public_key.into()),
StorageSlot::Value(account_owner_public_key.into()),
StorageSlot::Value(data_provider_public_key.into()),
],
BTreeMap::new(),
)
.unwrap();
)?;

let oracle_account_code =
AccountCode::from_components(&[component], AccountType::RegularAccountImmutableCode)?;

let account_storage = AccountStorage::new(vec![
StorageSlot::Value(account_owner_public_key.into()),
StorageSlot::Value(data_provider_public_key.into()),
])?;

Account::from_parts(
Ok(Account::from_parts(
oracle_account_id,
AssetVault::new(&[]).unwrap(),
account_storage.clone(),
oracle_account_code.clone(),
account_storage,
oracle_account_code,
Felt::new(1),
)
))
}
2 changes: 1 addition & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub struct Cli {

impl Cli {
pub async fn execute(&self) -> Result<(), String> {
let mut client = setup_client();
let mut client = setup_client().await;

match &self.action {
Command::Sync(sync) => sync.execute(&mut client).await,
Expand Down
25 changes: 12 additions & 13 deletions src/commands/new_oracle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use clap::{Parser, ValueEnum};
use miden_client::{rpc::NodeRpcClient, store::Store, Client, ClientError, Felt};
use miden_lib::{utils::hex_to_bytes, AuthScheme};
use miden_objects::{
accounts::{Account, AccountId, AccountStorageType, AccountType, AuthSecretKey},
accounts::{Account, AccountId, AccountStorageMode, AccountType, AuthSecretKey},
crypto::{
dsa::rpo_falcon512::{PublicKey, SecretKey},
rand::FeltRng,
Expand All @@ -25,21 +25,18 @@ pub struct AccountCmd {
pub trait OracleAccountCreation {
async fn new_oracle_account(
&mut self,
account_storage_type: AccountStorageType,
account_storage_type: AccountStorageMode,
data_provider_public_key: PublicKey,
) -> Result<(Account, Word), ClientError>;
}

impl AccountCmd {
pub async fn execute<N: NodeRpcClient, R: FeltRng, S: Store, A: TransactionAuthenticator>(
&self,
client: &mut Client<N, R, S, A>,
) -> Result<(), String>
pub async fn execute<R: FeltRng>(&self, client: &mut Client<R>) -> Result<(), String>
where
Client<N, R, S, A>: OracleAccountCreation,
Client<R>: OracleAccountCreation,
{
let (account, seed) = client
.new_oracle_account(AccountStorageType::OnChain, self.data_provider_public_key)
.new_oracle_account(AccountStorageMode::Public, self.data_provider_public_key)
.await
.map_err(|e| e.to_string())?;

Expand All @@ -53,12 +50,10 @@ impl AccountCmd {
}

#[maybe_async]
impl<N: NodeRpcClient, R: FeltRng, S: Store, A: TransactionAuthenticator> OracleAccountCreation
for Client<N, R, S, A>
{
impl<R: FeltRng> OracleAccountCreation for Client<R> {
async fn new_oracle_account(
&mut self,
account_storage_type: AccountStorageType,
account_storage_type: AccountStorageMode,
data_provider_public_key: PublicKey,
) -> Result<(Account, Word), ClientError> {
let key_pair = SecretKey::with_rng(&mut self.rng());
Expand All @@ -78,7 +73,11 @@ impl<N: NodeRpcClient, R: FeltRng, S: Store, A: TransactionAuthenticator> Oracle
data_provider_public_key,
)?;

self.insert_account(&account, Some(seed), &AuthSecretKey::RpoFalcon512(key_pair))?;
maybe_await!(self.insert_account(
&account,
Some(seed),
&AuthSecretKey::RpoFalcon512(key_pair)
))?;
Ok((account, seed))
}
}
Loading

0 comments on commit 926ab91

Please sign in to comment.