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]: #3268 Globally unique item identifiers #3317

Merged
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
24 changes: 12 additions & 12 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,13 @@ If you intend to implement the suggestion yourself, do the following:
1. Assign the issue you created to yourself **before** you start working on it.
2. Work on the feature you suggested and follow our [guidelines for code and documentation](#style-guides).
3. When you are ready to open a pull request, make sure you follow the [pull request guidelines](#pull-request-etiquette) and mark it as implementing the previously created issue:

```
[feature] #<issue number>: Description
```

4. If your change requires an API change, use the `api-changes` tag.

**Note:** features that require API changes may take longer to implement and approve as they require Iroha library makers to update their code.

### Asking Questions
Expand Down Expand Up @@ -132,7 +132,7 @@ Committing your work:
- Follow the [Git Style Guide](#git-workflow).
- Squash your commits [either before](https://www.git-tower.com/learn/git/faq/git-squash/) or [during the merge](https://rietta.com/blog/github-merge-types/).
- If during the preparation of your pull request your branch got out of date, rebase it locally with `git pull --rebase upstream iroha2-dev`. Alternatively, you may use the drop-down menu for the `Update branch` button and choose the `Update with rebase` option.

In the interest of making this process easier for everyone, try not to have more than a handful of commits for a pull request, and avoid re-using feature branches.

Creating a pull request:
Expand Down Expand Up @@ -164,10 +164,10 @@ To pass the *`check-PR-title`* check, the pull request should have the title tha
```
2. Add the issue number the pull request addresses:
- For `feature` and `fix` adding the issue number to the title is mandatory.
- For all other types it is optional but highly encouraged.
If your pull request solves multiple issues simultaneously, you can chain them with commas:
```
Expand Down Expand Up @@ -196,7 +196,7 @@ To pass the *`check-PR-title`* check, the pull request should have the title tha
Follow these commit guidelines:
- **Sign-off every commit**. If you don't, [DCO](https://github.com/apps/dco) will not let you merge.
Use `git commit -s` to automatically add `Signed-off-by: $NAME <$EMAIL>` as the final line of your commit message. Your name and email should be the same as specified in your GitHub account.
We also encourage you to sign your commits with GPG key using `git commit -sS` ([learn more](https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits)).
Expand Down Expand Up @@ -257,16 +257,16 @@ Code guidelines:
- Unless otherwise specified, refer to [Rust best practices](https://github.com/mre/idiomatic-rust).
- Use the `mod.rs` style. [Self-named modules](https://rust-lang.github.io/rust-clippy/master/) will not pass static analysis, except as [`trybuild`](https://crates.io/crates/trybuild) tests.
- Use a domain-first modules structure.
- Use a domain-first modules structure.
Example: don't do `constants::logger`. Instead, invert the hierarchy, putting the object for which it is used first: `iroha_logger::constants`.
- Use [`expect`](https://learning-rust.github.io/docs/e4.unwrap_and_expect.html) with an explicit error message or proof of infallibility instead of `unwrap`.
- Never ignore an error. If you can't `panic` and can't recover, it at least needs to be recorded in the log.
- Prefer to return a `Result` instead of `panic!`.
Exception: when implementing something that uses `issue_send` instead of `send` ([more about actors](docs/source/guides/actor.md)). Actors and parallelism don't mix; you could deadlock the entire peer, so it's better to `panic!` if something goes wrong. This is a necessary concession for asynchronous programming.
- Group related functionality spatially, preferably inside appropriate modules.
For example, instead of having a block with `struct` definitions and then `impl`s for each individual struct, it is better to have the `impl`s related to that `struct` next to it.
- Declare before implementation: `use` statements and constants at the top, unit tests at the bottom.
- Try to avoid `use` statements if the imported name is used only once. This makes moving your code into a different file easier.
Expand All @@ -276,7 +276,7 @@ Code guidelines:
- Avoid `Box<dyn Error>` if possible (we prefer strong typing).
- If your function is a getter/setter, mark it `#[inline]`.
- If your function is a constructor (i.e., it's creating a new value from the input parameters and calls `default()`), mark it `#[inline]`.
- Avoid tying your code to concrete data structures; `rustc` is smart enough to turn a `Vec<Instruction>` into `impl IntoIterator<Item = Instruction>` and vice versa when it needs to.
- Avoid tying your code to concrete data structures; `rustc` is smart enough to turn a `Vec<InstructionBox>` into `impl IntoIterator<Item = InstructionBox>` and vice versa when it needs to.
Naming guidelines:
- Use only full words in *public* structure, variable, method, trait, constant, and module names. However, abbreviations are allowed if:
Expand All @@ -292,7 +292,7 @@ Comment guidelines:
- You may leave `TODO` markers in code as long as you reference an issue that you created for it. Not creating an issue means it doesn't get merged.
We use pinned dependencies. Follow these guideline for versioning:
- If your work depends on a particular crate, see if it wasn't already installed using [`cargo tree`](https://doc.rust-lang.org/cargo/commands/cargo-tree.html) (use `bat` or `grep`), and try to use that version, instead of the latest version.
- Use the full version "X.Y.Z" in `Cargo.toml`.
- Provide version bumps in a separate PR.
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

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

6 changes: 2 additions & 4 deletions actor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
clippy::expect_used,
clippy::same_name_method
)]
#[cfg(feature = "deadlock_detection")]
use core::any::type_name;
use core::{
fmt::Debug,
ops::{Deref, DerefMut},
Expand Down Expand Up @@ -85,7 +83,7 @@ impl<A: Actor> Addr<A> {
Self {
sender,
#[cfg(feature = "deadlock_detection")]
actor_id: ActorId::new(Some(type_name::<A>())),
actor_id: ActorId::new(Some(core::any::type_name::<A>())),
}
}

Expand Down Expand Up @@ -432,7 +430,7 @@ impl<A: Actor> InitializedActor<A> {
}
}
}
iroha_logger::error!(actor = %std::any::type_name::<A>(), "Actor stopped");
iroha_logger::error!(actor = %core::any::type_name::<A>(), "Actor stopped");
actor.on_stop(&mut ctx).await;
}
.in_current_span();
Expand Down
2 changes: 1 addition & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ iroha_macro = { version = "=2.0.0-pre-rc.13", path = "../macro" }
iroha_logger = { version = "=2.0.0-pre-rc.13", path = "../logger" }
iroha_futures = { version = "=2.0.0-pre-rc.13", path = "../futures" }
iroha_actor = { version = "=2.0.0-pre-rc.13", path = "../actor" }
iroha_data_model = { version = "=2.0.0-pre-rc.13", path = "../data_model", features = ["transparent_api", "http"] }
iroha_data_model = { version = "=2.0.0-pre-rc.13", path = "../data_model", features = ["http"] }
iroha_telemetry = { version = "=2.0.0-pre-rc.13", path = "../telemetry", optional = true }
iroha_version = { version = "=2.0.0-pre-rc.13", path = "../version", features = ["http"] }
iroha_config = { version = "=2.0.0-pre-rc.13", path = "../config" }
Expand Down
1 change: 1 addition & 0 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use iroha_core::{
kura::Kura,
prelude::{World, WorldStateView},
queue::Queue,
smartcontracts::isi::Registrable as _,
sumeragi::Sumeragi,
tx::{PeerId, TransactionValidator},
IrohaNetwork,
Expand Down
2 changes: 1 addition & 1 deletion cli/src/samples.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use iroha_config::{
torii::{uri::DEFAULT_API_URL, DEFAULT_TORII_P2P_ADDR, DEFAULT_TORII_TELEMETRY_URL},
};
use iroha_crypto::{KeyPair, PublicKey};
use iroha_data_model::peer::Id as PeerId;
use iroha_data_model::peer::PeerId;

/// Get sample trusted peers. The public key must be the same as `configuration.public_key`
///
Expand Down
35 changes: 2 additions & 33 deletions cli/src/torii/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,34 +48,15 @@ pub enum Error {
/// Failed to execute or validate query
#[error("Failed to execute or validate query")]
Query(#[from] iroha_data_model::query::error::QueryExecutionFailure),
/// Failed to decode transaction
#[error("Failed to decode transaction")]
VersionedSignedTransaction(#[source] iroha_version::error::Error),
/// Failed to accept transaction
#[error("Failed to accept transaction: {0}")]
AcceptTransaction(#[from] iroha_data_model::transaction::error::AcceptTransactionFailure),
/// Failed to get pending transaction
#[error("Failed to get pending transactions: {0}")]
RequestPendingTransactions(#[source] eyre::Report),
/// Failed to decode pending transactions from leader
#[error("Failed to decode pending transactions from leader")]
DecodeRequestPendingTransactions(#[source] iroha_version::error::Error),
/// Failed to encode pending transactions
#[error("Failed to encode pending transactions")]
EncodePendingTransactions(#[source] iroha_version::error::Error),
/// The block sync message channel is full. Dropping the incoming message
#[error("Transaction is too big")]
TxTooBig,
/// Error while getting or setting configuration
#[error("Configuration error: {0}")]
Config(#[source] eyre::Report),
/// Failed to push into queue
#[error("Failed to push into queue")]
PushIntoQueue(#[from] Box<queue::Error>),
#[cfg(feature = "telemetry")]
/// Error while getting status
#[error("Failed to get status")]
Status(#[from] iroha_actor::Error),
/// Configuration change error.
#[error("Attempt to change configuration failed")]
ConfigurationReload(#[from] iroha_config::base::runtime_upgrades::ReloadError),
Expand Down Expand Up @@ -106,12 +87,6 @@ impl Reply for Error {
Query(err) => {
reply::with_status(utils::Scale(&err), query_status_code(&err)).into_response()
}
// TODO Have a type-preserved response body instead of a stringified one #2279
VersionedSignedTransaction(err)
| DecodeRequestPendingTransactions(err)
| EncodePendingTransactions(err) => {
reply::with_status(err.to_string(), err.status_code()).into_response()
}
_ => reply::with_status(Self::to_string(&self), self.status_code()).into_response(),
}
}
Expand All @@ -122,21 +97,15 @@ impl Error {
use Error::*;
match self {
Query(e) => query_status_code(e),
VersionedSignedTransaction(err)
| DecodeRequestPendingTransactions(err)
| EncodePendingTransactions(err) => err.status_code(),
AcceptTransaction(_)
| RequestPendingTransactions(_)
| ConfigurationReload(_)
| TxTooBig => StatusCode::BAD_REQUEST,
AcceptTransaction(_) | ConfigurationReload(_) => StatusCode::BAD_REQUEST,
Config(_) => StatusCode::NOT_FOUND,
PushIntoQueue(err) => match **err {
queue::Error::Full => StatusCode::INTERNAL_SERVER_ERROR,
queue::Error::SignatureCondition { .. } => StatusCode::UNAUTHORIZED,
_ => StatusCode::BAD_REQUEST,
},
#[cfg(feature = "telemetry")]
Prometheus(_) | Status(_) => StatusCode::INTERNAL_SERVER_ERROR,
Prometheus(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}

Expand Down
20 changes: 10 additions & 10 deletions cli/src/torii/routing.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Routing functions for Torii. If you want to add an endpoint to
//! Iroha you should add it here by creating a `handle_*` function,
//! and add it to impl Torii. This module also defines the `VerifiedQueryRequest`,
//! and add it to impl Torii. This module also defines the `VerifiedQuery`,
//! which is the only kind of query that is permitted to execute.
// FIXME: This can't be fixed, because one trait in `warp` is private.
Expand Down Expand Up @@ -47,15 +47,15 @@ pub fn sorting() -> impl warp::Filter<Extract = (Sorting,), Error = warp::Reject

/// Query Request verified on the Iroha node side.
#[derive(Debug, Decode, Encode)]
pub struct VerifiedQueryRequest {
pub struct VerifiedQuery {
/// Payload, containing the time, the query, the authenticating
/// user account and a filter
payload: query::http::Payload,
payload: query::http::QueryPayload,
/// Signature of the authenticating user
signature: SignatureOf<query::http::Payload>,
signature: SignatureOf<query::http::QueryPayload>,
}

impl VerifiedQueryRequest {
impl VerifiedQuery {
/// Validate query.
///
/// # Errors
Expand Down Expand Up @@ -84,10 +84,10 @@ impl VerifiedQueryRequest {
}
}

impl TryFrom<SignedQueryRequest> for VerifiedQueryRequest {
impl TryFrom<SignedQuery> for VerifiedQuery {
type Error = QueryExecutionFailure;

fn try_from(query: SignedQueryRequest) -> Result<Self, Self::Error> {
fn try_from(query: SignedQuery) -> Result<Self, Self::Error> {
query
.signature
.verify(&query.payload)
Expand Down Expand Up @@ -131,10 +131,10 @@ pub(crate) async fn handle_queries(
sumeragi: Arc<Sumeragi>,
pagination: Pagination,
sorting: Sorting,
request: VersionedSignedQueryRequest,
request: VersionedSignedQuery,
) -> Result<Scale<VersionedPaginatedQueryResult>> {
let VersionedSignedQueryRequest::V1(request) = request;
let request: VerifiedQueryRequest = request.try_into()?;
let VersionedSignedQuery::V1(request) = request;
let request: VerifiedQuery = request.try_into()?;

let (result, filter) = {
let wsv = sumeragi.wsv_mutex_access().clone();
Expand Down
18 changes: 9 additions & 9 deletions client/benches/tps/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ impl MeasurerUnit {
.with_params([("asset_id".parse()?, asset_id.clone().into())]);
let allow_alice_to_transfer_my_asset =
GrantBox::new(can_transfer_my_asset, alice_id).into();
let grant_tx = Transaction::new(
let grant_tx = TransactionBuilder::new(
account_id,
vec![
allow_alice_to_burn_my_asset,
Expand Down Expand Up @@ -222,15 +222,15 @@ impl MeasurerUnit {
let submitter = self.client.clone();
let interval_us_per_tx = self.config.interval_us_per_tx;
let instructions = self.instructions();
let alice_id = <Account as Identifiable>::Id::from_str("alice@wonderland")
.expect("Failed to parse account id");
let account_id = account_id(self.name);

let mut nonce = 0;
thread::spawn(move || {
for instruction in instructions {
match shutdown_signal.try_recv() {
Err(mpsc::TryRecvError::Empty) => {
let transaction =
Transaction::new(alice_id.clone(), [instruction], u64::MAX)
TransactionBuilder::new(account_id.clone(), [instruction], u64::MAX)
.with_nonce(nonce); // Use nonce to avoid transaction duplication within the same thread
let transaction = submitter
.sign_transaction(transaction)
Expand All @@ -254,13 +254,13 @@ impl MeasurerUnit {
}

#[allow(clippy::expect_used)]
fn instructions(&self) -> impl Iterator<Item = Instruction> {
fn instructions(&self) -> impl Iterator<Item = InstructionBox> {
[self.mint_or_burn(), self.relay_a_rose()]
.into_iter()
.cycle()
}

fn mint_or_burn(&self) -> Instruction {
fn mint_or_burn(&self) -> InstructionBox {
let is_running_out = Less::new(
EvaluatesTo::new_unchecked(
Expression::Query(FindAssetQuantityById::new(asset_id(self.name)).into()).into(),
Expand All @@ -270,10 +270,10 @@ impl MeasurerUnit {
let supply_roses = MintBox::new(100_u32.to_value(), asset_id(self.name));
let burn_a_rose = BurnBox::new(1_u32.to_value(), asset_id(self.name));

IfInstruction::with_otherwise(is_running_out, supply_roses, burn_a_rose).into()
Conditional::with_otherwise(is_running_out, supply_roses, burn_a_rose).into()
}

fn relay_a_rose(&self) -> Instruction {
fn relay_a_rose(&self) -> InstructionBox {
// Save at least one rose
// because if asset value hits 0 it's automatically deleted from account
// and query `FindAssetQuantityById` return error
Expand All @@ -289,7 +289,7 @@ impl MeasurerUnit {
asset_id(self.next_name),
);

IfInstruction::new(enough_to_transfer, transfer_rose).into()
Conditional::new(enough_to_transfer, transfer_rose).into()
}
}

Expand Down
Loading