diff --git a/cli/src/lib.rs b/cli/src/lib.rs index 8c61027bcba..3957300b09d 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -826,7 +826,7 @@ mod tests { } fn dummy_executor() -> Executor { - Executor::new(WasmSmartContract::from_compiled(vec![1, 2, 3])) + Executor::new(SmartContract::from_compiled(vec![1, 2, 3])) } #[test] diff --git a/cli/src/samples.rs b/cli/src/samples.rs index dccce0fe4fa..9b977758968 100644 --- a/cli/src/samples.rs +++ b/cli/src/samples.rs @@ -115,5 +115,5 @@ where .optimize()? .into_bytes()?; - Ok(Executor::new(WasmSmartContract::from_compiled(wasm_blob))) + Ok(Executor::new(SmartContract::from_compiled(wasm_blob))) } diff --git a/client/benches/tps/utils.rs b/client/benches/tps/utils.rs index cca409724ae..fa2c4baf335 100644 --- a/client/benches/tps/utils.rs +++ b/client/benches/tps/utils.rs @@ -51,7 +51,7 @@ impl Config { let clients = network.clients(); wait_for_genesis_committed_with_max_retries(&clients, 0, self.genesis_max_retries); - client.submit_blocking(SetParameter::new(Parameter::Block(self.block_limits)))?; + client.submit_blocking(SetParameter::new(self.block_limits))?; let unit_names = (UnitName::MIN..).take(self.peers as usize); let units = clients diff --git a/client/examples/register_1000_triggers.rs b/client/examples/register_1000_triggers.rs index a7f31bd2962..bda2d4ff1a3 100644 --- a/client/examples/register_1000_triggers.rs +++ b/client/examples/register_1000_triggers.rs @@ -40,7 +40,7 @@ fn generate_genesis( .build()? .optimize()? .into_bytes()?; - let wasm = WasmSmartContract::from_compiled(wasm); + let wasm = SmartContract::from_compiled(wasm); let (account_id, _account_keypair) = gen_account_in("wonderland"); let build_trigger = |trigger_id: TriggerId| { diff --git a/client/src/client.rs b/client/src/client.rs index d7729127604..773ab303390 100644 --- a/client/src/client.rs +++ b/client/src/client.rs @@ -16,7 +16,6 @@ use futures_util::StreamExt; use http_default::{AsyncWebSocketStream, WebSocketStream}; pub use iroha_config::client_api::ConfigDTO; use iroha_logger::prelude::*; -use iroha_primitives::json; use iroha_telemetry::metrics::Status; use iroha_torii_const::uri as torii_uri; use iroha_version::prelude::*; @@ -327,7 +326,7 @@ impl_query_output! { crate::data_model::account::Account, crate::data_model::domain::Domain, crate::data_model::block::BlockHeader, - json::JsonString, + crate::data_model::prelude::JsonString, crate::data_model::query::TransactionQueryOutput, crate::data_model::executor::ExecutorDataModel, crate::data_model::trigger::Trigger, @@ -447,7 +446,7 @@ impl Client { } } - /// Builds transaction out of supplied instructions or wasm. + /// Builds transaction out of supplied instructions or smart contract. /// /// # Errors /// Fails if signing transaction fails @@ -460,7 +459,9 @@ impl Client { let mut tx_builder = match instructions.into() { Executable::Instructions(instructions) => tx_builder.with_instructions(instructions), - Executable::Wasm(wasm) => tx_builder.with_wasm(wasm), + Executable::SmartContract(smart_contract) => { + tx_builder.with_smart_contract(smart_contract) + } }; if let Some(transaction_ttl) = self.transaction_ttl { diff --git a/client/tests/integration/asset_propagation.rs b/client/tests/integration/asset_propagation.rs index c191c5fdb82..75994e92b45 100644 --- a/client/tests/integration/asset_propagation.rs +++ b/client/tests/integration/asset_propagation.rs @@ -20,8 +20,8 @@ fn client_add_asset_quantity_to_existing_asset_should_increase_asset_amount_on_a wait_for_genesis_committed(&network.clients(), 0); let pipeline_time = Config::pipeline_time(); - client.submit_blocking(SetParameter::new(Parameter::Block( - BlockParameter::MaxTransactions(nonzero!(1_u64)), + client.submit_blocking(SetParameter::new(BlockParameter::MaxTransactions( + nonzero!(1_u64), )))?; let create_domain = Register::domain(Domain::new(DomainId::from_str("domain")?)); diff --git a/client/tests/integration/events/data.rs b/client/tests/integration/events/data.rs index 4c9e32e6e2a..31407295a8c 100644 --- a/client/tests/integration/events/data.rs +++ b/client/tests/integration/events/data.rs @@ -1,7 +1,7 @@ use std::{fmt::Write as _, sync::mpsc, thread}; use eyre::Result; -use iroha::data_model::{prelude::*, transaction::WasmSmartContract}; +use iroha::data_model::{prelude::*, transaction::SmartContract}; use iroha_executor_data_model::permission::account::{ CanRemoveKeyValueInAccount, CanSetKeyValueInAccount, }; @@ -125,7 +125,7 @@ fn wasm_execution_should_produce_events() -> Result<()> { ); transaction_execution_should_produce_events( - WasmSmartContract::from_compiled(wat.into_bytes()), + SmartContract::from_compiled(wat.into_bytes()), 10_615, ) } diff --git a/client/tests/integration/events/pipeline.rs b/client/tests/integration/events/pipeline.rs index f57d4382563..dd34a74d83a 100644 --- a/client/tests/integration/events/pipeline.rs +++ b/client/tests/integration/events/pipeline.rs @@ -57,8 +57,8 @@ fn test_with_instruction_and_status_and_port( wait_for_genesis_committed(&clients, 0); let pipeline_time = Config::pipeline_time(); - client.submit_blocking(SetParameter::new(Parameter::Block( - BlockParameter::MaxTransactions(nonzero!(1_u64)), + client.submit_blocking(SetParameter::new(BlockParameter::MaxTransactions( + nonzero!(1_u64), )))?; // Given diff --git a/client/tests/integration/extra_functional/multiple_blocks_created.rs b/client/tests/integration/extra_functional/multiple_blocks_created.rs index 78d10cae935..fb228b75920 100644 --- a/client/tests/integration/extra_functional/multiple_blocks_created.rs +++ b/client/tests/integration/extra_functional/multiple_blocks_created.rs @@ -20,8 +20,8 @@ fn long_multiple_blocks_created() -> Result<()> { wait_for_genesis_committed(&network.clients(), 0); let pipeline_time = Config::pipeline_time(); - client.submit_blocking(SetParameter::new(Parameter::Block( - BlockParameter::MaxTransactions(nonzero!(1_u64)), + client.submit_blocking(SetParameter::new(BlockParameter::MaxTransactions( + nonzero!(1_u64), )))?; let create_domain = Register::domain(Domain::new("domain".parse()?)); diff --git a/client/tests/integration/extra_functional/normal.rs b/client/tests/integration/extra_functional/normal.rs index 401d3b22626..b8b364aef45 100644 --- a/client/tests/integration/extra_functional/normal.rs +++ b/client/tests/integration/extra_functional/normal.rs @@ -10,8 +10,8 @@ fn tranasctions_should_be_applied() { let (_rt, network, iroha) = NetworkBuilder::new(4, Some(11_300)).create_with_runtime(); wait_for_genesis_committed(&network.clients(), 0); iroha - .submit_blocking(SetParameter::new(Parameter::Block( - BlockParameter::MaxTransactions(nonzero!(1_u64)), + .submit_blocking(SetParameter::new(BlockParameter::MaxTransactions( + nonzero!(1_u64), ))) .unwrap(); diff --git a/client/tests/integration/extra_functional/unregister_peer.rs b/client/tests/integration/extra_functional/unregister_peer.rs index ebd9ff458a9..082037f4648 100644 --- a/client/tests/integration/extra_functional/unregister_peer.rs +++ b/client/tests/integration/extra_functional/unregister_peer.rs @@ -116,9 +116,7 @@ fn init() -> Result<( let pipeline_time = Config::pipeline_time(); iroha_logger::info!("Started"); - let set_max_txns_in_block = SetParameter::new(Parameter::Block( - BlockParameter::MaxTransactions(nonzero!(1_u64)), - )); + let set_max_txns_in_block = SetParameter::new(BlockParameter::MaxTransactions(nonzero!(1_u64))); let create_domain = Register::domain(Domain::new("domain".parse()?)); let (account_id, _account_keypair) = gen_account_in("domain"); diff --git a/client/tests/integration/extra_functional/unstable_network.rs b/client/tests/integration/extra_functional/unstable_network.rs index c917b85580d..f3364f15c99 100644 --- a/client/tests/integration/extra_functional/unstable_network.rs +++ b/client/tests/integration/extra_functional/unstable_network.rs @@ -2,10 +2,7 @@ use std::thread; use iroha::{ client::{self, QueryResult}, - data_model::{ - parameter::{BlockParameter, Parameter}, - prelude::*, - }, + data_model::{parameter::BlockParameter, prelude::*}, }; use iroha_config::parameters::actual::Root as Config; use nonzero_ext::nonzero; @@ -64,8 +61,8 @@ fn unstable_network( .create_with_runtime(); wait_for_genesis_committed(&network.clients(), n_offline_peers); iroha - .submit_blocking(SetParameter::new(Parameter::Block( - BlockParameter::MaxTransactions(nonzero!(5_u64)), + .submit_blocking(SetParameter::new(BlockParameter::MaxTransactions( + nonzero!(5_u64), ))) .unwrap(); diff --git a/client/tests/integration/multisig.rs b/client/tests/integration/multisig.rs index c7fd8b0bb0c..b6fdcd4c321 100644 --- a/client/tests/integration/multisig.rs +++ b/client/tests/integration/multisig.rs @@ -7,7 +7,7 @@ use iroha::{ crypto::KeyPair, data_model::{ prelude::*, - transaction::{TransactionBuilder, WasmSmartContract}, + transaction::{SmartContract, TransactionBuilder}, }, }; use iroha_data_model::parameter::SmartContractParameter; @@ -38,7 +38,7 @@ fn mutlisig() -> Result<()> { .build()? .optimize()? .into_bytes()?; - let wasm = WasmSmartContract::from_compiled(wasm); + let wasm = SmartContract::from_compiled(wasm); let trigger = Trigger::new( multisig_register_trigger_id.clone(), diff --git a/client/tests/integration/queries/smart_contract.rs b/client/tests/integration/queries/smart_contract.rs index e41c4bd985a..9eda4b7887a 100644 --- a/client/tests/integration/queries/smart_contract.rs +++ b/client/tests/integration/queries/smart_contract.rs @@ -12,7 +12,7 @@ fn live_query_is_dropped_after_smart_contract_end() -> Result<()> { let (_rt, _peer, client) = ::new().with_port(11_140).start_with_runtime(); wait_for_genesis_committed(&[client.clone()], 0); - let wasm = iroha_wasm_builder::Builder::new( + let smart_contract = iroha_wasm_builder::Builder::new( "tests/integration/smartcontracts/query_assets_and_save_cursor", ) .show_output() @@ -20,8 +20,10 @@ fn live_query_is_dropped_after_smart_contract_end() -> Result<()> { .optimize()? .into_bytes()?; - let transaction = - client.build_transaction(WasmSmartContract::from_compiled(wasm), Metadata::default()); + let transaction = client.build_transaction( + SmartContract::from_compiled(smart_contract), + Metadata::default(), + ); client.submit_transaction_blocking(&transaction)?; let metadata_value: JsonString = client.request(FindAccountKeyValueByIdAndKey::new( @@ -49,7 +51,7 @@ fn smart_contract_can_filter_queries() -> Result<()> { let (_rt, _peer, client) = ::new().with_port(11_260).start_with_runtime(); wait_for_genesis_committed(&[client.clone()], 0); - let wasm = iroha_wasm_builder::Builder::new( + let smart_contract = iroha_wasm_builder::Builder::new( "tests/integration/smartcontracts/smart_contract_can_filter_queries", ) .show_output() @@ -57,8 +59,10 @@ fn smart_contract_can_filter_queries() -> Result<()> { .optimize()? .into_bytes()?; - let transaction = - client.build_transaction(WasmSmartContract::from_compiled(wasm), Metadata::default()); + let transaction = client.build_transaction( + SmartContract::from_compiled(smart_contract), + Metadata::default(), + ); client.submit_transaction_blocking(&transaction)?; Ok(()) diff --git a/client/tests/integration/smartcontracts/multisig_register/src/lib.rs b/client/tests/integration/smartcontracts/multisig_register/src/lib.rs index f3f2dfb6530..40f299a790d 100644 --- a/client/tests/integration/smartcontracts/multisig_register/src/lib.rs +++ b/client/tests/integration/smartcontracts/multisig_register/src/lib.rs @@ -18,8 +18,9 @@ static ALLOC: LockedAllocator = LockedAllocator::new(FreeList getrandom::register_custom_getrandom!(iroha_trigger::stub_getrandom); -// Trigger wasm code for handling multisig logic -const WASM: &[u8] = core::include_bytes!(concat!(core::env!("OUT_DIR"), "/multisig.wasm")); +// Trigger for handling multisig logic +const SMART_CONTRACT: &[u8] = + core::include_bytes!(concat!(core::env!("OUT_DIR"), "/multisig.wasm")); #[iroha_trigger::main] fn main(_id: TriggerId, _owner: AccountId, event: EventBox) { @@ -46,7 +47,7 @@ fn main(_id: TriggerId, _owner: AccountId, event: EventBox) { .parse() .dbg_expect("failed to parse trigger id"); - let payload = WasmSmartContract::from_compiled(WASM.to_vec()); + let payload = SmartContract::from_compiled(SMART_CONTRACT.to_vec()); let trigger = Trigger::new( trigger_id.clone(), Action::new( diff --git a/client/tests/integration/triggers/by_call_trigger.rs b/client/tests/integration/triggers/by_call_trigger.rs index 293982cee0e..1cdc6bece7e 100644 --- a/client/tests/integration/triggers/by_call_trigger.rs +++ b/client/tests/integration/triggers/by_call_trigger.rs @@ -8,7 +8,7 @@ use iroha::{ data_model::{ prelude::*, query::error::{FindError, QueryExecutionFail}, - transaction::{Executable, WasmSmartContract}, + transaction::{Executable, SmartContract}, }, }; use iroha_executor_data_model::permission::trigger::CanRegisterUserTrigger; @@ -430,7 +430,7 @@ fn trigger_in_genesis_using_base64() -> Result<()> { let trigger = Trigger::new( trigger_id.clone(), Action::new( - serde_json::from_str::(&wasm_base64) + serde_json::from_str::(&wasm_base64) .wrap_err("Can't deserialize wasm using base64")?, Repeats::Indefinitely, account_id.clone(), @@ -585,7 +585,7 @@ fn unregistering_one_of_two_triggers_with_identical_wasm_should_not_cause_origin .build()? .optimize()? .into_bytes()?; - let wasm = WasmSmartContract::from_compiled(wasm); + let wasm = SmartContract::from_compiled(wasm); let build_trigger = |trigger_id: TriggerId| { Trigger::new( @@ -667,7 +667,7 @@ fn call_execute_trigger_with_args() -> Result<()> { .build()? .optimize()? .into_bytes()?; - let wasm = WasmSmartContract::from_compiled(wasm); + let wasm = SmartContract::from_compiled(wasm); let trigger = Trigger::new( trigger_id.clone(), Action::new( diff --git a/client/tests/integration/triggers/time_trigger.rs b/client/tests/integration/triggers/time_trigger.rs index c77ca97eea9..a9daa99b74a 100644 --- a/client/tests/integration/triggers/time_trigger.rs +++ b/client/tests/integration/triggers/time_trigger.rs @@ -8,7 +8,7 @@ use iroha::{ events::pipeline::{BlockEventFilter, BlockStatus}, parameter::SumeragiParameters, prelude::*, - transaction::WasmSmartContract, + transaction::SmartContract, Level, }, }; @@ -228,7 +228,7 @@ fn mint_nft_for_every_user_every_1_sec() -> Result<()> { .optimize()? .into_bytes()?; - info!("WASM size is {} bytes", wasm.len()); + info!("Smart contract size is {} bytes", wasm.len()); let (_rt, _peer, mut test_client) = ::new().with_port(10_780).start_with_runtime(); wait_for_genesis_committed(&vec![test_client.clone()], 0); @@ -265,7 +265,7 @@ fn mint_nft_for_every_user_every_1_sec() -> Result<()> { let register_trigger = Register::trigger(Trigger::new( "mint_nft_for_all".parse()?, Action::new( - WasmSmartContract::from_compiled(wasm), + SmartContract::from_compiled(wasm), Repeats::Indefinitely, alice_id.clone(), filter, diff --git a/client/tests/integration/upgrade.rs b/client/tests/integration/upgrade.rs index 6baf7396168..c19dbc98833 100644 --- a/client/tests/integration/upgrade.rs +++ b/client/tests/integration/upgrade.rs @@ -405,8 +405,7 @@ fn define_custom_parameter() -> Result<()> { let parameter = DomainLimits { id_len: 2_u32.pow(6), - } - .into(); + }; let set_param_isi = SetParameter::new(parameter); client.submit_all_blocking::([set_param_isi.into(), create_domain.into()])?; @@ -422,9 +421,9 @@ fn upgrade_executor(client: &Client, executor: impl AsRef) -> Result<()> { .optimize()? .into_bytes()?; - info!("WASM size is {} bytes", wasm.len()); + info!("Smart contract size is {} bytes", wasm.len()); - let upgrade_executor = Upgrade::new(Executor::new(WasmSmartContract::from_compiled(wasm))); + let upgrade_executor = Upgrade::executor(Executor::new(SmartContract::from_compiled(wasm))); client.submit_blocking(upgrade_executor)?; Ok(()) diff --git a/client_cli/README.md b/client_cli/README.md index 08c4494f3d2..ce24f2ba14d 100644 --- a/client_cli/README.md +++ b/client_cli/README.md @@ -38,17 +38,17 @@ iroha [OPTIONS] ### Subcommands -| Command | Description | -| --------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -| `account` | Execute commands related to accounts: register a new one, list all accounts, grant a permission to an account, list all account permissions | -| `asset` | Execute commands related to assets: register a new one, mint or transfer assets, get info about an asset, list all assets | -| `blocks` | Get block stream from Iroha peer | -| `domain` | Execute commands related to domains: register a new one, list all domains | -| `events` | Get event stream from Iroha peer | -| `json` | Submit multi-instructions or request query as JSON | -| `peer` | Execute commands related to peer administration and networking | -| `wasm` | Execute commands related to WASM | -| `help` | Print the help message for `iroha` and/or the current subcommand other than `help` subcommand | +| Command | Description | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | +| `account` | Execute commands related to accounts: register a new one, list all accounts, grant a permission to an account, list all account permissions | +| `asset` | Execute commands related to assets: register a new one, mint or transfer assets, get info about an asset, list all assets | +| `blocks` | Get block stream from Iroha peer | +| `domain` | Execute commands related to domains: register a new one, list all domains | +| `events` | Get event stream from Iroha peer | +| `json` | Submit multi-instructions or request query as JSON | +| `peer` | Execute commands related to peer administration and networking | +| `smart-contract` | Execute commands related to smart contracts | +| `help` | Print the help message for `iroha` and/or the current subcommand other than `help` subcommand | Refer to [Iroha Special Instructions](https://hyperledger.github.io/iroha-2-docs/guide/blockchain/instructions.html) for more information about Iroha instructions such as register, mint, grant, and so on. @@ -79,7 +79,7 @@ In this section we will show you how to use Iroha CLI Client to do the following - [Create new Account](#create-new-account) - [Mint Asset to Account](#mint-asset-to-account) - [Query Account Assets Quantity](#query-account-assets-quantity) - - [Execute WASM transaction](#execute-wasm-transaction) + - [Execute smart contract](#execute-smart-contract) - [Execute Multi-instruction Transactions](#execute-multi-instruction-transactions) ### Create new Domain @@ -160,21 +160,21 @@ Examples: ./iroha asset list filter '{"Or": [{"Identifiable": {"Contains": "#wonderland#"}}, {"And": [{"Identifiable": {"Contains": "##"}}, {"Identifiable": {"EndsWith": "@wonderland"}}]}]}' ``` -### Execute WASM transaction +### Execute smart contract -Use `--file` to specify a path to the WASM file: +Use `--file` to specify a path to the smart contract file: ```bash -./iroha wasm --file=/path/to/file.wasm +./iroha smart-contract --file=/path/to/file.wasm ``` -Or skip `--file` to read WASM from standard input: +Or skip `--file` to read smart contract from standard input: ```bash -cat /path/to/file.wasm | ./iroha wasm +cat /path/to/file.wasm | ./iroha smart-contract ``` -These subcommands submit the provided wasm binary as an `Executable` to be executed outside a trigger context. +These subcommands submit the provided smart contract binary as an `Executable` to be executed outside a trigger context. ### Execute Multi-instruction Transactions diff --git a/client_cli/src/main.rs b/client_cli/src/main.rs index b45c53ad2b6..3f72f0a0913 100644 --- a/client_cli/src/main.rs +++ b/client_cli/src/main.rs @@ -108,8 +108,8 @@ enum Subcommand { /// The subcommand related to event streaming #[clap(subcommand)] Events(events::Args), - /// The subcommand related to Wasm - Wasm(wasm::Args), + /// The subcommand related to smart contracts + SmartContract(smart_contract::Args), /// The subcommand related to block streaming Blocks(blocks::Args), /// The subcommand related to multi-instructions as Json or Json5 @@ -169,7 +169,7 @@ macro_rules! match_all { impl RunArgs for Subcommand { fn run(self, context: &mut dyn RunContext) -> Result<()> { use Subcommand::*; - match_all!((self, context), { Domain, Account, Asset, Peer, Events, Wasm, Blocks, Json }) + match_all!((self, context), { Domain, Account, Asset, Peer, Events, SmartContract, Blocks, Json }) } } @@ -1006,15 +1006,15 @@ mod peer { } } -mod wasm { +mod smart_contract { use std::{io::Read, path::PathBuf}; use super::*; - /// Subcommand for dealing with Wasm + /// Subcommand for dealing with smart contracts #[derive(Debug, clap::Args)] pub struct Args { - /// Specify a path to the Wasm file or skip this flag to read from stdin + /// Specify a path to the smart contract file or skip this flag to read from stdin #[arg(short, long)] path: Option, } @@ -1022,21 +1022,22 @@ mod wasm { impl RunArgs for Args { fn run(self, context: &mut dyn RunContext) -> Result<()> { let raw_data = if let Some(path) = self.path { - read_file(path).wrap_err("Failed to read a Wasm from the file into the buffer")? + read_file(path) + .wrap_err("Failed to read a smart contract from the file into the buffer")? } else { let mut buf = Vec::::new(); stdin() .read_to_end(&mut buf) - .wrap_err("Failed to read a Wasm from stdin into the buffer")?; + .wrap_err("Failed to read a smart contract from stdin into the buffer")?; buf }; submit( - WasmSmartContract::from_compiled(raw_data), + SmartContract::from_compiled(raw_data), Metadata::default(), context, ) - .wrap_err("Failed to submit a Wasm smart contract") + .wrap_err("Failed to submit a smart contract") } } } diff --git a/configs/swarm/executor.wasm b/configs/swarm/executor.wasm index e23238a47bb..f4c1b442a42 100644 Binary files a/configs/swarm/executor.wasm and b/configs/swarm/executor.wasm differ diff --git a/core/benches/blocks/common.rs b/core/benches/blocks/common.rs index 96c408281a5..e357ddd7098 100644 --- a/core/benches/blocks/common.rs +++ b/core/benches/blocks/common.rs @@ -208,8 +208,8 @@ pub fn build_state(rt: &tokio::runtime::Handle, account_id: &AccountId) -> State .join("../configs/swarm/executor.wasm"); let wasm = std::fs::read(&path_to_executor) .unwrap_or_else(|_| panic!("Failed to read file: {}", path_to_executor.display())); - let executor = Executor::new(WasmSmartContract::from_compiled(wasm)); - Upgrade::new(executor) + let executor = Executor::new(SmartContract::from_compiled(wasm)); + Upgrade::executor(executor) .execute(account_id, &mut state_transaction) .expect("Failed to load executor"); diff --git a/core/benches/validation.rs b/core/benches/validation.rs index 57e7b661484..23a156544cf 100644 --- a/core/benches/validation.rs +++ b/core/benches/validation.rs @@ -61,11 +61,11 @@ fn build_test_and_transient_state() -> State { let mut state_transaction = state_block.transaction(); let path_to_executor = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("../configs/swarm/executor.wasm"); - let wasm = std::fs::read(&path_to_executor) + let smart_contract = std::fs::read(&path_to_executor) .unwrap_or_else(|_| panic!("Failed to read file: {}", path_to_executor.display())); - let executor = Executor::new(WasmSmartContract::from_compiled(wasm)); + let executor = Executor::new(SmartContract::from_compiled(smart_contract)); let (authority, _authority_keypair) = gen_account_in("genesis"); - Upgrade::new(executor) + Upgrade::executor(executor) .execute(&authority, &mut state_transaction) .expect("Failed to load executor"); state_transaction.apply(); diff --git a/core/src/executor.rs b/core/src/executor.rs index 0894b290639..78602156c24 100644 --- a/core/src/executor.rs +++ b/core/src/executor.rs @@ -278,7 +278,7 @@ impl LoadedExecutor { raw_executor: data_model_executor::Executor, ) -> Result { Ok(Self { - module: wasm::load_module(engine, &raw_executor.wasm)?, + module: wasm::load_module(engine, &raw_executor.smart_contract)?, raw_executor, }) } diff --git a/core/src/smartcontracts/isi/triggers/mod.rs b/core/src/smartcontracts/isi/triggers/mod.rs index a6950a792ab..9b84e990c16 100644 --- a/core/src/smartcontracts/isi/triggers/mod.rs +++ b/core/src/smartcontracts/isi/triggers/mod.rs @@ -95,7 +95,7 @@ pub mod isi { .map_err(|e: &str| Error::Conversion(e.to_owned()))?, ), } - .map_err(|e| InvalidParameterError::Wasm(e.to_string()))?; + .map_err(|e| InvalidParameterError::SmartContract(e.to_string()))?; if !success { return Err(RepetitionError { diff --git a/core/src/smartcontracts/isi/triggers/set.rs b/core/src/smartcontracts/isi/triggers/set.rs index d7781f7acb2..7461fa51a9a 100644 --- a/core/src/smartcontracts/isi/triggers/set.rs +++ b/core/src/smartcontracts/isi/triggers/set.rs @@ -17,7 +17,7 @@ use iroha_data_model::{ isi::error::{InstructionExecutionError, MathError}, prelude::*, query::error::FindError, - transaction::WasmSmartContract, + transaction::SmartContract, }; use serde::{ de::{DeserializeSeed, MapAccess, Visitor}, @@ -45,22 +45,20 @@ use crate::{ /// Error type for [`Set`] operations. #[derive(Debug, Error, displaydoc::Display)] pub enum Error { - /// Failed to preload wasm trigger + /// Failed to preload smart contract trigger Preload(#[from] wasm::error::Error), } /// Result type for [`Set`] operations. pub type Result = core::result::Result; -/// [`WasmSmartContract`]s by [`TriggerId`]. -/// Stored together with number to count triggers with identical [`WasmSmartContract`]. -type WasmSmartContractMap = Storage, WasmSmartContractEntry>; -type WasmSmartContractMapBlock<'set> = - StorageBlock<'set, HashOf, WasmSmartContractEntry>; -type WasmSmartContractMapTransaction<'block, 'set> = - StorageTransaction<'block, 'set, HashOf, WasmSmartContractEntry>; -type WasmSmartContractMapView<'set> = - StorageView<'set, HashOf, WasmSmartContractEntry>; +/// [`SmartContract`]s by [`TriggerId`]. +/// Stored together with number to count triggers with identical [`SmartContract`]. +type SmartContractMap = Storage, SmartContractEntry>; +type SmartContractMapBlock<'set> = StorageBlock<'set, HashOf, SmartContractEntry>; +type SmartContractMapTransaction<'block, 'set> = + StorageTransaction<'block, 'set, HashOf, SmartContractEntry>; +type SmartContractMapView<'set> = StorageView<'set, HashOf, SmartContractEntry>; /// Specialized structure that maps event filters to Triggers. // NB: `Set` has custom `Serialize` and `DeserializeSeed` implementations @@ -77,12 +75,12 @@ pub struct Set { by_call_triggers: Storage>, /// Trigger ids with type of events they process ids: Storage, - /// [`WasmSmartContract`]s map by wasm blob hash. + /// [`SmartContract`]s map by smart contract blob hash. /// This map serves multiple purposes: - /// 1. Querying original wasm blob of trigger + /// 1. Querying original smart contract blob of trigger /// 2. Getting compiled by wasmtime module for execution - /// 3. Deduplicating triggers with the same wasm blob - contracts: WasmSmartContractMap, + /// 3. Deduplicating triggers with the same smart contract blob + contracts: SmartContractMap, /// List of actions that should be triggered by events provided by `handle_*` methods. /// Vector is used to save the exact triggers order. // NOTE: Cell is used because matched_ids changed as whole (not granularly) @@ -101,8 +99,8 @@ pub struct SetBlock<'set> { by_call_triggers: StorageBlock<'set, TriggerId, LoadedAction>, /// Trigger ids with type of events they process ids: StorageBlock<'set, TriggerId, TriggeringEventType>, - /// Original [`WasmSmartContract`]s by [`TriggerId`] for querying purposes. - contracts: WasmSmartContractMapBlock<'set>, + /// Original [`SmartContract`]s by [`TriggerId`] for querying purposes. + contracts: SmartContractMapBlock<'set>, /// List of actions that should be triggered by events provided by `handle_*` methods. /// Vector is used to save the exact triggers order. matched_ids: CellBlock<'set, Vec<(EventBox, TriggerId)>>, @@ -122,8 +120,8 @@ pub struct SetTransaction<'block, 'set> { StorageTransaction<'block, 'set, TriggerId, LoadedAction>, /// Trigger ids with type of events they process ids: StorageTransaction<'block, 'set, TriggerId, TriggeringEventType>, - /// Original [`WasmSmartContract`]s by [`TriggerId`] for querying purposes. - contracts: WasmSmartContractMapTransaction<'block, 'set>, + /// Original [`SmartContract`]s by [`TriggerId`] for querying purposes. + contracts: SmartContractMapTransaction<'block, 'set>, /// List of actions that should be triggered by events provided by `handle_*` methods. /// Vector is used to save the exact triggers order. matched_ids: CellTransaction<'block, 'set, Vec<(EventBox, TriggerId)>>, @@ -141,18 +139,18 @@ pub struct SetView<'set> { by_call_triggers: StorageView<'set, TriggerId, LoadedAction>, /// Trigger ids with type of events they process ids: StorageView<'set, TriggerId, TriggeringEventType>, - /// Original [`WasmSmartContract`]s by [`TriggerId`] for querying purposes. - contracts: WasmSmartContractMapView<'set>, + /// Original [`SmartContract`]s by [`TriggerId`] for querying purposes. + contracts: SmartContractMapView<'set>, /// List of actions that should be triggered by events provided by `handle_*` methods. /// Vector is used to save the exact triggers order. matched_ids: CellView<'set, Vec<(EventBox, TriggerId)>>, } -/// Entry in wasm smart-contracts map +/// Entry in smart-contracts map #[derive(Debug, Clone, Serialize)] -pub struct WasmSmartContractEntry { - /// Original wasm binary blob - original_contract: WasmSmartContract, +pub struct SmartContractEntry { + /// Original smart contract binary blob + original_contract: SmartContract, /// Compiled with [`wasmtime`] smart-contract #[serde(skip)] compiled_contract: wasmtime::Module, @@ -210,7 +208,7 @@ impl<'de> DeserializeSeed<'de> for WasmSeed<'_, Set> { contracts = Some(map.next_value_seed(storage::serde::StorageSeeded { kseed: PhantomData, - vseed: self.loader.cast::(), + vseed: self.loader.cast::(), })?); } "matched_ids" => { @@ -242,22 +240,22 @@ impl<'de> DeserializeSeed<'de> for WasmSeed<'_, Set> { } } -impl<'de> DeserializeSeed<'de> for WasmSeed<'_, WasmSmartContractEntry> { - type Value = WasmSmartContractEntry; +impl<'de> DeserializeSeed<'de> for WasmSeed<'_, SmartContractEntry> { + type Value = SmartContractEntry; fn deserialize(self, deserializer: D) -> Result where D: serde::Deserializer<'de>, { - struct WasmSmartContractEntryVisitor<'e> { - loader: WasmSeed<'e, WasmSmartContractEntry>, + struct SmartContractEntryVisitor<'e> { + loader: WasmSeed<'e, SmartContractEntry>, } - impl<'de> Visitor<'de> for WasmSmartContractEntryVisitor<'_> { - type Value = WasmSmartContractEntry; + impl<'de> Visitor<'de> for SmartContractEntryVisitor<'_> { + type Value = SmartContractEntry; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - formatter.write_str("struct WasmSmartContractEntry") + formatter.write_str("struct SmartContractEntry") } fn visit_map(self, mut map: M) -> Result @@ -285,7 +283,7 @@ impl<'de> DeserializeSeed<'de> for WasmSeed<'_, WasmSmartContractEntry> { let compiled_contract = wasm::load_module(self.loader.engine, &original_contract) .map_err(serde::de::Error::custom)?; - Ok(WasmSmartContractEntry { + Ok(SmartContractEntry { original_contract, compiled_contract, count, @@ -293,7 +291,7 @@ impl<'de> DeserializeSeed<'de> for WasmSeed<'_, WasmSmartContractEntry> { } } - deserializer.deserialize_map(WasmSmartContractEntryVisitor { loader: self }) + deserializer.deserialize_map(SmartContractEntryVisitor { loader: self }) } } /// Trait to perform read-only operations on [`WorldBlock`], [`WorldTransaction`] and [`WorldView`] @@ -308,18 +306,14 @@ pub trait SetReadOnly { &self, ) -> &impl StorageReadOnly>; fn ids(&self) -> &impl StorageReadOnly; - fn contracts(&self) - -> &impl StorageReadOnly, WasmSmartContractEntry>; + fn contracts(&self) -> &impl StorageReadOnly, SmartContractEntry>; fn matched_ids(&self) -> &[(EventBox, TriggerId)]; - /// Get original [`WasmSmartContract`] for [`TriggerId`]. + /// Get original [`SmartContract`] for [`TriggerId`]. /// Returns `None` if there's no [`Trigger`] - /// with specified `id` that has WASM executable + /// with specified `id` that has smart contract executable #[inline] - fn get_original_contract( - &self, - hash: &HashOf, - ) -> Option<&WasmSmartContract> { + fn get_original_contract(&self, hash: &HashOf) -> Option<&SmartContract> { self.contracts() .get(hash) .map(|entry| &entry.original_contract) @@ -327,16 +321,16 @@ pub trait SetReadOnly { /// Get compiled [`wasmtime::Module`] for [`TriggerId`]. /// Returns `None` if there's no [`Trigger`] - /// with specified `id` that has WASM executable + /// with specified `id` that has smart contract executable #[inline] - fn get_compiled_contract(&self, hash: &HashOf) -> Option<&wasmtime::Module> { + fn get_compiled_contract(&self, hash: &HashOf) -> Option<&wasmtime::Module> { self.contracts() .get(hash) .map(|entry| &entry.compiled_contract) } /// Convert [`LoadedAction`] to original [`Action`] by retrieving original - /// [`WasmSmartContract`] if applicable + /// [`SmartContract`] if applicable fn get_original_action(&self, action: LoadedAction) -> SpecializedAction { let LoadedAction { executable, @@ -347,12 +341,12 @@ pub trait SetReadOnly { } = action; let original_executable = match executable { - ExecutableRef::Wasm(ref blob_hash) => { - let original_wasm = self + ExecutableRef::SmartContract(ref blob_hash) => { + let original_smart_contract = self .get_original_contract(blob_hash) .cloned() .expect("No original smartcontract saved for trigger. This is a bug."); - Executable::Wasm(original_wasm) + Executable::SmartContract(original_smart_contract) } ExecutableRef::Instructions(isi) => Executable::Instructions(isi), }; @@ -502,7 +496,7 @@ macro_rules! impl_set_ro { fn ids(&self) -> &impl StorageReadOnly { &self.ids } - fn contracts(&self) -> &impl StorageReadOnly, WasmSmartContractEntry> { + fn contracts(&self) -> &impl StorageReadOnly, SmartContractEntry> { &self.contracts } fn matched_ids(&self) -> &[(EventBox, TriggerId)] { @@ -631,7 +625,7 @@ impl<'block, 'set> SetTransaction<'block, 'set> { /// /// # Errors /// - /// Return [`Err`] if failed to preload wasm trigger + /// Return [`Err`] if failed to preload trigger #[inline] pub fn add_data_trigger( &mut self, @@ -649,7 +643,7 @@ impl<'block, 'set> SetTransaction<'block, 'set> { /// /// # Errors /// - /// Return [`Err`] if failed to preload wasm trigger + /// Return [`Err`] if failed to preload trigger #[inline] pub fn add_pipeline_trigger( &mut self, @@ -667,7 +661,7 @@ impl<'block, 'set> SetTransaction<'block, 'set> { /// /// # Errors /// - /// Return [`Err`] if failed to preload wasm trigger + /// Return [`Err`] if failed to preload trigger #[inline] pub fn add_time_trigger( &mut self, @@ -685,7 +679,7 @@ impl<'block, 'set> SetTransaction<'block, 'set> { /// /// # Errors /// - /// Return [`Err`] if failed to preload wasm trigger + /// Return [`Err`] if failed to preload trigger #[inline] pub fn add_by_call_trigger( &mut self, @@ -703,7 +697,7 @@ impl<'block, 'set> SetTransaction<'block, 'set> { /// /// # Errors /// - /// Return [`Err`] if failed to preload wasm trigger + /// Return [`Err`] if failed to preload trigger fn add_to( &mut self, engine: &wasmtime::Engine, @@ -728,10 +722,10 @@ impl<'block, 'set> SetTransaction<'block, 'set> { } let loaded_executable = match executable { - Executable::Wasm(bytes) => { + Executable::SmartContract(bytes) => { let hash = HashOf::new(&bytes); // Store original executable representation to respond to queries with. - if let Some(WasmSmartContractEntry { count, .. }) = self.contracts.get_mut(&hash) { + if let Some(SmartContractEntry { count, .. }) = self.contracts.get_mut(&hash) { // Considering 1 trigger registration takes 1 second, // it would take 584 942 417 355 years to overflow. *count = count.checked_add(1).expect( @@ -742,14 +736,14 @@ impl<'block, 'set> SetTransaction<'block, 'set> { let module = wasm::load_module(engine, &bytes)?; self.contracts.insert( hash, - WasmSmartContractEntry { + SmartContractEntry { original_contract: bytes, compiled_contract: module, count: NonZeroU64::MIN, }, ); }; - ExecutableRef::Wasm(hash) + ExecutableRef::SmartContract(hash) } Executable::Instructions(instructions) => ExecutableRef::Instructions(instructions), }; @@ -861,13 +855,13 @@ impl<'block, 'set> SetTransaction<'block, 'set> { .and_then(std::convert::identity) } - /// Remove trigger from `triggers` and decrease the counter of the original [`WasmSmartContract`]. + /// Remove trigger from `triggers` and decrease the counter of the original [`SmartContract`]. /// /// Note that this function doesn't remove the trigger from [`Set::ids`]. /// /// Returns `true` if trigger was removed and `false` otherwise. fn remove_from( - contracts: &mut WasmSmartContractMapTransaction<'block, 'set>, + contracts: &mut SmartContractMapTransaction<'block, 'set>, triggers: &mut StorageTransaction<'block, 'set, TriggerId, LoadedAction>, trigger_id: TriggerId, ) -> bool { @@ -881,15 +875,15 @@ impl<'block, 'set> SetTransaction<'block, 'set> { .is_some() } - /// Decrease the counter of the original [`WasmSmartContract`] by `blob_hash` + /// Decrease the counter of the original [`SmartContract`] by `blob_hash` /// or remove it if the counter reaches zero. /// /// # Panics /// /// Panics if `blob_hash` is not in the [`Set::contracts`]. fn remove_original_trigger( - contracts: &mut WasmSmartContractMapTransaction, - blob_hash: HashOf, + contracts: &mut SmartContractMapTransaction, + blob_hash: HashOf, ) { #[allow(clippy::option_if_let_else)] // More readable this way match contracts.get_mut(&blob_hash) { @@ -932,7 +926,7 @@ impl<'block, 'set> SetTransaction<'block, 'set> { /// Remove actions with zero execution count from `triggers` fn remove_zeros( ids: &mut StorageTransaction<'block, 'set, TriggerId, TriggeringEventType>, - contracts: &mut WasmSmartContractMapTransaction<'block, 'set>, + contracts: &mut SmartContractMapTransaction<'block, 'set>, triggers: &mut StorageTransaction<'block, 'set, TriggerId, LoadedAction>, ) { let to_remove: Vec = triggers @@ -1000,12 +994,12 @@ impl<'block, 'set> SetTransaction<'block, 'set> { } /// Same as [`Executable`](iroha_data_model::transaction::Executable), but instead of -/// [`Wasm`](iroha_data_model::transaction::Executable::Wasm) contains hash of the WASM blob +/// [`SmartContract`](iroha_data_model::transaction::Executable::SmartContract) contains hash of the smart contract blob /// Which can be used to obtain compiled by `wasmtime` module #[derive(Clone, Serialize, Deserialize)] pub enum ExecutableRef { - /// Loaded WASM - Wasm(HashOf), + /// Loaded smart contract + SmartContract(HashOf), /// Vector of ISI Instructions(Vec), } @@ -1013,7 +1007,7 @@ pub enum ExecutableRef { impl core::fmt::Debug for ExecutableRef { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Wasm(hash) => f.debug_tuple("Wasm").field(hash).finish(), + Self::SmartContract(hash) => f.debug_tuple("smart contract").field(hash).finish(), Self::Instructions(instructions) => { f.debug_tuple("Instructions").field(instructions).finish() } diff --git a/core/src/smartcontracts/isi/triggers/specialized.rs b/core/src/smartcontracts/isi/triggers/specialized.rs index a3deafa5d83..9ff5d7a3ed6 100644 --- a/core/src/smartcontracts/isi/triggers/specialized.rs +++ b/core/src/smartcontracts/isi/triggers/specialized.rs @@ -127,9 +127,9 @@ pub struct LoadedAction { } impl LoadedAction { - pub(super) fn extract_blob_hash(&self) -> Option> { + pub(super) fn extract_blob_hash(&self) -> Option> { match self.executable { - ExecutableRef::Wasm(blob_hash) => Some(blob_hash), + ExecutableRef::SmartContract(blob_hash) => Some(blob_hash), ExecutableRef::Instructions(_) => None, } } diff --git a/core/src/smartcontracts/isi/world.rs b/core/src/smartcontracts/isi/world.rs index bb348f84475..7859184dc9b 100644 --- a/core/src/smartcontracts/isi/world.rs +++ b/core/src/smartcontracts/isi/world.rs @@ -402,7 +402,7 @@ pub mod isi { authority: &AccountId, state_transaction: &mut StateTransaction<'_, '_>, ) -> Result<(), Error> { - let raw_executor = self.executor; + let raw_executor = self.object; // Cloning executor to avoid multiple mutable borrows of `state_transaction`. // Also it's a cheap operation. @@ -410,7 +410,7 @@ pub mod isi { upgraded_executor .migrate(raw_executor, state_transaction, authority) .map_err(|migration_error| { - InvalidParameterError::Wasm(format!( + InvalidParameterError::SmartContract(format!( "{:?}", eyre::eyre!(migration_error).wrap_err("Migration failed"), )) diff --git a/core/src/smartcontracts/wasm.rs b/core/src/smartcontracts/wasm.rs index 215d6d9a40b..04a23135665 100644 --- a/core/src/smartcontracts/wasm.rs +++ b/core/src/smartcontracts/wasm.rs @@ -713,7 +713,7 @@ impl Runtime> { (log_level, msg): (u8, String), state: &state::CommonState, ) -> Result<(), WasmtimeError> { - const TARGET: &str = "WASM"; + const TARGET: &str = "Smart contract"; let _span = state.log_span.enter(); match LogLevel::from_repr(log_level) @@ -745,7 +745,7 @@ impl Runtime> { store.limiter(|s| &mut s.store_limits); store .set_fuel(self.config.fuel.get()) - .expect("Wasm Runtime config is malformed, this is a bug"); + .expect("INTERNAL BUG: Smart contract config is malformed"); store } diff --git a/core/src/state.rs b/core/src/state.rs index 17aa9bd762f..bc1ec11c6ec 100644 --- a/core/src/state.rs +++ b/core/src/state.rs @@ -1448,7 +1448,7 @@ impl StateTransaction<'_, '_> { Executable::Instructions(instructions) => { self.process_instructions(instructions.iter().cloned(), &authority) } - Executable::Wasm(bytes) => { + Executable::SmartContract(bytes) => { let mut wasm_runtime = wasm::RuntimeBuilder::::new() .with_config(self.world().parameters().smart_contract) .with_engine(self.engine.clone()) // Cloning engine is cheap @@ -1484,7 +1484,7 @@ impl StateTransaction<'_, '_> { Instructions(instructions) => { self.process_instructions(instructions.iter().cloned(), authority) } - Wasm(blob_hash) => { + SmartContract(blob_hash) => { let module = self .world .triggers diff --git a/core/src/tx.rs b/core/src/tx.rs index 2b841f7bba2..6f7202c7f3a 100644 --- a/core/src/tx.rs +++ b/core/src/tx.rs @@ -134,7 +134,7 @@ impl AcceptedTransaction { // when executing wasm where we deny wasm if number of instructions exceeds the limit. // // Should we allow infinite instructions in wasm? And deny only based on fuel and size - Executable::Wasm(smart_contract) => { + Executable::SmartContract(smart_contract) => { let smart_contract_size_limit = limits .smart_contract_size .get() @@ -145,7 +145,7 @@ impl AcceptedTransaction { return Err(AcceptTransactionFail::TransactionLimit( TransactionLimitError { reason: format!( - "WASM binary size is too large: max {}, got {} \ + "Smart contract binary size is too large: max {}, got {} \ (configured by \"Parameter::SmartContractLimits\")", limits.smart_contract_size, smart_contract.size_bytes() @@ -232,21 +232,21 @@ impl TransactionExecutor { debug!("Validating transaction: {:?}", tx); Self::validate_with_runtime_executor(tx.clone(), state_transaction)?; - if let (authority, Executable::Wasm(bytes)) = tx.into() { - self.validate_wasm(authority, state_transaction, bytes)? + if let (authority, Executable::SmartContract(bytes)) = tx.into() { + self.validate_smart_contract(authority, state_transaction, bytes)? } debug!("Validation successful"); Ok(()) } - fn validate_wasm( + fn validate_smart_contract( &self, authority: AccountId, state_transaction: &mut StateTransaction<'_, '_>, - wasm: WasmSmartContract, + smart_contract: SmartContract, ) -> Result<(), TransactionRejectionReason> { - debug!("Validating wasm"); + debug!("Validating smart contract"); wasm::RuntimeBuilder::::new() .build() @@ -254,14 +254,14 @@ impl TransactionExecutor { wasm_runtime.validate( state_transaction, authority, - wasm, + smart_contract, self.limits.max_instructions, ) }) - .map_err(|error| WasmExecutionFail { + .map_err(|error| SmartContractExecutionFail { reason: format!("{:?}", eyre::Report::from(error)), }) - .map_err(TransactionRejectionReason::WasmExecution) + .map_err(TransactionRejectionReason::SmartContractExecution) } /// Validate transaction with runtime executors. diff --git a/data_model/src/executor.rs b/data_model/src/executor.rs index f03775cbe50..a4e1b36ac22 100644 --- a/data_model/src/executor.rs +++ b/data_model/src/executor.rs @@ -10,7 +10,7 @@ use iroha_primitives::json::JsonString; use iroha_schema::{Ident, IntoSchema}; pub use self::model::*; -use crate::transaction::WasmSmartContract; +use crate::transaction::SmartContract; #[model] mod model { @@ -48,8 +48,8 @@ mod model { // TODO: Derive with getset once FFI impl is fixed //#[getset(get = "pub")] pub struct Executor { - /// WASM code of the executor - pub wasm: WasmSmartContract, + /// Smart contract code of the executor + pub smart_contract: SmartContract, } /// Executor data model. diff --git a/data_model/src/isi.rs b/data_model/src/isi.rs index 60d6f2772ca..79a5e05ce75 100644 --- a/data_model/src/isi.rs +++ b/data_model/src/isi.rs @@ -252,7 +252,7 @@ mod transparent { iroha_data_model_derive::model_single! { /// Generic instruction for setting a chain-wide config parameter. - #[derive(Debug, Display, Clone, PartialEq, Eq, PartialOrd, Ord, Constructor)] + #[derive(Debug, Display, Clone, PartialEq, Eq, PartialOrd, Ord)] #[derive(parity_scale_codec::Decode, parity_scale_codec::Encode)] #[derive(serde::Deserialize, serde::Serialize)] #[derive(iroha_schema::IntoSchema)] @@ -262,6 +262,13 @@ mod transparent { pub struct SetParameter(pub Parameter); } + impl SetParameter { + /// Construct a new [`SetParameter`] + pub fn new(parameter: impl Into) -> Self { + Self(parameter.into()) + } + } + isi! { /// Generic instruction to set key value at the object. #[schema(bounds = "O: Identifiable, O::Id: IntoSchema")] @@ -953,13 +960,20 @@ mod transparent { isi! { /// Generic instruction for upgrading runtime objects. - #[derive(Constructor, Display)] + #[derive(Display)] #[display(fmt = "UPGRADE")] #[serde(transparent)] #[repr(transparent)] pub struct Upgrade { /// Object to upgrade. - pub executor: Executor, + pub object: Executor, + } + } + + impl Upgrade { + /// Constructs a new [`Upgrade`] + pub fn executor(object: Executor) -> Self { + Self { object } } } @@ -1465,8 +1479,8 @@ pub mod error { #[ffi_type(opaque)] #[repr(u8)] pub enum InvalidParameterError { - /// Invalid WASM binary: {0} - Wasm(String), + /// Invalid smart contract binary: {0} + SmartContract(String), /// Name length violation /// /// i.e. too long [`AccountId`] diff --git a/data_model/src/lib.rs b/data_model/src/lib.rs index a86d786812b..c81153e8e53 100644 --- a/data_model/src/lib.rs +++ b/data_model/src/lib.rs @@ -18,7 +18,6 @@ use iroha_macro::FromVariant; use iroha_schema::IntoSchema; use iroha_version::{declare_versioned, version_with_scale}; use parity_scale_codec::{Decode, Encode}; -use prelude::Executable; use serde::{Deserialize, Serialize}; use strum::FromRepr; @@ -371,9 +370,9 @@ mod model { ), /// Query execution failed QueryFailed(#[cfg_attr(feature = "std", source)] query::error::QueryExecutionFail), - /// Operation is too complex, perhaps `WASM_RUNTIME_CONFIG` blockchain parameters should be increased + /// Operation is too complex, perhaps `SmartContractParameter` limits should be increased /// - /// For example it's a very big WASM binary. + /// For example it's a very big smart contract binary. /// /// It's different from [`TransactionRejectionReason::LimitCheck`] because it depends on /// executor. diff --git a/data_model/src/parameter.rs b/data_model/src/parameter.rs index afff07b46d7..4f87f232844 100644 --- a/data_model/src/parameter.rs +++ b/data_model/src/parameter.rs @@ -20,6 +20,7 @@ mod model { use derive_more::{Constructor, Display, FromStr}; use getset::{CopyGetters, Getters}; use iroha_data_model_derive::IdEqOrdHash; + use iroha_macro::FromVariant; use iroha_schema::IntoSchema; use parity_scale_codec::{Decode, Encode}; use serde::{Deserialize, Serialize}; @@ -155,7 +156,7 @@ mod model { pub struct TransactionParameters { /// Maximum number of instructions per transaction pub max_instructions: NonZeroU64, - /// Maximum size of wasm binary in bytes + /// Maximum size of smart contract binary in bytes pub smart_contract_size: NonZeroU64, } @@ -269,6 +270,7 @@ mod model { Eq, PartialOrd, Ord, + FromVariant, EnumDiscriminants, Decode, Encode, @@ -281,8 +283,16 @@ mod model { Sumeragi(SumeragiParameter), Block(BlockParameter), Transaction(TransactionParameter), - SmartContract(SmartContractParameter), - Executor(SmartContractParameter), + SmartContract( + #[skip_from] + #[skip_try_from] + SmartContractParameter, + ), + Executor( + #[skip_from] + #[skip_try_from] + SmartContractParameter, + ), Custom(CustomParameter), } } diff --git a/data_model/src/query/mod.rs b/data_model/src/query/mod.rs index 4520069e0b3..0cb00072b11 100644 --- a/data_model/src/query/mod.rs +++ b/data_model/src/query/mod.rs @@ -251,9 +251,9 @@ mod model { pub transaction: CommittedTransaction, } - /// Request type clients (like http clients or wasm) can send to a query endpoint. + /// Request type clients (like http clients or smart contract) can send to a query endpoint. /// - /// `Q` should be either [`http::SignedQuery`] for client or [`SmartContractQuery`] for wasm smart contract. + /// `Q` should be either [`http::SignedQuery`] for client or [`SmartContractQuery`] for smart contract. // NOTE: if updating, also update the `iroha_smart_contract::QueryRequest` and its encoding #[derive(Debug, Clone, Encode, Decode, Serialize, Deserialize)] pub enum QueryRequest { @@ -1034,7 +1034,7 @@ pub mod trigger { events::TriggeringEventFilterBox, prelude::InstructionBox, trigger::{Trigger, TriggerId}, - Executable, Identifiable, Name, + Identifiable, Name, }; queries! { diff --git a/data_model/src/transaction.rs b/data_model/src/transaction.rs index 19a5b97c60a..ddc4093165a 100644 --- a/data_model/src/transaction.rs +++ b/data_model/src/transaction.rs @@ -34,7 +34,7 @@ mod model { use super::*; use crate::account::AccountId; - /// Either ISI or Wasm binary + /// Either ISI or smart contract binary #[derive( DebugCustom, Clone, @@ -55,10 +55,10 @@ mod model { #[debug(fmt = "{_0:?}")] Instructions(Vec), /// WebAssembly smartcontract - Wasm(WasmSmartContract), + SmartContract(SmartContract), } - /// Wrapper for byte representation of [`Executable::Wasm`]. + /// Wrapper for byte representation of [`Executable::SmartContract`]. /// /// Uses **base64** (de-)serialization format. #[derive( @@ -74,13 +74,13 @@ mod model { Serialize, IntoSchema, )] - #[debug(fmt = "WASM binary(len = {})", "self.0.len()")] + #[debug(fmt = "Smart contract binary(len = {})", "self.0.len()")] #[serde(transparent)] #[repr(transparent)] - // SAFETY: `WasmSmartContract` has no trap representation in `Vec` + // SAFETY: `SmartContract` has no trap representation in `Vec` #[ffi_type(unsafe {robust})] - pub struct WasmSmartContract( - /// Raw wasm blob. + pub struct SmartContract( + /// Raw smart contract blob. #[serde(with = "base64")] pub(super) Vec, ); @@ -191,20 +191,20 @@ impl> From for Executable { } } -impl From for Executable { - fn from(source: WasmSmartContract) -> Self { - Self::Wasm(source) +impl From for Executable { + fn from(source: SmartContract) -> Self { + Self::SmartContract(source) } } -impl AsRef<[u8]> for WasmSmartContract { +impl AsRef<[u8]> for SmartContract { fn as_ref(&self) -> &[u8] { self.0.as_ref() } } -impl WasmSmartContract { - /// Create [`Self`] from raw wasm bytes +impl SmartContract { + /// Create [`Self`] from raw bytes #[inline] pub const fn from_compiled(blob: Vec) -> Self { Self(blob) @@ -381,7 +381,7 @@ mod candidate { mod base64 { //! Module with (de-)serialization functions for - //! [`WasmSmartContract`](super::WasmSmartContract)'s bytes using `base64`. + //! [`SmartContract`](super::SmartContract)'s bytes using `base64`. //! //! No extra heap allocation is performed nor for serialization nor for deserialization. @@ -490,12 +490,12 @@ pub mod error { Serialize, IntoSchema, )] - #[display(fmt = "Failed to execute wasm binary: {reason}")] + #[display(fmt = "Failed to execute smart contract: {reason}")] #[serde(transparent)] #[repr(transparent)] - // SAFETY: `WasmExecutionFail` has no trap representation in `String` + // SAFETY: `SmartContractExecutionFail` has no trap representation in `String` #[ffi_type(unsafe {robust})] - pub struct WasmExecutionFail { + pub struct SmartContractExecutionFail { /// Error which happened during execution pub reason: String, } @@ -540,7 +540,7 @@ pub mod error { /// and will be removed soon. InstructionExecution(#[cfg_attr(feature = "std", source)] InstructionExecutionFail), /// Failure in WebAssembly execution - WasmExecution(#[cfg_attr(feature = "std", source)] WasmExecutionFail), + SmartContractExecution(#[cfg_attr(feature = "std", source)] SmartContractExecutionFail), } } @@ -578,12 +578,14 @@ pub mod error { impl std::error::Error for InstructionExecutionFail {} #[cfg(feature = "std")] - impl std::error::Error for WasmExecutionFail {} + impl std::error::Error for SmartContractExecutionFail {} pub mod prelude { //! The prelude re-exports most commonly used traits, structs and macros from this module. - pub use super::{InstructionExecutionFail, TransactionRejectionReason, WasmExecutionFail}; + pub use super::{ + InstructionExecutionFail, SmartContractExecutionFail, TransactionRejectionReason, + }; } } @@ -671,9 +673,9 @@ mod http { self } - /// Add wasm to this transaction - pub fn with_wasm(mut self, wasm: WasmSmartContract) -> Self { - self.payload.instructions = wasm.into(); + /// Add smart contract to this transaction + pub fn with_smart_contract(mut self, smart_contract: SmartContract) -> Self { + self.payload.instructions = smart_contract.into(); self } @@ -738,7 +740,7 @@ pub mod prelude { #[cfg(feature = "http")] pub use super::http::TransactionBuilder; pub use super::{ - error::prelude::*, CommittedTransaction, Executable, SignedTransaction, WasmSmartContract, + error::prelude::*, CommittedTransaction, Executable, SignedTransaction, SmartContract, }; } @@ -751,7 +753,7 @@ mod tests { #[test] fn wasm_smart_contract_debug_repr_should_contain_just_len() { - let contract = WasmSmartContract::from_compiled(vec![0, 1, 2, 3, 4]); - assert_eq!(format!("{contract:?}"), "WASM binary(len = 5)"); + let contract = SmartContract::from_compiled(vec![0, 1, 2, 3, 4]); + assert_eq!(format!("{contract:?}"), "Smart contract binary(len = 5)"); } } diff --git a/data_model/src/visit.rs b/data_model/src/visit.rs index cc0e92764f5..66c7a4a0315 100644 --- a/data_model/src/visit.rs +++ b/data_model/src/visit.rs @@ -23,7 +23,7 @@ pub trait Visit { // Visit SignedTransaction visit_transaction(&SignedTransaction), visit_instruction(&InstructionBox), - visit_wasm(&WasmSmartContract), + visit_smart_contract(&SmartContract), visit_query(&QueryBox), // Visit InstructionBox @@ -150,7 +150,9 @@ pub fn visit_transaction( transaction: &SignedTransaction, ) { match transaction.instructions() { - Executable::Wasm(wasm) => visitor.visit_wasm(authority, wasm), + Executable::SmartContract(smart_contract) => { + visitor.visit_smart_contract(authority, smart_contract) + } Executable::Instructions(instructions) => { for isi in instructions { visitor.visit_instruction(authority, isi); @@ -213,10 +215,10 @@ pub fn visit_query(visitor: &mut V, authority: &AccountId, qu } } -pub fn visit_wasm( +pub fn visit_smart_contract( _visitor: &mut V, _authority: &AccountId, - _wasm: &WasmSmartContract, + _smart_contract: &SmartContract, ) { } diff --git a/docs/source/references/schema.json b/docs/source/references/schema.json index 65ed5f1a562..cb1a7d8c9a1 100644 --- a/docs/source/references/schema.json +++ b/docs/source/references/schema.json @@ -1356,9 +1356,9 @@ "type": "Vec" }, { - "tag": "Wasm", + "tag": "SmartContract", "discriminant": 1, - "type": "WasmSmartContract" + "type": "SmartContract" } ] }, @@ -1418,8 +1418,8 @@ "Executor": { "Struct": [ { - "name": "wasm", - "type": "WasmSmartContract" + "name": "smart_contract", + "type": "SmartContract" } ] }, @@ -2229,7 +2229,7 @@ "InvalidParameterError": { "Enum": [ { - "tag": "Wasm", + "tag": "SmartContract", "discriminant": 0, "type": "String" }, @@ -3761,6 +3761,15 @@ } ] }, + "SmartContract": "Vec", + "SmartContractExecutionFail": { + "Struct": [ + { + "name": "reason", + "type": "String" + } + ] + }, "SmartContractParameter": { "Enum": [ { @@ -4077,9 +4086,9 @@ "type": "InstructionExecutionFail" }, { - "tag": "WasmExecution", + "tag": "SmartContractExecution", "discriminant": 4, - "type": "WasmExecutionFail" + "type": "SmartContractExecutionFail" } ] }, @@ -4482,7 +4491,7 @@ "Upgrade": { "Struct": [ { - "name": "executor", + "name": "object", "type": "Executor" } ] @@ -4544,15 +4553,6 @@ "Vec": { "Vec": "u8" }, - "WasmExecutionFail": { - "Struct": [ - { - "name": "reason", - "type": "String" - } - ] - }, - "WasmSmartContract": "Vec", "u128": { "Int": "FixedWidth" }, diff --git a/genesis/src/lib.rs b/genesis/src/lib.rs index 078ba4bc2f1..99019ee46e5 100644 --- a/genesis/src/lib.rs +++ b/genesis/src/lib.rs @@ -140,7 +140,7 @@ fn build_transactions( chain_id: ChainId, genesis_key_pair: &KeyPair, ) -> Vec { - let upgrade_isi = Upgrade::new(executor).into(); + let upgrade_isi = Upgrade::executor(executor).into(); let transaction_executor = build_transaction(vec![upgrade_isi], chain_id.clone(), genesis_key_pair); let mut transactions = vec![transaction_executor]; @@ -180,7 +180,7 @@ fn build_transaction( fn get_executor(file: &Path) -> Result { let wasm = fs::read(file) .wrap_err_with(|| eyre!("failed to read the executor from {}", file.display()))?; - Ok(Executor::new(WasmSmartContract::from_compiled(wasm))) + Ok(Executor::new(SmartContract::from_compiled(wasm))) } /// Builder type for [`GenesisBlock`]/[`RawGenesisTransaction`] @@ -331,7 +331,7 @@ mod tests { use super::*; fn dummy_executor() -> Executor { - Executor::new(WasmSmartContract::from_compiled(vec![1, 2, 3])) + Executor::new(SmartContract::from_compiled(vec![1, 2, 3])) } #[test] @@ -395,7 +395,7 @@ mod tests { panic!("Expected instructions"); }; - assert_eq!(instructions[0], Upgrade::new(dummy_executor()).into()); + assert_eq!(instructions[0], Upgrade::executor(dummy_executor()).into()); assert_eq!(instructions.len(), 1); } diff --git a/schema/gen/src/lib.rs b/schema/gen/src/lib.rs index 0b8fb381f22..df3aa05be95 100644 --- a/schema/gen/src/lib.rs +++ b/schema/gen/src/lib.rs @@ -364,6 +364,8 @@ types!( SignedQueryV1, SignedTransaction, SignedTransactionV1, + SmartContract, + SmartContractExecutionFail, SmartContractParameter, SmartContractParameters, SocketAddr, @@ -425,8 +427,6 @@ types!( Vec, Vec, Vec, - WasmExecutionFail, - WasmSmartContract, [u16; 8], [u8; 32], [u8; 4], diff --git a/smart_contract/README.md b/smart_contract/README.md index 5231e044444..e5e8e6a9ecb 100644 --- a/smart_contract/README.md +++ b/smart_contract/README.md @@ -1,10 +1,10 @@ -# Iroha WASM +# Iroha Smart Contract The library crate that is used for writing Iroha-compliant smart contracts in Rust using the WebAssembly format. ## Usage -Check the [WASM section of our tutorial](https://hyperledger.github.io/iroha-2-docs/guide/blockchain/wasm.html) for a detailed guide. +Check the [Smart Contract section of our tutorial](https://hyperledger.github.io/iroha-2-docs/guide/blockchain/smart_contract.html) for a detailed guide. ## Running tests @@ -20,7 +20,7 @@ Then run tests: cargo test ``` -## Reducing the size of WASM +## Reducing the size of smart contracts Since smart contracts are stored directly on the blockchain, you would want to reduce their size. By following this list of optimization steps you can reduce the size of your binary by an order of magnitude @@ -67,5 +67,5 @@ By following this list of optimization steps you can reduce the size of your bin $ wasm-opt -Os -o output.wasm input.wasm ``` -Following these steps is the bare minimum that can be done to all WASM smart contracts. +Following these steps is the bare minimum that can be done to all smart contracts. We encourage you to profile the binaries [using twiggy](https://rustwasm.github.io/twiggy/) to further reduce their size. diff --git a/smart_contract/derive/src/entrypoint.rs b/smart_contract/derive/src/entrypoint.rs index 081651fc878..e0e3d6dc8ae 100644 --- a/smart_contract/derive/src/entrypoint.rs +++ b/smart_contract/derive/src/entrypoint.rs @@ -50,7 +50,7 @@ pub fn impl_entrypoint(emitter: &mut Emitter, item: syn::ItemFn) -> TokenStream #fn_name(payload.owner) } - // NOTE: Host objects are always passed by value to wasm + // NOTE: Host objects are always passed by value to the smart contract #[allow(clippy::needless_pass_by_value)] #(#attrs)* #[inline] diff --git a/smart_contract/executor/data_model/derive/src/parameter.rs b/smart_contract/executor/data_model/derive/src/parameter.rs index e98e4abbf25..3baf2082ff5 100644 --- a/smart_contract/executor/data_model/derive/src/parameter.rs +++ b/smart_contract/executor/data_model/derive/src/parameter.rs @@ -12,10 +12,10 @@ pub fn impl_derive_parameter(input: &syn::DeriveInput) -> TokenStream { quote! { impl #impl_generics ::iroha_executor_data_model::parameter::Parameter for #ident #ty_generics #where_clause {} - impl #impl_generics TryFrom<&::iroha_executor_data_model::parameter::CustomParameter> for #ident #ty_generics #where_clause { + impl #impl_generics TryFrom<&::iroha_data_model::parameter::CustomParameter> for #ident #ty_generics #where_clause { type Error = ::iroha_executor_data_model::TryFromDataModelObjectError; - fn try_from(value: &::iroha_executor_data_model::parameter::CustomParameter) -> core::result::Result { + fn try_from(value: &::iroha_data_model::parameter::CustomParameter) -> core::result::Result { let value_id = iroha_data_model::Identifiable::id(value); if *value_id != ::id() { @@ -26,9 +26,9 @@ pub fn impl_derive_parameter(input: &syn::DeriveInput) -> TokenStream { } } - impl #impl_generics From<#ident #ty_generics> for ::iroha_executor_data_model::parameter::CustomParameter #where_clause { + impl #impl_generics From<#ident #ty_generics> for ::iroha_data_model::parameter::CustomParameter #where_clause { fn from(value: #ident #ty_generics) -> Self { - ::iroha_executor_data_model::parameter::CustomParameter::new( + ::iroha_data_model::parameter::CustomParameter::new( <#ident as ::iroha_executor_data_model::parameter::Parameter>::id(), ::serde_json::to_value::<#ident #ty_generics>(value) .expect("INTERNAL BUG: Failed to serialize Executor data model entity"), diff --git a/smart_contract/executor/data_model/src/parameter.rs b/smart_contract/executor/data_model/src/parameter.rs index 9756548efb7..c838e4533cc 100644 --- a/smart_contract/executor/data_model/src/parameter.rs +++ b/smart_contract/executor/data_model/src/parameter.rs @@ -1,6 +1,5 @@ //! Module with parameter related functionality. -pub use iroha_data_model::parameter::CustomParameter; use iroha_data_model::parameter::CustomParameterId; pub use iroha_executor_data_model_derive::Parameter; use iroha_schema::IntoSchema; diff --git a/smart_contract/executor/derive/src/entrypoint.rs b/smart_contract/executor/derive/src/entrypoint.rs index e546eb69809..5f5a4e75ebe 100644 --- a/smart_contract/executor/derive/src/entrypoint.rs +++ b/smart_contract/executor/derive/src/entrypoint.rs @@ -119,7 +119,7 @@ fn impl_validate_entrypoint( bytes_box.as_ptr() } - // NOTE: Host objects are always passed by value to wasm + // NOTE: Host objects are always passed by value to the smart contract #[allow(clippy::needless_pass_by_value)] #(#attrs)* #[inline] diff --git a/smart_contract/executor/src/default.rs b/smart_contract/executor/src/default.rs index 4e01bc24c00..08ec075545a 100644 --- a/smart_contract/executor/src/default.rs +++ b/smart_contract/executor/src/default.rs @@ -54,14 +54,16 @@ use crate::{ /// # Warning /// /// Each instruction is executed in sequence following successful validation. -/// [`Executable::Wasm`] is not executed because it is validated on the host side. +/// [`Executable::SmartContract`] is not executed because it is validated on the host side. pub fn visit_transaction( executor: &mut V, authority: &AccountId, transaction: &SignedTransaction, ) { match transaction.instructions() { - Executable::Wasm(wasm) => executor.visit_wasm(authority, wasm), + Executable::SmartContract(smart_contract) => { + executor.visit_smart_contract(authority, smart_contract) + } Executable::Instructions(instructions) => { for isi in instructions { if executor.verdict().is_ok() { diff --git a/smart_contract/executor/src/lib.rs b/smart_contract/executor/src/lib.rs index a280572cdf9..6a44359825a 100644 --- a/smart_contract/executor/src/lib.rs +++ b/smart_contract/executor/src/lib.rs @@ -26,7 +26,7 @@ pub mod utils { } pub mod log { - //! WASM logging utilities + //! Smart contract logging utilities pub use iroha_smart_contract_utils::{debug, error, event, info, log::*, trace, warn}; } diff --git a/smart_contract/src/lib.rs b/smart_contract/src/lib.rs index ee6e2ac2c0f..002ea906680 100644 --- a/smart_contract/src/lib.rs +++ b/smart_contract/src/lib.rs @@ -37,7 +37,7 @@ extern "C" fn _iroha_smart_contract_alloc(len: usize) -> *const u8 { } /// # Safety -/// - `offset` is a pointer to a `[u8; len]` which is allocated in the WASM memory. +/// - `offset` is a pointer to a `[u8; len]` which is allocated in the smart contract memory. /// - This function can't call destructor of the encoded object. #[no_mangle] unsafe extern "C" fn _iroha_smart_contract_dealloc(offset: *mut u8, len: usize) { diff --git a/smart_contract/trigger/derive/src/entrypoint.rs b/smart_contract/trigger/derive/src/entrypoint.rs index 29723cd3511..a4ac32f2d47 100644 --- a/smart_contract/trigger/derive/src/entrypoint.rs +++ b/smart_contract/trigger/derive/src/entrypoint.rs @@ -50,7 +50,7 @@ pub fn impl_entrypoint(emitter: &mut Emitter, item: syn::ItemFn) -> TokenStream #fn_name(payload.id, payload.owner, payload.event) } - // NOTE: Host objects are always passed by value to wasm + // NOTE: Host objects are always passed by value to the smart contract #[allow(clippy::needless_pass_by_value)] #(#attrs)* #[inline] diff --git a/smart_contract/trigger/src/lib.rs b/smart_contract/trigger/src/lib.rs index 413f6f2be77..e31d790207f 100644 --- a/smart_contract/trigger/src/lib.rs +++ b/smart_contract/trigger/src/lib.rs @@ -12,7 +12,7 @@ pub use iroha_trigger_derive::main; pub use smart_contract::{data_model, stub_getrandom}; pub mod log { - //! WASM logging utilities + //! Smart contract logging utilities pub use iroha_smart_contract_utils::{debug, error, event, info, log::*, trace, warn}; } diff --git a/smart_contract/utils/src/debug.rs b/smart_contract/utils/src/debug.rs index ef1780accd3..d06fc602c3a 100644 --- a/smart_contract/utils/src/debug.rs +++ b/smart_contract/utils/src/debug.rs @@ -1,4 +1,4 @@ -//! WASM debugging utilities +//! Smart contract debugging utilities #[cfg(feature = "debug")] use alloc::format; @@ -25,10 +25,10 @@ mod host { /// Print `obj` in debug representation. /// -/// When running as a wasm smart contract, prints to host's stdout. -/// Does nothing unless `debug` feature is enabled. +/// When running on a smart contract VM, prints to the host logging system. +/// Otherwise, prints the output along with its level to stderr /// -/// When running outside of wasm, always prints the output to stderr +/// Does nothing unless `debug` feature is enabled. #[allow(unused_variables)] pub fn dbg(obj: &T) { cfg_if! { @@ -85,7 +85,7 @@ impl DebugUnwrapExt for Result { Ok(out) => out, Err(err) => { dbg(&format!( - "WASM execution panicked at `called Result::dbg_unwrap()` on an `Err` value: {err:?}", + "Smart contract panicked at `called Result::dbg_unwrap()` on an `Err` value: {err:?}", )); panic!(""); } @@ -107,7 +107,7 @@ impl DebugUnwrapExt for Option { match self { Some(out) => out, None => { - dbg("WASM execution panicked at 'called `Option::dbg_unwrap()` on a `None` value'"); + dbg("Smart contract panicked at 'called `Option::dbg_unwrap()` on a `None` value'"); panic!(""); } } @@ -140,7 +140,7 @@ impl DebugExpectExt for Result { match self { Ok(out) => out, Err(err) => { - dbg(&format!("WASM execution panicked at `{msg}: {err:?}`",)); + dbg(&format!("Smart contract panicked at `{msg}: {err:?}`",)); panic!(""); } } @@ -161,7 +161,7 @@ impl DebugExpectExt for Option { match self { Some(out) => out, None => { - dbg(&format!("WASM execution panicked at `{msg}`",)); + dbg(&format!("Smart contract panicked at `{msg}`",)); panic!(""); } } diff --git a/smart_contract/utils/src/lib.rs b/smart_contract/utils/src/lib.rs index 971177c09fe..c76015130ae 100644 --- a/smart_contract/utils/src/lib.rs +++ b/smart_contract/utils/src/lib.rs @@ -1,6 +1,7 @@ //! Crate with utilities for implementing smart contract FFI -// do not use `no_std` when not running in wasm -// this is useful to implement `dbg` and `log` functions for host-side tests + +// not using `no_std` when not running outside of wasm so that +// `dbg` and `log` functions work for host-side tests #![cfg_attr(target_family = "wasm", no_std)] #![allow(unsafe_code)] diff --git a/smart_contract/utils/src/log.rs b/smart_contract/utils/src/log.rs index d42255aee72..b2ab6760f60 100644 --- a/smart_contract/utils/src/log.rs +++ b/smart_contract/utils/src/log.rs @@ -1,4 +1,4 @@ -//! WASM logging utilities +//! Smart contract logging utilities use cfg_if::cfg_if; pub use iroha_data_model::Level; @@ -21,10 +21,8 @@ mod host { /// Log `obj` with desired log level /// -/// When running as a wasm smart contract, -/// prints to the host logging system with the corresponding level. -/// -/// When running outside of wasm, prints the output along with its level to stderr +/// When running on a smart contract VM, prints to the host logging system. +/// Otherwise, prints the output along with its level to stderr pub fn log(log_level: Level, obj: &T) { cfg_if! { if #[cfg(not(target_family = "wasm"))] {