Skip to content

Commit

Permalink
feat(stress-test): custom transactions to tx generator, result summary
Browse files Browse the repository at this point in the history
  • Loading branch information
sdbondi committed Jan 5, 2024
1 parent 6d30028 commit 984a3b4
Show file tree
Hide file tree
Showing 31 changed files with 551 additions and 174 deletions.
18 changes: 10 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 10 additions & 6 deletions applications/tari_dan_wallet_cli/src/command/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,12 +294,16 @@ async fn handle_submit_manifest(

let request = TransactionSubmitRequest {
signing_key_index: None,
fee_instructions: vec![Instruction::CallMethod {
component_address: fee_account.address.as_component_address().unwrap(),
method: "pay_fee".to_string(),
args: args![Amount::try_from(common.max_fee.unwrap_or(1000))?],
}],
instructions,
fee_instructions: instructions
.fee_instructions
.into_iter()
.chain(vec![Instruction::CallMethod {
component_address: fee_account.address.as_component_address().unwrap(),
method: "pay_fee".to_string(),
args: args![Amount::try_from(common.max_fee.unwrap_or(1000))?],
}])
.collect(),
instructions: instructions.instructions,
inputs: common.inputs,
override_inputs: common.override_inputs.unwrap_or_default(),
is_dry_run: common.dry_run,
Expand Down
2 changes: 2 additions & 0 deletions applications/tari_dan_wallet_daemon/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ pub struct Cli {
pub signaling_server_address: Option<SocketAddr>,
#[clap(long, alias = "indexer-url")]
pub indexer_node_json_rpc_url: Option<String>,
#[clap(long)]
pub derive_secret: Option<u64>,
}

impl Cli {
Expand Down
45 changes: 26 additions & 19 deletions applications/tari_dan_wallet_daemon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub mod cli;
pub mod config;
mod handlers;
mod http_ui;
mod indexer_jrpc_impl;
pub mod indexer_jrpc_impl;
mod jrpc_server;
mod notify;
mod services;
Expand Down Expand Up @@ -67,24 +67,7 @@ pub async fn run_tari_dan_wallet_daemon(
// Uncomment to enable tokio tracing via tokio-console
// console_subscriber::init();

let store = SqliteWalletStore::try_open(config.common.base_path.join("data/wallet.sqlite"))?;
store.run_migrations()?;

let sdk_config = WalletSdkConfig {
// TODO: Configure
password: None,
indexer_jrpc_endpoint: config.dan_wallet_daemon.indexer_node_json_rpc_url,
jwt_expiry: config.dan_wallet_daemon.jwt_expiry.unwrap(),
jwt_secret_key: config.dan_wallet_daemon.jwt_secret_key.unwrap(),
};
let config_api = ConfigApi::new(&store);
let indexer_jrpc_endpoint = if let Some(indexer_url) = config_api.get(ConfigKey::IndexerUrl).optional()? {
indexer_url
} else {
sdk_config.indexer_jrpc_endpoint.clone()
};
let indexer = IndexerJsonRpcNetworkInterface::new(indexer_jrpc_endpoint);
let wallet_sdk = DanWalletSdk::initialize(store, indexer, sdk_config)?;
let wallet_sdk = initialize_wallet_sdk(&config)?;
wallet_sdk
.key_manager_api()
.get_or_create_initial(key_manager::TRANSACTION_BRANCH)?;
Expand Down Expand Up @@ -127,3 +110,27 @@ pub async fn run_tari_dan_wallet_daemon(
}
Ok(())
}

pub fn initialize_wallet_sdk(
config: &ApplicationConfig,
) -> anyhow::Result<DanWalletSdk<SqliteWalletStore, IndexerJsonRpcNetworkInterface>> {
let store = SqliteWalletStore::try_open(config.common.base_path.join("data/wallet.sqlite"))?;
store.run_migrations()?;

let sdk_config = WalletSdkConfig {
// TODO: Configure
password: None,
indexer_jrpc_endpoint: config.dan_wallet_daemon.indexer_node_json_rpc_url.clone(),
jwt_expiry: config.dan_wallet_daemon.jwt_expiry.unwrap(),
jwt_secret_key: config.dan_wallet_daemon.jwt_secret_key.clone().unwrap(),
};
let config_api = ConfigApi::new(&store);
let indexer_jrpc_endpoint = if let Some(indexer_url) = config_api.get(ConfigKey::IndexerUrl).optional()? {
indexer_url
} else {
sdk_config.indexer_jrpc_endpoint.clone()
};
let indexer = IndexerJsonRpcNetworkInterface::new(indexer_jrpc_endpoint);
let wallet_sdk = DanWalletSdk::initialize(store, indexer, sdk_config)?;
Ok(wallet_sdk)
}
15 changes: 14 additions & 1 deletion applications/tari_dan_wallet_daemon/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
use std::{fs, panic, process};

use tari_common::{initialize_logging, load_configuration};
use tari_dan_wallet_daemon::{cli::Cli, config::ApplicationConfig, run_tari_dan_wallet_daemon};
use tari_crypto::{keys::PublicKey, ristretto::RistrettoPublicKey};
use tari_dan_wallet_daemon::{cli::Cli, config::ApplicationConfig, initialize_wallet_sdk, run_tari_dan_wallet_daemon};
use tari_dan_wallet_sdk::apis::key_manager;
use tari_shutdown::Shutdown;

#[tokio::main]
Expand All @@ -37,10 +39,21 @@ async fn main() -> Result<(), anyhow::Error> {
}));

let cli = Cli::init();

let config_path = cli.common.config_path();
let cfg = load_configuration(config_path, true, &cli)?;
let config = ApplicationConfig::load_from(&cfg)?;

if let Some(index) = cli.derive_secret {
let sdk = initialize_wallet_sdk(&config)?;
let secret = sdk
.key_manager_api()
.derive_key(key_manager::TRANSACTION_BRANCH, index)?;
println!("Secret: {}", secret.key.reveal());
println!("Public key: {}", RistrettoPublicKey::from_secret_key(&secret.key));
return Ok(());
}

// Remove the file if it was left behind by a previous run
let _file = fs::remove_file(config.common.base_path.join("pid"));

Expand Down
7 changes: 4 additions & 3 deletions applications/tari_validator_node/src/json_rpc/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ impl JsonRpcHandlers {
let request: GetTransactionResultRequest = value.parse_params()?;

let mut tx = self.state_store.create_read_tx().map_err(internal_error(answer_id))?;
let executed = ExecutedTransaction::get(&mut tx, &request.transaction_id)
let transaction = TransactionRecord::get(&mut tx, &request.transaction_id)
.optional()
.map_err(internal_error(answer_id))?
.ok_or_else(|| {
Expand All @@ -312,8 +312,9 @@ impl JsonRpcHandlers {
})?;

let response = GetTransactionResultResponse {
is_finalized: executed.is_finalized(),
result: executed.into_final_result(),
is_finalized: transaction.is_finalized(),
execution_time: transaction.execution_time(),
result: transaction.into_final_result(),
};
Ok(JsonRpcResponse::success(answer_id, response))
}
Expand Down
3 changes: 2 additions & 1 deletion applications/tari_validator_node_cli/src/command/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ impl ManifestSubcommand {
let contents = get_contents(args.manifest)?;
let instructions = tari_transaction_manifest::parse_manifest(&contents, Default::default())?;
// TODO: improve output
println!("Instructions: {:#?}", instructions);
println!("Instructions: {:#?}", instructions.instructions);
println!("Fee Instructions: {:#?}", instructions.fee_instructions);
},
ManifestSubcommand::New(args) => {
let mut out_stream = if let Some(ref path) = args.manifest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ async fn handle_submit_manifest(
) -> Result<SubmitTransactionResponse, anyhow::Error> {
let contents = std::fs::read_to_string(&args.manifest).map_err(|e| anyhow!("Failed to read manifest: {}", e))?;
let instructions = parse_manifest(&contents, manifest::parse_globals(args.input_variables)?)?;
submit_transaction(instructions, args.common, base_dir, client).await
submit_transaction(instructions.instructions, args.common, base_dir, client).await
}

pub async fn submit_transaction(
Expand Down
1 change: 1 addition & 0 deletions clients/validator_node_client/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ pub struct GetTransactionResultRequest {
pub struct GetTransactionResultResponse {
pub result: Option<ExecuteResult>,
pub is_finalized: bool,
pub execution_time: Option<Duration>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down
7 changes: 4 additions & 3 deletions dan_layer/engine/tests/templates/tariswap/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ mod tariswap {
Self::check_resource_is_fungible(b_addr);

// the fee represents a percentage, so it must be between 0 and 100
let valid_fee_range = 0..1000;
let valid_fee_range = 0..100;
assert!(valid_fee_range.contains(&fee), "Invalid fee {}", fee);

// create the vaults to store the funds
Expand Down Expand Up @@ -223,9 +223,10 @@ mod tariswap {
}

fn check_resource_is_fungible(resource: ResourceAddress) {
let resource_type = ResourceManager::get(resource).resource_type();
assert!(
ResourceManager::get(resource).resource_type() == ResourceType::Fungible,
"Resource {} is not fungible",
matches!(resource_type, ResourceType::Fungible | ResourceType::Confidential),
"Resource {} is not fungible nor confidential",
resource
);
}
Expand Down
4 changes: 4 additions & 0 deletions dan_layer/storage/src/consensus_models/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ impl TransactionRecord {
self.execution_time
}

pub fn is_finalized(&self) -> bool {
self.final_decision.is_some()
}

pub fn abort_details(&self) -> Option<&String> {
self.abort_details.as_ref()
}
Expand Down
2 changes: 1 addition & 1 deletion dan_layer/template_test_tooling/src/template_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ impl TemplateTest {
variables.into_iter().map(|(a, b)| (a.to_string(), b)).collect(),
)
.unwrap();
self.execute_and_commit(instructions, proofs)
self.execute_and_commit(instructions.instructions, proofs)
}

pub fn print_state(&self) {
Expand Down
8 changes: 4 additions & 4 deletions dan_layer/transaction_manifest/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,17 @@ use syn::{
Result,
};

use crate::parser::{ManifestIntent, ManifestParser};
use crate::parser::{ManifestParser, ParsedManifest};

#[derive(Debug, Clone)]
pub struct ManifestAst {
pub intents: Vec<ManifestIntent>,
pub parsed: ParsedManifest,
}

impl Parse for ManifestAst {
fn parse(input: ParseStream) -> Result<Self> {
let parser = ManifestParser::new();
let intents = parser.parse(input)?;
Ok(Self { intents })
let parsed = parser.parse(input)?;
Ok(Self { parsed })
}
}
38 changes: 24 additions & 14 deletions dan_layer/transaction_manifest/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use std::collections::{HashMap, HashSet};

use proc_macro2::Ident;
use syn::Lit;
use tari_engine_types::{instruction::Instruction, substate::SubstateAddress, TemplateAddress};
use tari_template_lib::{
Expand All @@ -15,11 +16,12 @@ use crate::{
ast::ManifestAst,
error::ManifestError,
parser::{InvokeIntent, ManifestIntent, ManifestLiteral, SpecialLiteral},
ManifestInstructions,
ManifestValue,
};

pub struct ManifestInstructionGenerator {
imported_templates: HashMap<String, TemplateAddress>,
imported_templates: HashMap<Ident, TemplateAddress>,
global_aliases: HashMap<String, ManifestValue>,
globals: HashMap<String, ManifestValue>,
variables: HashSet<String>,
Expand All @@ -35,24 +37,32 @@ impl ManifestInstructionGenerator {
}
}

pub fn generate_instructions(&mut self, ast: ManifestAst) -> Result<Vec<Instruction>, ManifestError> {
let mut instructions = Vec::with_capacity(ast.intents.len());
for intent in ast.intents {
pub fn generate_instructions(&mut self, ast: ManifestAst) -> Result<ManifestInstructions, ManifestError> {
self.imported_templates = ast
.parsed
.defines
.into_iter()
.map(|import| (import.alias, import.template_address))
.collect();

let mut instructions = Vec::with_capacity(ast.parsed.instruction_intents.len());
for intent in ast.parsed.instruction_intents {
instructions.extend(self.translate_intent(intent)?);
}

Ok(instructions)
let mut fee_instructions = Vec::with_capacity(ast.parsed.fee_instruction_intents.len());
for intent in ast.parsed.fee_instruction_intents {
fee_instructions.extend(self.translate_intent(intent)?);
}

Ok(ManifestInstructions {
instructions,
fee_instructions,
})
}

fn translate_intent(&mut self, intent: ManifestIntent) -> Result<Vec<Instruction>, ManifestError> {
match intent {
ManifestIntent::DefineTemplate {
template_address,
alias,
} => {
self.imported_templates.insert(alias.to_string(), template_address);
Ok(vec![])
},
ManifestIntent::InvokeTemplate(InvokeIntent {
output_variable,
template_variable,
Expand All @@ -64,7 +74,7 @@ impl ManifestInstructionGenerator {
.as_ref()
.expect("AST parse should have failed: no template ident for TemplateInvoke statement");
let mut instructions = vec![Instruction::CallFunction {
template_address: self.get_imported_template(&template_ident.to_string())?,
template_address: self.get_imported_template(template_ident)?,
function: function_name.to_string(),
args: self.process_args(arguments)?,
}];
Expand Down Expand Up @@ -173,7 +183,7 @@ impl ManifestInstructionGenerator {
.collect()
}

fn get_imported_template(&self, name: &str) -> Result<TemplateAddress, ManifestError> {
fn get_imported_template(&self, name: &Ident) -> Result<TemplateAddress, ManifestError> {
self.imported_templates
.get(name)
.copied()
Expand Down
Loading

0 comments on commit 984a3b4

Please sign in to comment.