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

refactor(iroha_config): Immutable configuration #5257

Open
wants to merge 9 commits into
base: main
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
35 changes: 35 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ derive_more = { version = "0.99.18", default-features = false }
async-trait = "0.1.81"
strum = { version = "0.25.0", default-features = false }
getset = "0.1.2"
derive_builder = "0.20"
hex-literal = "0.4.1"
derive-where = "1.2.7"

Expand Down
2 changes: 2 additions & 0 deletions crates/iroha/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ iroha_logger = { workspace = true }
iroha_telemetry = { workspace = true }
iroha_torii_const = { workspace = true }
iroha_version = { workspace = true }
getset = { workspace = true }
derive_builder = { workspace = true }

iroha_data_model = { workspace = true, features = ["http"] }
iroha_executor_data_model = { workspace = true }
Expand Down
22 changes: 10 additions & 12 deletions crates/iroha/examples/tutorial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,20 @@ fn main() {

// Your code goes here…

domain_registration_test(config.clone())
domain_registration_test(&config)
.expect("Domain registration example is expected to work correctly");
account_definition_test().expect("Account definition example is expected to work correctly");
account_registration_test(config.clone())
account_registration_test(&config)
.expect("Account registration example is expected to work correctly");
asset_registration_test(config.clone())
asset_registration_test(&config)
.expect("Asset registration example is expected to work correctly");
asset_minting_test(config.clone())
.expect("Asset minting example is expected to work correctly");
asset_burning_test(config.clone())
.expect("Asset burning example is expected to work correctly");
asset_minting_test(&config).expect("Asset minting example is expected to work correctly");
asset_burning_test(&config).expect("Asset burning example is expected to work correctly");
// output_visualising_test(&config).expect(msg: "Visualising outputs example is expected to work correctly");
println!("Success!");
}

fn domain_registration_test(config: Config) -> Result<(), Error> {
fn domain_registration_test(config: &Config) -> Result<(), Error> {
// #region domain_register_example_crates
use iroha::{
client::Client,
Expand Down Expand Up @@ -93,7 +91,7 @@ fn account_definition_test() -> Result<(), Error> {
Ok(())
}

fn account_registration_test(config: Config) -> Result<(), Error> {
fn account_registration_test(config: &Config) -> Result<(), Error> {
// #region register_account_crates
use iroha::{
client::Client,
Expand Down Expand Up @@ -139,7 +137,7 @@ fn account_registration_test(config: Config) -> Result<(), Error> {
Ok(())
}

fn asset_registration_test(config: Config) -> Result<(), Error> {
fn asset_registration_test(config: &Config) -> Result<(), Error> {
// #region register_asset_crates
use iroha::{
client::Client,
Expand Down Expand Up @@ -187,7 +185,7 @@ fn asset_registration_test(config: Config) -> Result<(), Error> {
Ok(())
}

fn asset_minting_test(config: Config) -> Result<(), Error> {
fn asset_minting_test(config: &Config) -> Result<(), Error> {
// #region mint_asset_crates
use iroha::{
client::Client,
Expand Down Expand Up @@ -239,7 +237,7 @@ fn asset_minting_test(config: Config) -> Result<(), Error> {
Ok(())
}

fn asset_burning_test(config: Config) -> Result<(), Error> {
fn asset_burning_test(config: &Config) -> Result<(), Error> {
// #region burn_asset_crates
use iroha::{
client::Client,
Expand Down
75 changes: 32 additions & 43 deletions crates/iroha/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,28 +143,16 @@ pub struct Client {
impl Client {
/// Constructor for client from configuration
#[inline]
pub fn new(configuration: Config) -> Self {
pub fn new(configuration: &Config) -> Self {
Self::with_headers(configuration, HashMap::new())
}

/// Constructor for client from configuration and headers
///
/// *Authorization* header will be added if `basic_auth` is presented
#[inline]
pub fn with_headers(
Config {
chain,
account,
torii_api_url,
key_pair,
basic_auth,
transaction_add_nonce,
transaction_ttl,
transaction_status_timeout,
}: Config,
mut headers: HashMap<String, String>,
) -> Self {
if let Some(basic_auth) = basic_auth {
pub fn with_headers(config: &Config, mut headers: HashMap<String, String>) -> Self {
if let Some(basic_auth) = config.basic_auth().clone() {
let credentials = format!(
"{}:{}",
basic_auth.web_login,
Expand All @@ -176,14 +164,14 @@ impl Client {
}

Self {
chain,
torii_url: torii_api_url,
key_pair,
transaction_ttl: Some(transaction_ttl),
transaction_status_timeout,
account,
chain: config.chain().clone(),
torii_url: config.torii_api_url().clone(),
key_pair: config.key_pair().clone(),
transaction_ttl: Some(*config.transaction_ttl()),
transaction_status_timeout: *config.transaction_status_timeout(),
account: config.account().clone(),
headers,
add_transaction_nonce: transaction_add_nonce,
add_transaction_nonce: *config.transaction_add_nonce(),
}
}

Expand Down Expand Up @@ -982,7 +970,7 @@ mod tests {

use super::*;
use crate::{
config::{BasicAuth, Config},
config::{BasicAuth, ConfigBuilder},
secrecy::SecretString,
};

Expand All @@ -991,26 +979,26 @@ mod tests {
// `mad_hatter:ilovetea` encoded with base64
const ENCRYPTED_CREDENTIALS: &str = "bWFkX2hhdHRlcjppbG92ZXRlYQ==";

fn config_factory() -> Config {
fn with_default_config(config_builder: &mut ConfigBuilder) -> &mut ConfigBuilder {
let (account_id, key_pair) = gen_account_in("wonderland");
Config {
chain: ChainId::from("00000000-0000-0000-0000-000000000000"),
key_pair,
account: account_id,
torii_api_url: "http://127.0.0.1:8080".parse().unwrap(),
basic_auth: None,
transaction_add_nonce: false,
transaction_ttl: Duration::from_secs(5),
transaction_status_timeout: Duration::from_secs(10),
}
config_builder
.chain(ChainId::from("00000000-0000-0000-0000-000000000000"))
.key_pair(key_pair)
.account(account_id)
.torii_api_url("http://127.0.0.1:8080".parse().unwrap())
.transaction_ttl(Duration::from_secs(5))
.transaction_status_timeout(Duration::from_secs(10))
.transaction_add_nonce(false)
.basic_auth(None)
}

#[test]
fn txs_same_except_for_nonce_have_different_hashes() {
let client = Client::new(Config {
transaction_add_nonce: true,
..config_factory()
});
let config = with_default_config(&mut ConfigBuilder::default())
.transaction_add_nonce(true)
.build()
.expect("Can't build config");
let client = Client::new(&config);

let build_transaction =
|| client.build_transaction(Vec::<InstructionBox>::new(), Metadata::default());
Expand Down Expand Up @@ -1038,13 +1026,14 @@ mod tests {

#[test]
fn authorization_header() {
let client = Client::new(Config {
basic_auth: Some(BasicAuth {
let config = with_default_config(&mut ConfigBuilder::default())
.basic_auth(Some(BasicAuth {
web_login: LOGIN.parse().expect("Failed to create valid `WebLogin`"),
password: SecretString::new(PASSWORD.to_owned()),
}),
..config_factory()
});
}))
.build()
.expect("Can't build config");
let client = Client::new(&config);

let value = client
.headers
Expand Down
30 changes: 21 additions & 9 deletions crates/iroha/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
use core::str::FromStr;
use std::{path::Path, time::Duration};

use derive_builder::Builder;
use derive_more::Display;
use error_stack::ResultExt;
use eyre::Result;
use getset::Getters;
use iroha_config_base::{read::ConfigReader, toml::TomlSource};
use iroha_primitives::small::SmallStr;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -60,17 +62,27 @@ pub struct BasicAuth {
}

/// Complete client configuration
#[derive(Clone, Debug, Serialize)]
#[derive(Clone, Debug, Serialize, Getters, Builder)]
#[getset(get = "pub")]
#[builder(pattern = "mutable")]
#[allow(missing_docs)]
pub struct Config {
pub chain: ChainId,
pub account: AccountId,
pub key_pair: KeyPair,
pub basic_auth: Option<BasicAuth>,
pub torii_api_url: Url,
pub transaction_ttl: Duration,
pub transaction_status_timeout: Duration,
pub transaction_add_nonce: bool,
/// Blockchain id
chain: ChainId,
/// Account id
account: AccountId,
/// Public and Private keys
key_pair: KeyPair,
/// Basic Authentication credentials
basic_auth: Option<BasicAuth>,
/// Torii url
torii_api_url: Url,
/// Transaction TTL
transaction_ttl: Duration,
/// Transaction status timeout
transaction_status_timeout: Duration,
/// Transaction add nonce
transaction_add_nonce: bool,
}

/// An error type for [`Config::load`]
Expand Down
4 changes: 2 additions & 2 deletions crates/iroha_cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ trait RunContext {
fn configuration(&self) -> &Config;

fn client_from_config(&self) -> Client {
Client::new(self.configuration().clone())
Client::new(self.configuration())
}

/// Serialize and print data
Expand Down Expand Up @@ -1199,7 +1199,7 @@ mod json {
.wrap_err("Failed to submit parsed instructions")
}
Variant::Query => {
let client = Client::new(context.configuration().clone());
let client = Client::new(context.configuration());
let query: AnyQueryBox = json5::from_str(&string_content)?;

match query {
Expand Down
2 changes: 2 additions & 0 deletions crates/iroha_config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ derive_more = { workspace = true }
cfg-if = { workspace = true }
nonzero_ext = { workspace = true }
hex = { workspace = true, features = ["std"] }
getset = { workspace = true }
derive_builder = { workspace = true }

# for tracing
stderrlog = "0.6.0"
Expand Down
4 changes: 2 additions & 2 deletions crates/iroha_config/src/client_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub struct ConfigDTO {
impl From<&'_ BaseConfig> for ConfigDTO {
fn from(value: &'_ BaseConfig) -> Self {
Self {
logger: (&value.logger).into(),
logger: value.logger().into(),
}
}
}
Expand All @@ -41,7 +41,7 @@ pub struct Logger {
impl From<&'_ BaseLogger> for Logger {
fn from(value: &'_ BaseLogger) -> Self {
Self {
level: value.level.clone(),
level: value.level().clone(),
}
}
}
Expand Down
Loading
Loading