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!: don't send public key with signature #4518

Merged
merged 3 commits into from
Jun 13, 2024
Merged
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
1 change: 0 additions & 1 deletion Cargo.lock

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

34 changes: 29 additions & 5 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub struct Iroha {
/// A boolean value indicating whether or not the peers will receive data from the network.
/// Used in sumeragi testing.
#[cfg(debug_assertions)]
pub freeze_status: Arc<AtomicBool>,
pub freeze_status: FreezeStatus,
}

impl Drop for Iroha {
Expand Down Expand Up @@ -107,14 +107,37 @@ pub enum StartError {
StartTorii,
}

/// Handle for freezing and unfreezing the network
#[derive(Clone)]
#[cfg(debug_assertions)]
pub struct FreezeStatus(Arc<AtomicBool>, PeerId);

#[cfg(debug_assertions)]
impl FreezeStatus {
pub(crate) fn new(peer_id: PeerId) -> Self {
Self(Arc::new(AtomicBool::new(false)), peer_id)
}

/// Stop listening for messages
pub fn freeze(&self) {
iroha_logger::warn!(peer_id=%self.1, "NetworkRelay is frozen");
self.0.store(true, Ordering::SeqCst);
}
/// Start listening for messages
pub fn unfreeze(&self) {
iroha_logger::warn!(peer_id=%self.1, "NetworkRelay is unfrozen");
self.0.store(false, Ordering::SeqCst);
}
}

struct NetworkRelay {
sumeragi: SumeragiHandle,
block_sync: BlockSynchronizerHandle,
gossiper: TransactionGossiperHandle,
network: IrohaNetwork,
shutdown_notify: Arc<Notify>,
#[cfg(debug_assertions)]
freeze_status: Arc<AtomicBool>,
freeze_status: FreezeStatus,
}

impl NetworkRelay {
Expand Down Expand Up @@ -145,7 +168,7 @@ impl NetworkRelay {
use iroha_core::NetworkMessage::*;

#[cfg(debug_assertions)]
if self.freeze_status.load(Ordering::SeqCst) {
if self.freeze_status.0.load(Ordering::SeqCst) {
return;
}

Expand Down Expand Up @@ -335,7 +358,8 @@ impl Iroha {
.start();

#[cfg(debug_assertions)]
let freeze_status = Arc::new(AtomicBool::new(false));
let freeze_status = FreezeStatus::new(config.common.peer.clone());
Arc::new(AtomicBool::new(false));

let notify_shutdown = Arc::new(Notify::new());

Expand Down Expand Up @@ -510,7 +534,7 @@ impl Iroha {

#[allow(missing_docs)]
#[cfg(debug_assertions)]
pub fn freeze_status(&self) -> &Arc<AtomicBool> {
pub fn freeze_status(&self) -> &FreezeStatus {
&self.freeze_status
}

Expand Down
3 changes: 3 additions & 0 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ async fn main() -> error_stack::Result<(), MainError> {
iroha_logger::info!(
version = env!("CARGO_PKG_VERSION"),
git_commit_sha = env!("VERGEN_GIT_SHA"),
peer = %config.common.peer,
chain = %config.common.chain,
listening_on = %config.torii.address.value(),
"Hyperledgerいろは2にようこそ!(translation) Welcome to Hyperledger Iroha!"
);

Expand Down
2 changes: 0 additions & 2 deletions cli/src/samples.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,6 @@ pub fn get_config_toml(
) -> toml::Table {
let (public_key, private_key) = peer_key_pair.into_parts();

iroha_logger::info!(%public_key, "sample configuration public key");

let mut raw = toml::Table::new();
iroha_config::base::toml::Writer::new(&mut raw)
.write("chain", chain_id)
Expand Down
2 changes: 1 addition & 1 deletion client/benches/tps/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ use iroha::{
client::Client,
crypto::KeyPair,
data_model::{
events::pipeline::{BlockEventFilter, BlockStatus},
parameter::{default::MAX_TRANSACTIONS_IN_BLOCK, ParametersBuilder},
prelude::*,
},
};
use iroha_data_model::events::pipeline::{BlockEventFilter, BlockStatus};
use nonzero_ext::nonzero;
use serde::Deserialize;
use test_network::*;
Expand Down
6 changes: 4 additions & 2 deletions client/examples/million_accounts_genesis.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
//! This file contains examples from the Rust tutorial.
use std::{thread, time::Duration};

use iroha::{crypto::KeyPair, data_model::prelude::*};
use iroha_data_model::isi::InstructionBox;
use iroha::{
crypto::KeyPair,
data_model::{isi::InstructionBox, prelude::*},
};
use iroha_genesis::{GenesisTransaction, GenesisTransactionBuilder};
use iroha_primitives::unique_vec;
use irohad::samples::{construct_executor, get_config};
Expand Down
9 changes: 5 additions & 4 deletions client/examples/register_1000_triggers.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//! Example of registering multiple triggers
//! Used to show Iroha's trigger deduplication capabilities

use iroha::{client::Client, data_model::prelude::*};
use iroha_crypto::KeyPair;
use iroha_data_model::trigger::TriggerId;
use iroha::{
client::Client,
data_model::{prelude::*, trigger::TriggerId},
};
use iroha_genesis::{GenesisTransaction, GenesisTransactionBuilder};
use iroha_primitives::unique_vec;
use irohad::samples::{construct_executor, get_config};
Expand All @@ -17,7 +18,7 @@ use tokio::runtime::Runtime;
fn generate_genesis(
num_triggers: u32,
chain_id: ChainId,
genesis_key_pair: &KeyPair,
genesis_key_pair: &iroha_crypto::KeyPair,
) -> Result<GenesisTransaction, Box<dyn std::error::Error>> {
let builder = GenesisTransactionBuilder::default();

Expand Down
52 changes: 13 additions & 39 deletions client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,6 @@ use eyre::{eyre, Result, WrapErr};
use futures_util::StreamExt;
use http_default::{AsyncWebSocketStream, WebSocketStream};
pub use iroha_config::client_api::ConfigDTO;
use iroha_data_model::{
events::pipeline::{
BlockEventFilter, BlockStatus, PipelineEventBox, PipelineEventFilterBox,
TransactionEventFilter, TransactionStatus,
},
query::QueryOutputBox,
};
use iroha_logger::prelude::*;
use iroha_telemetry::metrics::Status;
use iroha_torii_const::uri as torii_uri;
Expand All @@ -36,9 +29,14 @@ use crate::{
crypto::{HashOf, KeyPair},
data_model::{
block::SignedBlock,
events::pipeline::{
BlockEventFilter, BlockStatus, PipelineEventBox, PipelineEventFilterBox,
TransactionEventFilter, TransactionStatus,
},
isi::Instruction,
prelude::*,
query::{predicate::PredicateBox, Pagination, Query, Sorting},
query::{predicate::PredicateBox, Pagination, Query, QueryOutputBox, Sorting},
transaction::TransactionBuilder,
BatchedResponse, ChainId, ValidationFail,
},
http::{Method as HttpMethod, RequestBuilder, Response, StatusCode},
Expand Down Expand Up @@ -68,24 +66,6 @@ impl<R> QueryResponseHandler<R> {
/// `Result` with [`ClientQueryError`] as an error
pub type QueryResult<T> = core::result::Result<T, ClientQueryError>;

/// Trait for signing transactions
pub trait Sign {
/// Sign transaction with provided key pair.
fn sign(self, key_pair: &crate::crypto::KeyPair) -> SignedTransaction;
}

impl Sign for TransactionBuilder {
fn sign(self, key_pair: &crate::crypto::KeyPair) -> SignedTransaction {
self.sign(key_pair)
}
}

impl Sign for SignedTransaction {
fn sign(self, key_pair: &crate::crypto::KeyPair) -> SignedTransaction {
self.sign(key_pair)
}
}

impl<R: QueryOutput> QueryResponseHandler<R>
where
<R as TryFrom<QueryOutputBox>>::Error: Into<eyre::Error>,
Expand Down Expand Up @@ -489,15 +469,17 @@ impl Client {
tx_builder.set_nonce(nonce);
};

tx_builder.with_metadata(metadata).sign(&self.key_pair)
tx_builder
.with_metadata(metadata)
.sign(self.key_pair.private_key())
}

/// Signs transaction
///
/// # Errors
/// Fails if signature generation fails
pub fn sign_transaction<Tx: Sign>(&self, transaction: Tx) -> SignedTransaction {
transaction.sign(&self.key_pair)
pub fn sign_transaction(&self, transaction: TransactionBuilder) -> SignedTransaction {
transaction.sign(self.key_pair.private_key())
}

/// Signs query
Expand Down Expand Up @@ -1684,20 +1666,12 @@ mod tests {
use http::Response;

use super::*;
use crate::data_model::{asset::Asset, query::error::QueryExecutionFail, ValidationFail};
use crate::data_model::{asset::Asset, ValidationFail};

#[test]
fn certain_errors() -> Result<()> {
let mut sut = QueryResponseHandler::<Vec<Asset>>::new(QueryRequest::dummy());
let responses = vec![
(
StatusCode::UNAUTHORIZED,
ValidationFail::QueryFailed(QueryExecutionFail::Signature(
"whatever".to_owned(),
)),
),
(StatusCode::UNPROCESSABLE_ENTITY, ValidationFail::TooComplex),
];
let responses = vec![(StatusCode::UNPROCESSABLE_ENTITY, ValidationFail::TooComplex)];
for (status_code, err) in responses {
let resp = Response::builder().status(status_code).body(err.encode())?;

Expand Down
7 changes: 5 additions & 2 deletions client/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@ use derive_more::Display;
use error_stack::ResultExt;
use eyre::Result;
use iroha_config_base::{read::ConfigReader, toml::TomlSource};
use iroha_crypto::KeyPair;
use iroha_data_model::{prelude::*, ChainId};
use iroha_primitives::small::SmallStr;
use serde::{Deserialize, Serialize};
use serde_with::{DeserializeFromStr, SerializeDisplay};
use url::Url;

use crate::{
crypto::KeyPair,
data_model::{prelude::*, ChainId},
};

mod user;

#[allow(missing_docs)]
Expand Down
Empty file.
7 changes: 4 additions & 3 deletions client/src/query_builder.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::fmt::Debug;

use iroha_data_model::query::{IterableQuery, QueryOutputBox};

use crate::{
client::{Client, QueryOutput, QueryResult},
data_model::query::{predicate::PredicateBox, sorting::Sorting, FetchSize, Pagination, Query},
data_model::query::{
predicate::PredicateBox, sorting::Sorting, FetchSize, IterableQuery, Pagination, Query,
QueryOutputBox,
},
};

pub struct QueryRequestBuilder<'a, R> {
Expand Down
14 changes: 7 additions & 7 deletions client/tests/integration/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ use eyre::Result;
use iroha::{
client::{self, QueryResult},
crypto::KeyPair,
data_model::prelude::*,
data_model::{
asset::{AssetId, AssetValue, AssetValueType},
isi::error::{InstructionEvaluationError, InstructionExecutionError, Mismatch, TypeError},
prelude::*,
transaction::error::TransactionRejectionReason,
},
};
use iroha_config::parameters::actual::Root as Config;
use iroha_data_model::{
asset::{AssetId, AssetValue, AssetValueType},
isi::error::{InstructionEvaluationError, InstructionExecutionError, Mismatch, TypeError},
transaction::error::TransactionRejectionReason,
};
use serde_json::json;
use test_network::*;
use test_samples::{gen_account_in, ALICE_ID, BOB_ID};
Expand Down Expand Up @@ -307,7 +307,7 @@ fn find_rate_and_make_exchange_isi_should_succeed() {
asset_id.account().clone(),
)
.with_instructions([instruction])
.sign(&owner_key_pair);
.sign(owner_key_pair.private_key());

test_client
.submit_transaction_blocking(&transaction)
Expand Down
12 changes: 5 additions & 7 deletions client/tests/integration/domain_owner_permissions.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use eyre::Result;
use iroha::data_model::prelude::*;
use iroha_data_model::transaction::error::TransactionRejectionReason;
use iroha::data_model::{prelude::*, transaction::error::TransactionRejectionReason};
use serde_json::json;
use test_network::*;
use test_samples::{gen_account_in, ALICE_ID, BOB_ID};
Expand All @@ -27,7 +26,7 @@ fn domain_owner_domain_permissions() -> Result<()> {
// Asset definitions can't be registered by "bob@kingdom" by default
let transaction = TransactionBuilder::new(chain_id.clone(), bob_id.clone())
.with_instructions([Register::asset_definition(coin.clone())])
.sign(&bob_keypair);
.sign(bob_keypair.private_key());
let err = test_client
.submit_transaction_blocking(&transaction)
.expect_err("Tx should fail due to permissions");
Expand All @@ -53,7 +52,7 @@ fn domain_owner_domain_permissions() -> Result<()> {
test_client.submit_blocking(Grant::permission(token.clone(), bob_id.clone()))?;
let transaction = TransactionBuilder::new(chain_id, bob_id.clone())
.with_instructions([Register::asset_definition(coin)])
.sign(&bob_keypair);
.sign(bob_keypair.private_key());
test_client.submit_transaction_blocking(&transaction)?;
test_client.submit_blocking(Revoke::permission(token, bob_id.clone()))?;

Expand Down Expand Up @@ -149,7 +148,7 @@ fn domain_owner_asset_definition_permissions() -> Result<()> {
let coin = AssetDefinition::numeric(coin_id.clone());
let transaction = TransactionBuilder::new(chain_id, bob_id.clone())
.with_instructions([Register::asset_definition(coin)])
.sign(&bob_keypair);
.sign(bob_keypair.private_key());
test_client.submit_transaction_blocking(&transaction)?;

// check that "alice@wonderland" as owner of domain can transfer asset definitions in her domain
Expand Down Expand Up @@ -218,7 +217,7 @@ fn domain_owner_asset_permissions() -> Result<()> {
Register::asset_definition(coin),
Register::asset_definition(store),
])
.sign(&bob_keypair);
.sign(bob_keypair.private_key());
test_client.submit_transaction_blocking(&transaction)?;

// check that "alice@wonderland" as owner of domain can register and unregister assets in her domain
Expand Down Expand Up @@ -304,7 +303,6 @@ fn domain_owner_trigger_permissions() -> Result<()> {
Ok(())
}

#[ignore = "migrated to client cli python tests"]
#[test]
fn domain_owner_transfer() -> Result<()> {
let (_rt, _peer, test_client) = <PeerBuilder>::new().with_port(11_100).start_with_runtime();
Expand Down
14 changes: 6 additions & 8 deletions client/tests/integration/events/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,17 @@ use eyre::Result;
use iroha::{
crypto::HashOf,
data_model::{
events::pipeline::{
BlockEvent, BlockEventFilter, BlockStatus, TransactionEventFilter, TransactionStatus,
},
isi::error::InstructionExecutionError,
parameter::{default::MAX_TRANSACTIONS_IN_BLOCK, ParametersBuilder},
prelude::*,
transaction::error::TransactionRejectionReason,
ValidationFail,
},
};
use iroha_config::parameters::actual::Root as Config;
use iroha_data_model::{
events::pipeline::{
BlockEvent, BlockEventFilter, BlockStatus, TransactionEventFilter, TransactionStatus,
},
isi::error::InstructionExecutionError,
transaction::error::TransactionRejectionReason,
ValidationFail,
};
use test_network::*;

// Needed to re-enable ignored tests.
Expand Down
1 change: 1 addition & 0 deletions client/tests/integration/extra_functional/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod connected_peers;
mod multiple_blocks_created;
mod normal;
mod offline_peers;
mod restart_peer;
mod unregister_peer;
Expand Down
Loading
Loading