From ba15f037f7f5d8dc4cca1f8e3ee65154d1c2c3e0 Mon Sep 17 00:00:00 2001 From: Arsenii Lyashenko Date: Tue, 20 Jun 2023 22:00:47 +0300 Subject: [PATCH] refactor(core-errors)!: New sys-call error representation (#2839) --- core-backend/codegen/src/host.rs | 12 +- core-backend/codegen/src/lib.rs | 6 +- core-backend/common/src/funcs.rs | 68 +-- core-backend/common/src/lib.rs | 10 +- core-backend/sandbox/src/env.rs | 1 - core-backend/wasmi/src/funcs_tree.rs | 1 - core-errors/src/lib.rs | 430 +++++++++++------- core-processor/src/common.rs | 7 +- core-processor/src/ext.rs | 76 ++-- core/src/costs.rs | 6 - core/src/env.rs | 6 +- core/src/message/context.rs | 30 +- examples/binaries/backend-error/src/lib.rs | 6 +- examples/binaries/reserve-gas/src/lib.rs | 10 +- examples/binaries/syscall-error/src/lib.rs | 18 +- gcore/src/errors.rs | 31 +- gcore/src/exec.rs | 33 +- gcore/src/msg.rs | 138 +++--- gcore/src/prog.rs | 10 +- gsdk/src/metadata/generated.rs | 1 - gsys/src/lib.rs | 260 +++++------ gtest/src/program.rs | 2 +- pallets/gear/src/benchmarking/mod.rs | 11 - pallets/gear/src/benchmarking/syscalls.rs | 34 -- .../benchmarking/tests/syscalls_integrity.rs | 24 +- pallets/gear/src/schedule.rs | 5 - pallets/gear/src/tests.rs | 35 +- pallets/gear/src/weights.rs | 21 - runtime/gear/src/weights/pallet_gear.rs | 21 - runtime/vara/src/weights/pallet_gear.rs | 21 - utils/regression-analysis/src/main.rs | 1 - utils/wasm-gen/src/lib.rs | 4 +- utils/wasm-instrument/src/syscalls.rs | 4 - utils/wasm-proc/metadata-js/index.js | 1 - 34 files changed, 585 insertions(+), 759 deletions(-) diff --git a/core-backend/codegen/src/host.rs b/core-backend/codegen/src/host.rs index 9f344e4cb59..e19eab19dbb 100644 --- a/core-backend/codegen/src/host.rs +++ b/core-backend/codegen/src/host.rs @@ -115,7 +115,7 @@ impl HostFn { } let cost = self.meta.runtime_costs.clone(); - let err_len = self.meta.err_len.clone(); + let err = self.meta.err.clone(); let inner_block = self.item.block.clone(); let inputs = self.build_inputs(); @@ -129,7 +129,7 @@ impl HostFn { } CallType::Fallible => { parse_quote! { - ctx.run_fallible::<_, _, #err_len>(err_mid_ptr, #cost, |ctx| { + ctx.run_fallible::<_, _, #err>(err_mid_ptr, #cost, |ctx| { #inner_block }) } @@ -186,7 +186,7 @@ pub struct HostFnMeta { /// The runtime costs of the host function. runtime_costs: Expr, /// The length of the error. - pub err_len: Expr, + pub err: Expr, } impl Parse for HostFnMeta { @@ -194,7 +194,7 @@ impl Parse for HostFnMeta { let mut call_type = Default::default(); let mut wgas = false; let mut runtime_costs = parse_quote!(RuntimeCosts::Null); - let mut err_len = parse_quote!(LengthWithHash); + let mut err = parse_quote!(ErrorWithHash); let meta_list = Punctuated::::parse_terminated(input)?; for meta in meta_list { @@ -203,7 +203,7 @@ impl Parse for HostFnMeta { "fallible" => call_type = CallType::Fallible, "wgas" => wgas = true, "cost" => runtime_costs = meta.require_name_value()?.value.clone(), - "err_len" => err_len = meta.require_name_value()?.value.clone(), + "err" => err = meta.require_name_value()?.value.clone(), _ => {} } } @@ -212,7 +212,7 @@ impl Parse for HostFnMeta { call_type, wgas, runtime_costs, - err_len, + err, }) } } diff --git a/core-backend/codegen/src/lib.rs b/core-backend/codegen/src/lib.rs index 2c1f7bda60c..427ff085416 100644 --- a/core-backend/codegen/src/lib.rs +++ b/core-backend/codegen/src/lib.rs @@ -28,7 +28,7 @@ mod host; /// * `fallible` - if the host function executes fallible call. /// * `wgas` - if the host function supports with-gas version. /// * `cost` - RuntimeCosts definition, for example `#[host(cost = RuntimeCosts::Null)]` -/// * `err_len` - Error length definition, for example `#[host(err_len = LengthBytes)]` +/// * `err` - Structure definition with error code, for example `#[host(err = ErrorWithHash)]` /// /// # Example /// @@ -62,7 +62,7 @@ mod host; /// ) -> Result<(), R::Error> { /// syscall_trace!("reply", payload_ptr, len, value_ptr, delay, err_mid_ptr); /// -/// ctx.run_fallible::<_, _, LengthWithHash>(err_mid_ptr, RuntimeCosts::Reply(len), |ctx| { +/// ctx.run_fallible::<_, _, ErrorWithHash>(err_mid_ptr, RuntimeCosts::Reply(len), |ctx| { /// // ... /// }) /// } @@ -77,7 +77,7 @@ mod host; /// ) -> Result<(), R::Error> { /// syscall_trace!("reply_wgas", payload_ptr, len, gas_limit, value_ptr, delay, err_mid_ptr); /// -/// ctx.run_fallible::<_, _, LengthWithHash>(err_mid_ptr, RuntimeCosts::ReplyWGas(len), |ctx| { +/// ctx.run_fallible::<_, _, ErrorWithHash>(err_mid_ptr, RuntimeCosts::ReplyWGas(len), |ctx| { /// // ... /// }) /// } diff --git a/core-backend/common/src/funcs.rs b/core-backend/common/src/funcs.rs index dc355ff5cba..79a62b259b0 100644 --- a/core-backend/common/src/funcs.rs +++ b/core-backend/common/src/funcs.rs @@ -34,13 +34,12 @@ use gear_core::{ memory::{PageU32Size, WasmPage}, message::{HandlePacket, InitPacket, ReplyPacket}, }; -use gear_core_errors::{ExtError, ReplyCode, SignalCode}; +use gear_core_errors::{ReplyCode, SignalCode}; use gsys::{ - BlockNumberWithHash, Hash, HashWithValue, LengthBytes, LengthWithBlockNumberAndValue, - LengthWithGas, LengthWithHandle, LengthWithHash, LengthWithReplyCode, LengthWithSignalCode, - LengthWithTwoHashes, TwoHashesWithValue, + BlockNumberWithHash, ErrorBytes, ErrorWithBlockNumberAndValue, ErrorWithGas, ErrorWithHandle, + ErrorWithHash, ErrorWithReplyCode, ErrorWithSignalCode, ErrorWithTwoHashes, Hash, + HashWithValue, TwoHashesWithValue, }; -use parity_scale_codec::Encode; pub struct FuncsHandler { _phantom: PhantomData<(Ext, Runtime)>, @@ -107,12 +106,12 @@ where .map_err(Into::into) } - #[host(fallible, cost = RuntimeCosts::SendInit, err_len = LengthWithHandle)] + #[host(fallible, cost = RuntimeCosts::SendInit, err = ErrorWithHandle)] pub fn send_init(ctx: &mut R) -> Result<(), R::Error> { ctx.ext_mut().send_init().map_err(Into::into) } - #[host(fallible, cost = RuntimeCosts::SendPush(len), err_len = LengthBytes)] + #[host(fallible, cost = RuntimeCosts::SendPush(len), err = ErrorBytes)] pub fn send_push(ctx: &mut R, handle: u32, payload_ptr: u32, len: u32) -> Result<(), R::Error> { let read_payload = ctx.register_read(payload_ptr, len); let payload = ctx.read(read_payload)?; @@ -172,7 +171,7 @@ where .map_err(Into::into) } - #[host(fallible, cost = RuntimeCosts::Read, err_len = LengthBytes)] + #[host(fallible, cost = RuntimeCosts::Read, err = ErrorBytes)] pub fn read(ctx: &mut R, at: u32, len: u32, buffer_ptr: u32) -> Result<(), R::Error> { let payload_lock = ctx.ext_mut().lock_payload(at, len)?; payload_lock @@ -203,7 +202,7 @@ where Err(ActorTerminationReason::Exit(inheritor_id).into()) } - #[host(fallible, cost = RuntimeCosts::ReplyCode, err_len = LengthWithReplyCode)] + #[host(fallible, cost = RuntimeCosts::ReplyCode, err = ErrorWithReplyCode)] pub fn reply_code(ctx: &mut R) -> Result<(), R::Error> { ctx.ext_mut() .reply_code() @@ -212,7 +211,7 @@ where } // TODO: write proper benchmark #2825 - #[host(fallible, cost = RuntimeCosts::ReplyCode, err_len = LengthWithSignalCode)] + #[host(fallible, cost = RuntimeCosts::ReplyCode, err = ErrorWithSignalCode)] pub fn signal_code(ctx: &mut R) -> Result<(), R::Error> { ctx.ext_mut() .signal_code() @@ -361,7 +360,7 @@ where ctx.ext_mut().signal_from().map_err(Into::into) } - #[host(fallible, cost = RuntimeCosts::ReplyPush(len), err_len = LengthBytes)] + #[host(fallible, cost = RuntimeCosts::ReplyPush(len), err = ErrorBytes)] pub fn reply_push(ctx: &mut R, payload_ptr: u32, len: u32) -> Result<(), R::Error> { let read_payload = ctx.register_read(payload_ptr, len); let payload = ctx.read(read_payload)?; @@ -383,7 +382,7 @@ where f().map_err(Into::into) } - #[host(fallible, cost = RuntimeCosts::ReplyPushInput, err_len = LengthBytes)] + #[host(fallible, cost = RuntimeCosts::ReplyPushInput, err = ErrorBytes)] pub fn reply_push_input(ctx: &mut R, offset: u32, len: u32) -> Result<(), R::Error> { ctx.ext_mut() .reply_push_input(offset, len) @@ -418,7 +417,7 @@ where f().map_err(Into::into) } - #[host(fallible, cost = RuntimeCosts::SendPushInput, err_len = LengthBytes)] + #[host(fallible, cost = RuntimeCosts::SendPushInput, err = ErrorBytes)] pub fn send_push_input( ctx: &mut R, handle: u32, @@ -461,23 +460,17 @@ where ctx.ext_mut().reserve_gas(gas, duration).map_err(Into::into) } - pub fn reply_deposit( - ctx: &mut R, - message_id_ptr: u32, - gas: u64, - err_mid_ptr: u32, - ) -> Result<(), R::Error> { - ctx.run_fallible::<_, _, LengthBytes>(err_mid_ptr, RuntimeCosts::ReplyDeposit, |ctx| { - let read_message_id = ctx.register_read_decoded(message_id_ptr); - let message_id = ctx.read_decoded(read_message_id)?; + #[host(fallible, cost = RuntimeCosts::ReplyDeposit, err = ErrorBytes)] + pub fn reply_deposit(ctx: &mut R, message_id_ptr: u32, gas: u64) -> Result<(), R::Error> { + let read_message_id = ctx.register_read_decoded(message_id_ptr); + let message_id = ctx.read_decoded(read_message_id)?; - ctx.ext_mut() - .reply_deposit(message_id, gas) - .map_err(Into::into) - }) + ctx.ext_mut() + .reply_deposit(message_id, gas) + .map_err(Into::into) } - #[host(fallible, cost = RuntimeCosts::UnreserveGas, err_len = LengthWithGas)] + #[host(fallible, cost = RuntimeCosts::UnreserveGas, err = ErrorWithGas)] pub fn unreserve_gas(ctx: &mut R, reservation_id_ptr: u32) -> Result<(), R::Error> { let read_reservation_id = ctx.register_read_decoded(reservation_id_ptr); let reservation_id = ctx.read_decoded(read_reservation_id)?; @@ -487,7 +480,7 @@ where .map_err(Into::into) } - #[host(fallible, cost = RuntimeCosts::SystemReserveGas, err_len = LengthBytes)] + #[host(fallible, cost = RuntimeCosts::SystemReserveGas, err = ErrorBytes)] pub fn system_reserve_gas(ctx: &mut R, gas: u64) -> Result<(), R::Error> { ctx.ext_mut().system_reserve_gas(gas).map_err(Into::into) } @@ -519,7 +512,7 @@ where .map_err(Into::into) } - #[host(fallible, cost = RuntimeCosts::PayProgramRent, err_len = LengthWithBlockNumberAndValue)] + #[host(fallible, cost = RuntimeCosts::PayProgramRent, err = ErrorWithBlockNumberAndValue)] pub fn pay_program_rent(ctx: &mut R, rent_pid_ptr: u32) -> Result<(), R::Error> { let read_rent_pid = ctx.register_read_as(rent_pid_ptr); @@ -587,7 +580,7 @@ where Err(ActorTerminationReason::Wait(Some(duration), waited_type).into()) } - #[host(fallible, cost = RuntimeCosts::Wake, err_len = LengthBytes)] + #[host(fallible, cost = RuntimeCosts::Wake, err = ErrorBytes)] pub fn wake(ctx: &mut R, message_id_ptr: u32, delay: u32) -> Result<(), R::Error> { let read_message_id = ctx.register_read_decoded(message_id_ptr); let message_id = ctx.read_decoded(read_message_id)?; @@ -596,7 +589,7 @@ where } #[allow(clippy::too_many_arguments)] - #[host(fallible, wgas, cost = RuntimeCosts::CreateProgram(payload_len, salt_len), err_len = LengthWithTwoHashes)] + #[host(fallible, wgas, cost = RuntimeCosts::CreateProgram(payload_len, salt_len), err = ErrorWithTwoHashes)] pub fn create_program( ctx: &mut R, cid_value_ptr: u32, @@ -621,19 +614,6 @@ where .map_err(Into::into) } - // `error_bytes_ptr` is ptr for buffer of an error - #[host(fallible, cost = RuntimeCosts::Error, err_len = LengthBytes)] - pub fn error(ctx: &mut R, error_bytes_ptr: u32) -> Result<(), R::Error> { - if let Some(err) = ctx.fallible_syscall_error().as_ref() { - let err = err.encode(); - let write_error_bytes = ctx.register_write(error_bytes_ptr, err.len() as u32); - ctx.write(write_error_bytes, err.as_ref())?; - Ok(()) - } else { - Err(ActorTerminationReason::Trap(TrapExplanation::Ext(ExtError::SyscallUsage)).into()) - } - } - pub fn forbidden(ctx: &mut R) -> Result<(), R::Error> { syscall_trace!("forbidden"); diff --git a/core-backend/common/src/lib.rs b/core-backend/common/src/lib.rs index ed820f4d028..3b28c580ab7 100644 --- a/core-backend/common/src/lib.rs +++ b/core-backend/common/src/lib.rs @@ -58,10 +58,7 @@ use gear_core::{ use gear_core_errors::{ExecutionError, ExtError, MemoryError, MessageError}; use lazy_pages::GlobalsAccessConfig; use memory::ProcessAccessError; -use scale_info::{ - scale::{self, Decode, Encode}, - TypeInfo, -}; +use scale_info::scale::{self, Decode, Encode}; pub use crate::utils::{LimitedStr, TrimmedString}; pub use log; @@ -164,7 +161,6 @@ pub struct SystemTerminationReason; #[derive( Decode, Encode, - TypeInfo, Debug, Clone, PartialEq, @@ -360,10 +356,10 @@ pub trait BackendState { TrapExplanation::Ext(ext_err), )) = err { - let len = ext_err.encoded_size() as u32; + let code = ext_err.to_u32(); log::trace!(target: "syscalls", "fallible syscall error: {ext_err}"); self.set_fallible_syscall_error(ext_err); - Ok(Err(len)) + Ok(Err(code)) } else { Err(err) } diff --git a/core-backend/sandbox/src/env.rs b/core-backend/sandbox/src/env.rs index 33b015cbd4f..454dee70cd5 100644 --- a/core-backend/sandbox/src/env.rs +++ b/core-backend/sandbox/src/env.rs @@ -210,7 +210,6 @@ where builder.add_func(Debug, wrap_common_func!(FuncsHandler::debug, (2) -> ())); builder.add_func(Panic, wrap_common_func!(FuncsHandler::panic, (2) -> ())); builder.add_func(OomPanic, wrap_common_func!(FuncsHandler::oom_panic, () -> ())); - builder.add_func(Error, wrap_common_func!(FuncsHandler::error, (2) -> ())); builder.add_func(Exit, wrap_common_func!(FuncsHandler::exit, (1) -> ())); builder.add_func(ReplyCode, wrap_common_func!(FuncsHandler::reply_code, (1) -> ())); builder.add_func(SignalCode, wrap_common_func!(FuncsHandler::signal_code, (1) -> ())); diff --git a/core-backend/wasmi/src/funcs_tree.rs b/core-backend/wasmi/src/funcs_tree.rs index fbe52c09364..2f12a91be02 100644 --- a/core-backend/wasmi/src/funcs_tree.rs +++ b/core-backend/wasmi/src/funcs_tree.rs @@ -153,7 +153,6 @@ where f.build(Wake, |forbidden| wrap_common_func!(CommonFuncsHandler::wake, (3) -> ())(store, forbidden, memory)), f.build(CreateProgram, |forbidden| wrap_common_func!(CommonFuncsHandler::create_program, (7) -> ())(store, forbidden, memory)), f.build(CreateProgramWGas, |forbidden| wrap_common_func!(CommonFuncsHandler::create_program_wgas, (8) -> ())(store, forbidden, memory)), - f.build(Error, |forbidden| wrap_common_func!(CommonFuncsHandler::error, (2) -> ())(store, forbidden, memory)), f.build(ReserveGas, |forbidden| wrap_common_func!(CommonFuncsHandler::reserve_gas, (3) -> ())(store, forbidden, memory)), f.build(ReplyDeposit, |forbidden| wrap_common_func!(CommonFuncsHandler::reply_deposit, (3) -> ())(store, forbidden, memory)), f.build(UnreserveGas, |forbidden| wrap_common_func!(CommonFuncsHandler::unreserve_gas, (2) -> ())(store, forbidden, memory)), diff --git a/core-errors/src/lib.rs b/core-errors/src/lib.rs index 2b4b3f22155..1000ae06dcb 100644 --- a/core-errors/src/lib.rs +++ b/core-errors/src/lib.rs @@ -26,277 +26,359 @@ extern crate alloc; mod simple; use core::fmt::Debug; +use enum_iterator::Sequence; #[cfg(feature = "codec")] -use scale_info::{ - scale::{self, Decode, Encode}, - TypeInfo, +use { + alloc::vec::Vec, + scale_info::scale::{Decode, Encode, Error, Input}, }; pub use simple::*; -/// Error using messages. -#[allow(clippy::unnecessary_cast)] -#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, derive_more::Display)] -#[cfg_attr(feature = "codec", derive(Encode, Decode, TypeInfo), codec(crate = scale))] +/// Execution error. +#[derive( + Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Sequence, derive_more::Display, +)] #[non_exhaustive] -#[repr(u8)] -pub enum MessageError { - /// Message has bigger then allowed one message size - #[display(fmt = "Max message size exceed")] - MaxMessageSizeExceed = 0, +#[repr(u32)] +pub enum ExecutionError { + /// An error occurs in attempt to charge more gas than available for operation. + #[display(fmt = "Not enough gas for operation")] + NotEnoughGas = 100, + + /// The error occurs when balance is less than required by operation. + #[display(fmt = "Not enough value for operation")] + NotEnoughValue = 101, + + /// An error occurs in attempt to parse invalid string in `gr_debug` sys-call. + #[display(fmt = "Invalid debug string passed in `gr_debug` sys-call")] + InvalidDebugString = 102, /// Overflow in 'gr_read' - #[display(fmt = "Length is overflowed ({at} + {len}) to read payload")] - TooBigReadLen { - /// Range starts at - at: u32, - /// Range length - len: u32, - } = 1, + #[display(fmt = "Length is overflowed to read payload")] + TooBigReadLen = 103, /// Cannot take data in payload range - #[display( - fmt = "Cannot take data in payload range [{start}; {end}) from message with size {msg_len}" - )] - ReadWrongRange { - /// Range starts at - start: u32, - /// Range ends at - end: u32, - /// Message length - msg_len: u32, - } = 2, + #[display(fmt = "Cannot take data in payload range from message with size")] + ReadWrongRange = 104, + + /// The error occurs when functions related to reply context, used without it. + #[display(fmt = "Not running in reply context")] + NoReplyContext = 105, + + /// The error occurs when functions related to signal context, used without it. + #[display(fmt = "Not running in signal context")] + NoSignalContext = 106, + + /// The error occurs when functions related to status code, used without required context. + #[display(fmt = "No status code in reply/signal context")] + NoStatusCodeContext = 107, + + /// An error occurs in attempt to send or push reply while reply function is banned. + #[display(fmt = "Reply sending is only allowed in `init` and `handle` functions")] + IncorrectEntryForReply = 108, +} + +/// Memory error. +#[derive( + Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, Sequence, derive_more::Display, +)] +#[non_exhaustive] +#[repr(u32)] +pub enum MemoryError { + /// The error occurs, when program tries to allocate in block-chain runtime more memory than allowed. + #[display(fmt = "Trying to allocate more memory in block-chain runtime than allowed")] + RuntimeAllocOutOfBounds = 200, + /// The error occurs in attempt to access memory outside wasm program memory. + #[display(fmt = "Trying to access memory outside wasm program memory")] + AccessOutOfBounds = 201, +} + +/// Error using messages. +#[derive( + Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Sequence, derive_more::Display, +)] +#[non_exhaustive] +#[repr(u32)] +pub enum MessageError { + /// Message has bigger then allowed one message size + #[display(fmt = "Max message size exceed")] + MaxMessageSizeExceed = 300, /// The error "Message limit exceeded" occurs when a program attempts to /// send more than the maximum amount of messages allowed within a single /// execution (current setting - 1024). #[display(fmt = "Message limit exceeded")] - OutgoingMessagesAmountLimitExceeded = 3, + OutgoingMessagesAmountLimitExceeded = 301, /// The error occurs in case of attempt to send more than one replies. #[display(fmt = "Duplicate reply message")] - DuplicateReply = 4, + DuplicateReply = 302, /// The error occurs in attempt to get the same message from the waitlist /// again (which is waked already). #[display(fmt = "Duplicate waking message")] - DuplicateWaking = 5, + DuplicateWaking = 303, /// An attempt to commit or push a payload into an already formed message. #[display(fmt = "An attempt to commit or push a payload into an already formed message")] - LateAccess = 6, + LateAccess = 304, /// The error occurs in case of not valid identifier specified. #[display(fmt = "Message with given handle is not found")] - OutOfBounds = 7, + OutOfBounds = 305, /// The error occurs in attempt to initialize the same program twice within /// a single execution. #[display(fmt = "Duplicated program initialization message")] - DuplicateInit = 8, - - /// An error occurs in attempt to send a message with more gas than available after previous message. - #[display(fmt = "Not enough gas to send in message")] - NotEnoughGas = 9, + DuplicateInit = 306, /// Everything less than existential deposit but greater than 0 is not considered as available balance and not saved in DB. /// Value between 0 and existential deposit cannot be sent in message. - #[display( - fmt = "In case of non-zero message value {message_value}, it must be greater than existential deposit {existential_deposit}" - )] - InsufficientValue { - /// Message's value. - message_value: u128, - /// Minimal amount of funds on a balance that can be considered and added in DB. - existential_deposit: u128, - } = 10, + #[display(fmt = "In case of non-zero message value must be greater than existential deposit")] + InsufficientValue = 307, /// Everything less than mailbox threshold but greater than 0 is not considered as available gas limit and /// not inserted in mailbox. /// /// Gas limit between 0 and mailbox threshold cannot be inserted in mailbox. #[display( - fmt = "In case of non-zero message gas limit {message_gas_limit}, it must be greater than mailbox threshold {mailbox_threshold}" - )] - InsufficientGasLimit { - /// Message's gas limit. - message_gas_limit: u64, - /// Minimal amount of gas limit on a message that can be inserted in mailbox. - mailbox_threshold: u64, - } = 11, - - /// The error occurs when program's balance is less than value in message it tries to send. - #[display( - fmt = "Existing value {value_left} is not enough to send a message with value {message_value}" + fmt = "In case of non-zero message gas limit must be greater than mailbox threshold" )] - NotEnoughValue { - /// Message's value. - message_value: u128, - /// Amount of available value. - value_left: u128, - } = 12, - - /// The error occurs when functions related to reply context, used without it. - #[display(fmt = "Not running in reply context")] - NoReplyContext = 13, + InsufficientGasLimit = 308, - /// The error occurs when functions related to signal context, used without it. - #[display(fmt = "Not running in signal context")] - NoSignalContext = 14, + /// The error occurs when program tries to create reply deposit for message + /// that already been created within the execution. + #[display(fmt = "Reply deposit already exists for given message")] + DuplicateReplyDeposit = 309, - /// The error occurs when functions related to status code, used without required context. - #[display(fmt = "No status code in reply/signal context")] - NoStatusCodeContext = 15, + /// The error occurs when program tries to create reply deposit for message + /// that wasn't sent within the execution or for reply. + #[display( + fmt = "Reply deposit could be only created for init or handle message sent within the execution" + )] + IncorrectMessageForReplyDeposit = 310, + // TODO: remove after delay refactoring is done /// An error occurs in attempt to charge gas for dispatch stash hold. #[display(fmt = "Not enough gas to hold dispatch message")] - InsufficientGasForDelayedSending = 16, - - /// An error occurs in attempt to send or push reply while reply function is banned. - #[display(fmt = "Reply sending is only allowed in `init` and `handle` functions")] - IncorrectEntryForReply = 17, + InsufficientGasForDelayedSending = 399, } /// Error using waiting syscalls. -#[allow(clippy::unnecessary_cast)] -#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, derive_more::Display)] -#[cfg_attr(feature = "codec", derive(Encode, Decode, TypeInfo), codec(crate = scale))] +#[derive( + Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Sequence, derive_more::Display, +)] #[non_exhaustive] -#[repr(u8)] +#[repr(u32)] pub enum WaitError { - /// An error occurs in attempt to wait duration greater than could be paid. - #[display(fmt = "Not enough gas to cover holding in waitlist")] - NotEnoughGas = 0, - /// An error occurs in attempt to wait duration greater than could be paid. - #[display(fmt = "Provided incorrect argument for wait (zero case)")] - InvalidArgument = 1, + /// An error occurs in attempt to wait for or wait up to zero blocks. + #[display(fmt = "Waiting duration cannot be zero")] + ZeroDuration = 400, /// An error occurs in attempt to wait after reply sent. - WaitAfterReply = 2, -} - -/// Memory error. -#[allow(clippy::unnecessary_cast)] -#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, derive_more::Display)] -#[cfg_attr(feature = "codec", derive(Encode, Decode, TypeInfo), codec(crate = scale))] -#[non_exhaustive] -#[repr(u8)] -pub enum MemoryError { - /// The error occurs, when program tries to allocate in block-chain runtime more memory than allowed. - #[display(fmt = "Trying to allocate more memory in block-chain runtime than allowed")] - RuntimeAllocOutOfBounds = 0, - /// The error occurs in attempt to access memory outside wasm program memory. - #[display(fmt = "Trying to access memory outside wasm program memory")] - AccessOutOfBounds = 1, + #[display(fmt = "`wait()` is not allowed after reply sent")] + WaitAfterReply = 401, } /// Reservation error. -#[allow(clippy::unnecessary_cast)] -#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, derive_more::Display)] -#[cfg_attr(feature = "codec", derive(Encode, Decode, TypeInfo), codec(crate = scale))] +#[derive( + Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, Sequence, derive_more::Display, +)] #[non_exhaustive] -#[repr(u8)] +#[repr(u32)] +// TODO: refactor after multiple reservations are done pub enum ReservationError { /// An error occurs in attempt to unreserve gas with non-existing reservation ID. #[display(fmt = "Invalid reservation ID")] - InvalidReservationId = 0, - /// An error occurs in attempt to reserve more gas than available. - #[display(fmt = "Insufficient gas for reservation")] - InsufficientGasForReservation = 1, + InvalidReservationId = 500, /// An error occurs in attempt to reserve more times than allowed. #[display(fmt = "Reservation limit has reached")] - ReservationsLimitReached = 2, + ReservationsLimitReached = 501, /// An error occurs in attempt to create reservation for 0 blocks. #[display(fmt = "Reservation duration cannot be zero")] - ZeroReservationDuration = 3, + ZeroReservationDuration = 502, /// An error occurs in attempt to reserve zero gas. #[display(fmt = "Reservation amount cannot be zero")] - ZeroReservationAmount = 4, + ZeroReservationAmount = 503, /// An error occurs in attempt to reserve gas less than mailbox threshold. #[display(fmt = "Reservation amount cannot be below mailbox threshold")] - ReservationBelowMailboxThreshold = 5, + ReservationBelowMailboxThreshold = 504, } -/// Execution error. -#[allow(clippy::unnecessary_cast)] -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)] -#[cfg_attr(feature = "codec", derive(Encode, Decode, TypeInfo), codec(crate = scale))] +/// Program rent error. +#[derive( + Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, Sequence, derive_more::Display, +)] #[non_exhaustive] -#[repr(u8)] -pub enum ExecutionError { - /// An error occurs in attempt to parse invalid string in `gr_debug` sys-call. - #[display(fmt = "Invalid debug string passed in `gr_debug` sys-call")] - InvalidDebugString = 0, - - /// The error occurs when program's balance is less than rent it tries to pay. - #[display(fmt = "Existing value {value_left} is not enough to pay rent {rent}")] - NotEnoughValueForRent { - /// Rent value. - rent: u128, - /// Amount of available value. - value_left: u128, - } = 1, - +#[repr(u32)] +pub enum ProgramRentError { /// The error occurs when program's paid block count is maximum. #[display(fmt = "Rent block count limit has been reached")] - MaximumBlockCountPaid = 2, - - /// The error occurs when program tries to create reply deposit for message - /// that already been created within the execution. - #[display(fmt = "Reply deposit already exists for given message")] - DuplicateReplyDeposit = 3, - - /// The error occurs when program tries to create reply deposit for message - /// that wasn't sent within the execution or for reply. - #[display( - fmt = "Reply deposit could be only created for init or handle message sent within the execution" - )] - IncorrectMessageForReplyDeposit = 4, + MaximumBlockCountPaid = 600, } /// An error occurred in API. -#[allow(clippy::unnecessary_cast)] #[derive( - Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord, derive_more::Display, derive_more::From, + Debug, + Clone, + Copy, + Eq, + PartialEq, + Hash, + PartialOrd, + Ord, + Sequence, + derive_more::Display, + derive_more::From, )] -#[cfg_attr(feature = "codec", derive(Encode, Decode, TypeInfo), codec(crate = scale))] #[non_exhaustive] -#[repr(u8)] pub enum ExtError { - /// We got some error but don't know which exactly because of disabled gcore's `codec` feature - #[cfg(not(feature = "codec"))] - #[display(fmt = "Some error")] - Some = 0, - - // TODO: consider to create more complex one. + // TODO: remove /// Syscall usage error. #[display(fmt = "Syscall usage error")] - SyscallUsage = 1, + SyscallUsage, + + /// Execution error. + #[display(fmt = "Execution error: {_0}")] + Execution(ExecutionError), /// Memory error. #[display(fmt = "Memory error: {_0}")] - Memory(MemoryError) = 2, + Memory(MemoryError), /// Message error. #[display(fmt = "Message error: {_0}")] - Message(MessageError) = 3, + Message(MessageError), /// Waiting error. #[display(fmt = "Waiting error: {_0}")] - Wait(WaitError) = 4, + Wait(WaitError), /// Reservation error. #[display(fmt = "Reservation error: {_0}")] - Reservation(ReservationError) = 5, + Reservation(ReservationError), - /// Execution error. - #[display(fmt = "Execution error: {_0}")] - Execution(ExecutionError) = 6, + /// Program rent error. + #[display(fmt = "Program rent error: {_0}")] + ProgramRent(ProgramRentError), + + /// There is a new error variant old program don't support. + Unsupported, } -#[cfg(feature = "codec")] impl ExtError { - /// Size of error encoded in SCALE codec - pub fn encoded_size(&self) -> usize { - Encode::encoded_size(self) + /// Convert error into code. + pub fn to_u32(self) -> u32 { + match self { + ExtError::SyscallUsage => 0xffff, + ExtError::Execution(err) => err as u32, + ExtError::Memory(err) => err as u32, + ExtError::Message(err) => err as u32, + ExtError::Wait(err) => err as u32, + ExtError::Reservation(err) => err as u32, + ExtError::ProgramRent(err) => err as u32, + ExtError::Unsupported => 1, + } + } + + /// Convert code into error. + pub fn from_u32(code: u32) -> Option { + match code { + 1 => Some(ExtError::Unsupported), + 100 => Some(ExecutionError::NotEnoughGas.into()), + 101 => Some(ExecutionError::NotEnoughValue.into()), + 102 => Some(ExecutionError::InvalidDebugString.into()), + 103 => Some(ExecutionError::TooBigReadLen.into()), + 104 => Some(ExecutionError::ReadWrongRange.into()), + 105 => Some(ExecutionError::NoReplyContext.into()), + 106 => Some(ExecutionError::NoSignalContext.into()), + 107 => Some(ExecutionError::NoStatusCodeContext.into()), + 108 => Some(ExecutionError::IncorrectEntryForReply.into()), + // + 200 => Some(MemoryError::RuntimeAllocOutOfBounds.into()), + 201 => Some(MemoryError::AccessOutOfBounds.into()), + // + 300 => Some(MessageError::MaxMessageSizeExceed.into()), + 301 => Some(MessageError::OutgoingMessagesAmountLimitExceeded.into()), + 302 => Some(MessageError::DuplicateReply.into()), + 303 => Some(MessageError::DuplicateWaking.into()), + 304 => Some(MessageError::LateAccess.into()), + 305 => Some(MessageError::OutOfBounds.into()), + 306 => Some(MessageError::DuplicateInit.into()), + 307 => Some(MessageError::InsufficientValue.into()), + 308 => Some(MessageError::InsufficientGasLimit.into()), + 309 => Some(MessageError::DuplicateReplyDeposit.into()), + 310 => Some(MessageError::IncorrectMessageForReplyDeposit.into()), + 399 => Some(MessageError::InsufficientGasForDelayedSending.into()), + // + 400 => Some(WaitError::ZeroDuration.into()), + 401 => Some(WaitError::WaitAfterReply.into()), + // + 500 => Some(ReservationError::InvalidReservationId.into()), + 501 => Some(ReservationError::ReservationsLimitReached.into()), + 502 => Some(ReservationError::ZeroReservationDuration.into()), + 503 => Some(ReservationError::ZeroReservationAmount.into()), + 504 => Some(ReservationError::ReservationBelowMailboxThreshold.into()), + // + 600 => Some(ProgramRentError::MaximumBlockCountPaid.into()), + // + 0xffff => Some(ExtError::SyscallUsage), + _ => None, + } + } +} + +#[cfg(feature = "codec")] +impl Encode for ExtError { + fn encode(&self) -> Vec { + ExtError::to_u32(*self).to_le_bytes().to_vec() + } +} + +#[cfg(feature = "codec")] +impl Decode for ExtError { + fn decode(input: &mut I) -> Result { + let mut code = [0; 4]; + input.read(&mut code)?; + let err = + ExtError::from_u32(u32::from_le_bytes(code)).ok_or("Failed to decode error code")?; + Ok(err) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::collections::BTreeMap; + + #[test] + fn error_codes_are_unique() { + let mut codes = BTreeMap::new(); + + for err in enum_iterator::all::() { + let code = err.to_u32(); + if let Some(same_code_err) = codes.insert(code, err) { + panic!("{:?} has same code {:?} as {:?}", same_code_err, code, err); + } + } + } + + #[test] + fn encode_decode() { + for err in enum_iterator::all::() { + let code = err.to_u32(); + let decoded = ExtError::from_u32(code) + .unwrap_or_else(|| unreachable!("failed to decode error code: {}", code)); + assert_eq!(err, decoded); + } + } + + #[test] + fn error_code_no_specific_value() { + for err in enum_iterator::all::() { + let code = err.to_u32(); + assert_ne!(code, 0); // zeroed structures, variables, etc + assert_ne!(code, u32::MAX); // success code + } } } diff --git a/core-processor/src/common.rs b/core-processor/src/common.rs index 27a2a26657e..d3a6cd0c6b1 100644 --- a/core-processor/src/common.rs +++ b/core-processor/src/common.rs @@ -40,10 +40,7 @@ use gear_core::{ reservation::{GasReservationMap, GasReserver}, }; use gear_core_errors::{MemoryError, SignalCode, SimpleExecutionError}; -use scale_info::{ - scale::{self, Decode, Encode}, - TypeInfo, -}; +use scale_info::scale::{self, Decode, Encode}; /// Kind of the dispatch result. #[derive(Clone)] @@ -456,7 +453,7 @@ pub struct ActorExecutionError { } /// Reason of execution error -#[derive(Encode, Decode, TypeInfo, Debug, PartialEq, Eq, PartialOrd, Ord, derive_more::Display)] +#[derive(Encode, Decode, Debug, PartialEq, Eq, PartialOrd, Ord, derive_more::Display)] #[codec(crate = scale)] pub enum ActorExecutionErrorReplyReason { /// Not enough gas to perform an operation during precharge. diff --git a/core-processor/src/ext.rs b/core-processor/src/ext.rs index 9d1fb465cb7..abfe4401860 100644 --- a/core-processor/src/ext.rs +++ b/core-processor/src/ext.rs @@ -47,8 +47,8 @@ use gear_core::{ reservation::GasReserver, }; use gear_core_errors::{ - ExecutionError, ExtError as ExtErrorCore, MemoryError, MessageError, ReplyCode, - ReservationError, SignalCode, WaitError, + ExecutionError, ExtError as ExtErrorCore, MemoryError, MessageError, ProgramRentError, + ReplyCode, ReservationError, SignalCode, WaitError, }; use gear_wasm_instrument::syscalls::SysCallName; @@ -166,6 +166,12 @@ impl From for ExtError { } } +impl From for ExtError { + fn from(err: ProgramRentError) -> Self { + Self::Core(ExtErrorCore::ProgramRent(err)) + } +} + impl From for ExtError { fn from(err: ExecutionError) -> Self { Self::Core(ExtErrorCore::Execution(err)) @@ -277,11 +283,7 @@ impl Ext { let existential_deposit = self.context.existential_deposit; // Sending value should apply the range {0} ∪ [existential_deposit; +inf) if message_value != 0 && message_value < existential_deposit { - Err(MessageError::InsufficientValue { - message_value, - existential_deposit, - } - .into()) + Err(MessageError::InsufficientValue.into()) } else { Ok(()) } @@ -293,11 +295,7 @@ impl Ext { // Sending gas should apply the range {0} ∪ [mailbox_threshold; +inf) if gas_limit < mailbox_threshold && gas_limit != 0 { - Err(MessageError::InsufficientGasLimit { - message_gas_limit: gas_limit, - mailbox_threshold, - } - .into()) + Err(MessageError::InsufficientGasLimit.into()) } else { Ok(gas_limit) } @@ -305,7 +303,7 @@ impl Ext { fn reduce_gas(&mut self, gas_limit: GasLimit) -> Result<(), ExtError> { if self.context.gas_counter.reduce(gas_limit) != ChargeResult::Enough { - Err(MessageError::NotEnoughGas.into()) + Err(ExecutionError::NotEnoughGas.into()) } else { Ok(()) } @@ -313,11 +311,7 @@ impl Ext { fn charge_message_value(&mut self, message_value: u128) -> Result<(), ExtError> { if self.context.value_counter.reduce(message_value) != ChargeResult::Enough { - Err(MessageError::NotEnoughValue { - message_value, - value_left: self.context.value_counter.left(), - } - .into()) + Err(ExecutionError::NotEnoughValue.into()) } else { Ok(()) } @@ -616,7 +610,7 @@ impl Externalities for Ext { .current() .details() .and_then(|d| d.to_reply_details().map(|d| d.to_message_id())) - .ok_or_else(|| MessageError::NoReplyContext.into()) + .ok_or_else(|| ExecutionError::NoReplyContext.into()) } fn signal_from(&self) -> Result { @@ -625,7 +619,7 @@ impl Externalities for Ext { .current() .details() .and_then(|d| d.to_signal_details().map(|d| d.to_message_id())) - .ok_or_else(|| MessageError::NoSignalContext.into()) + .ok_or_else(|| ExecutionError::NoSignalContext.into()) } fn reply_push_input(&mut self, offset: u32, len: u32) -> Result<(), Self::Error> { @@ -647,7 +641,7 @@ impl Externalities for Ext { .current() .details() .and_then(|d| d.to_reply_details().map(|d| d.to_reply_code())) - .ok_or_else(|| MessageError::NoReplyContext.into()) + .ok_or_else(|| ExecutionError::NoReplyContext.into()) } fn signal_code(&self) -> Result { @@ -656,7 +650,7 @@ impl Externalities for Ext { .current() .details() .and_then(|d| d.to_signal_details().map(|d| d.to_signal_code())) - .ok_or_else(|| MessageError::NoSignalContext.into()) + .ok_or_else(|| ExecutionError::NoSignalContext.into()) } fn message_id(&self) -> Result { @@ -682,7 +676,7 @@ impl Externalities for Ext { let (paid_blocks, blocks_to_pay) = match old_paid_blocks.overflowing_add(block_count) { (count, false) => (count, block_count), - (_, true) => return Err(ExecutionError::MaximumBlockCountPaid.into()), + (_, true) => return Err(ProgramRentError::MaximumBlockCountPaid.into()), }; if blocks_to_pay == 0 { @@ -694,13 +688,7 @@ impl Externalities for Ext { ChargeResult::Enough => { self.context.program_rents.insert(program_id, paid_blocks); } - ChargeResult::NotEnough => { - return Err(ExecutionError::NotEnoughValueForRent { - rent, - value_left: self.context.value_counter.left(), - } - .into()) - } + ChargeResult::NotEnough => return Err(ExecutionError::NotEnoughValue.into()), } Ok((rent.saturating_sub(cost), blocks_to_pay)) @@ -716,18 +704,10 @@ impl Externalities for Ext { } fn lock_payload(&mut self, at: u32, len: u32) -> Result { - let end = at - .checked_add(len) - .ok_or(MessageError::TooBigReadLen { at, len })?; + let end = at.checked_add(len).ok_or(ExecutionError::TooBigReadLen)?; self.charge_gas_runtime_if_enough(RuntimeCosts::ReadPerByte(len))?; - PayloadSliceLock::try_new((at, end), &mut self.context.message_context).map_err(|msg_len| { - MessageError::ReadWrongRange { - start: at, - end, - msg_len: msg_len as u32, - } - .into() - }) + PayloadSliceLock::try_new((at, end), &mut self.context.message_context) + .ok_or_else(|| ExecutionError::ReadWrongRange.into()) } fn unlock_payload(&mut self, payload_holder: &mut PayloadSliceLock) -> UnlockPayloadBound { @@ -753,7 +733,7 @@ impl Externalities for Ext { .saturating_mul(self.context.reservation); let reduce_amount = amount.saturating_add(reserve); if self.context.gas_counter.reduce(reduce_amount) == ChargeResult::NotEnough { - return Err(ReservationError::InsufficientGasForReservation.into()); + return Err(ExecutionError::NotEnoughGas.into()); } let id = self.context.gas_reserver.reserve(amount, duration)?; @@ -782,7 +762,7 @@ impl Externalities for Ext { } if self.context.gas_counter.reduce(amount) == ChargeResult::NotEnough { - return Err(ReservationError::InsufficientGasForReservation.into()); + return Err(ExecutionError::NotEnoughGas.into()); } let reservation = &mut self.context.system_reservation; @@ -816,7 +796,7 @@ impl Externalities for Ext { .saturating_mul(self.context.waitlist_cost); if self.context.gas_counter.reduce(reserve) != ChargeResult::Enough { - return Err(WaitError::NotEnoughGas.into()); + return Err(ExecutionError::NotEnoughGas.into()); } Ok(()) @@ -830,14 +810,14 @@ impl Externalities for Ext { } if duration == 0 { - return Err(WaitError::InvalidArgument.into()); + return Err(WaitError::ZeroDuration.into()); } let reserve = u64::from(self.context.reserve_for.saturating_add(duration)) .saturating_mul(self.context.waitlist_cost); if self.context.gas_counter.reduce(reserve) != ChargeResult::Enough { - return Err(WaitError::NotEnoughGas.into()); + return Err(ExecutionError::NotEnoughGas.into()); } Ok(()) @@ -851,14 +831,14 @@ impl Externalities for Ext { } if duration == 0 { - return Err(WaitError::InvalidArgument.into()); + return Err(WaitError::ZeroDuration.into()); } let reserve = u64::from(self.context.reserve_for.saturating_add(1)) .saturating_mul(self.context.waitlist_cost); if self.context.gas_counter.reduce(reserve) != ChargeResult::Enough { - return Err(WaitError::NotEnoughGas.into()); + return Err(ExecutionError::NotEnoughGas.into()); } let reserve_full = u64::from(self.context.reserve_for.saturating_add(duration)) diff --git a/core/src/costs.rs b/core/src/costs.rs index 4258e6d201f..17c2cc0fc69 100644 --- a/core/src/costs.rs +++ b/core/src/costs.rs @@ -250,9 +250,6 @@ pub struct HostFnWeights { /// Weight per payload byte by `gr_debug`. pub gr_debug_per_byte: u64, - /// Weight of calling `gr_error`. - pub gr_error: u64, - /// Weight of calling `gr_reply_code`. pub gr_reply_code: u64, @@ -406,8 +403,6 @@ pub enum RuntimeCosts { SignalFrom, /// Weight of calling `gr_debug`. Debug(u32), - /// Weight of calling `gr_error`. - Error, /// Weight of calling `gr_reply_code`. ReplyCode, /// Weight of calling `gr_exit`. @@ -498,7 +493,6 @@ impl RuntimeCosts { ReplyTo => s.gr_reply_to, SignalFrom => s.gr_signal_from, Debug(len) => cost_with_weight_per_byte!(gr_debug, len), - Error => s.gr_error, ReplyCode => s.gr_reply_code, Exit => s.gr_exit, Leave => s.gr_leave, diff --git a/core/src/env.rs b/core/src/env.rs index f28d83d6eac..f97bad015f7 100644 --- a/core/src/env.rs +++ b/core/src/env.rs @@ -60,13 +60,13 @@ impl PayloadSliceLock { /// The method checks whether received range (slice) is correct, i.e., the end is lower /// than payload's length. If the check goes well, the ownership over payload will be /// taken from the message context by [`mem::take`]. - pub fn try_new((start, end): (u32, u32), msg_ctx: &mut MessageContext) -> Result { + pub fn try_new((start, end): (u32, u32), msg_ctx: &mut MessageContext) -> Option { let payload_len = msg_ctx.payload_mut().inner().len(); if end as usize > payload_len { - return Err(payload_len); + return None; } - Ok(Self { + Some(Self { payload: mem::take(msg_ctx.payload_mut()), range: (start as usize, end as usize), }) diff --git a/core/src/message/context.rs b/core/src/message/context.rs index 04fd4b61baa..efd71a578a6 100644 --- a/core/src/message/context.rs +++ b/core/src/message/context.rs @@ -27,7 +27,7 @@ use alloc::{ collections::{BTreeMap, BTreeSet}, vec::Vec, }; -use gear_core_errors::{ExecutionError, MessageError as Error}; +use gear_core_errors::{ExecutionError, ExtError, MessageError as Error, MessageError}; use scale_info::{ scale::{Decode, Encode}, TypeInfo, @@ -252,9 +252,9 @@ impl MessageContext { &self.settings } - fn check_reply_availability(&self) -> Result<(), Error> { + fn check_reply_availability(&self) -> Result<(), ExecutionError> { if !matches!(self.kind, DispatchKind::Init | DispatchKind::Handle) { - return Err(Error::IncorrectEntryForReply); + return Err(ExecutionError::IncorrectEntryForReply); } Ok(()) @@ -412,7 +412,7 @@ impl MessageContext { &mut self, packet: ReplyPacket, reservation: Option, - ) -> Result { + ) -> Result { self.check_reply_availability()?; if !self.reply_sent() { @@ -434,12 +434,12 @@ impl MessageContext { Ok(message_id) } else { - Err(Error::DuplicateReply) + Err(Error::DuplicateReply.into()) } } /// Pushes payload into stored reply payload. - pub fn reply_push(&mut self, buffer: &[u8]) -> Result<(), Error> { + pub fn reply_push(&mut self, buffer: &[u8]) -> Result<(), ExtError> { self.check_reply_availability()?; if !self.reply_sent() { @@ -449,7 +449,7 @@ impl MessageContext { Ok(()) } else { - Err(Error::LateAccess) + Err(Error::LateAccess.into()) } } @@ -459,7 +459,7 @@ impl MessageContext { } /// Pushes the incoming message buffer into stored reply payload. - pub fn reply_push_input(&mut self, range: CheckedRange) -> Result<(), Error> { + pub fn reply_push_input(&mut self, range: CheckedRange) -> Result<(), ExtError> { self.check_reply_availability()?; if !self.reply_sent() { @@ -474,7 +474,7 @@ impl MessageContext { Ok(()) } else { - Err(Error::LateAccess) + Err(Error::LateAccess.into()) } } @@ -494,14 +494,14 @@ impl MessageContext { &mut self, message_id: MessageId, amount: u64, - ) -> Result<(), ExecutionError> { + ) -> Result<(), MessageError> { if self .outcome .reply_deposits .iter() .any(|(mid, _)| mid == &message_id) { - return Err(ExecutionError::DuplicateReplyDeposit); + return Err(MessageError::DuplicateReplyDeposit); } if !self @@ -515,7 +515,7 @@ impl MessageContext { .iter() .any(|(message, ..)| message.id() == message_id) { - return Err(ExecutionError::IncorrectMessageForReplyDeposit); + return Err(MessageError::IncorrectMessageForReplyDeposit); } self.outcome.reply_deposits.push((message_id, amount)); @@ -887,7 +887,7 @@ mod tests { assert!(message_context.reply_deposit(message_id, 1234).is_ok()); assert_err!( message_context.reply_deposit(message_id, 1234), - ExecutionError::DuplicateReplyDeposit + MessageError::DuplicateReplyDeposit ); } @@ -916,11 +916,11 @@ mod tests { assert_err!( message_context.reply_deposit(message_id, 1234), - ExecutionError::IncorrectMessageForReplyDeposit + MessageError::IncorrectMessageForReplyDeposit ); assert_err!( message_context.reply_deposit(Default::default(), 1234), - ExecutionError::IncorrectMessageForReplyDeposit + MessageError::IncorrectMessageForReplyDeposit ); } } diff --git a/examples/binaries/backend-error/src/lib.rs b/examples/binaries/backend-error/src/lib.rs index 0616068a23d..3f06eb8249b 100644 --- a/examples/binaries/backend-error/src/lib.rs +++ b/examples/binaries/backend-error/src/lib.rs @@ -29,7 +29,7 @@ pub use code::WASM_BINARY_OPT as WASM_BINARY; #[cfg(not(feature = "std"))] mod wasm { extern crate gstd; - use gsys::{HashWithValue, LengthWithHash}; + use gsys::{ErrorWithHash, HashWithValue}; #[no_mangle] extern "C" fn init() { @@ -39,7 +39,7 @@ mod wasm { value: 0, }; - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); // u32::MAX ptr + 42 len of the payload triggers error of payload read. unsafe { @@ -52,6 +52,6 @@ mod wasm { ) }; - assert!(res.length != 0) + assert!(res.error_code != 0) } } diff --git a/examples/binaries/reserve-gas/src/lib.rs b/examples/binaries/reserve-gas/src/lib.rs index d103441ca4d..45ec982e698 100644 --- a/examples/binaries/reserve-gas/src/lib.rs +++ b/examples/binaries/reserve-gas/src/lib.rs @@ -66,7 +66,7 @@ pub type BlockCount = u32; mod wasm { use super::*; use gstd::{ - errors::{Error, ExtError, ReservationError}, + errors::{Error, ExecutionError, ExtError, ReservationError}, exec, msg, prelude::*, MessageId, ReservationId, @@ -147,15 +147,15 @@ mod wasm { assert_eq!( ReservationId::reserve(mailbox_threshold, u32::MAX), - Err(Error::Ext(ExtError::Reservation( - ReservationError::InsufficientGasForReservation + Err(Error::Ext(ExtError::Execution( + ExecutionError::NotEnoughGas ))) ); assert_eq!( ReservationId::reserve(u64::MAX, 1), - Err(Error::Ext(ExtError::Reservation( - ReservationError::InsufficientGasForReservation + Err(Error::Ext(ExtError::Execution( + ExecutionError::NotEnoughGas ))) ); } diff --git a/examples/binaries/syscall-error/src/lib.rs b/examples/binaries/syscall-error/src/lib.rs index 26bbb5b8256..022b079c64e 100644 --- a/examples/binaries/syscall-error/src/lib.rs +++ b/examples/binaries/syscall-error/src/lib.rs @@ -31,27 +31,11 @@ use gstd::errors::{Error, ExtError, MessageError}; #[no_mangle] extern "C" fn init() { - unsafe { - let mut len = 0; - gsys::gr_error(ptr::null_mut(), &mut len); - assert_ne!(len, 0); - - let mut buf = vec![0; len as usize]; - let mut len = 0; - gsys::gr_error(buf.as_mut_ptr(), &mut len); - assert_eq!(len, 0); - let err = ExtError::decode(&mut buf.as_ref()).unwrap(); - assert_eq!(err, ExtError::SyscallUsage); - } - let res = msg::send(ActorId::default(), "dummy", 250); assert_eq!( res, Err(Error::Ext(ExtError::Message( - MessageError::InsufficientValue { - message_value: 250, - existential_deposit: 500 - } + MessageError::InsufficientValue ))) ); } diff --git a/gcore/src/errors.rs b/gcore/src/errors.rs index 15622ad2ef1..9db4c2e23d3 100644 --- a/gcore/src/errors.rs +++ b/gcore/src/errors.rs @@ -35,7 +35,7 @@ impl From for Result<()> { fn from(value: SyscallError) -> Self { match value.0 { 0 => Ok(()), - _ => Err(value.get_err()?), + code => Err(ExtError::from_u32(code).unwrap_or(ExtError::Unsupported)), } } } @@ -45,33 +45,4 @@ impl SyscallError { pub fn into_result(self) -> Result<()> { self.into() } - - // TODO: issue #1859 - // We get an error using the `gr_error` syscall, which expects the error - // occurred earlier in another syscall, or you'll get a trap. We believe error - // decoding is successful because we use the SCALE codec crate of identical - // versions (at least major ones) to encode and decode errors, so error - // representation stays the same. You'll get a trap if the `len` argument is - // less than the actual encoded error length. - #[cfg(feature = "codec")] - fn get_err(self) -> Result { - use alloc::vec; - use codec::Decode; - - let mut error = vec![0; self.0 as usize]; - let mut len = 0u32; - - // We hope `gr_error` returns `Ok`; otherwise, we fall into recursion. - unsafe { gsys::gr_error(error.as_mut_ptr(), &mut len as *mut u32) }; - - Self(len).into_result()?; - - Ok(ExtError::decode(&mut error.as_ref()) - .unwrap_or_else(|e| unreachable!("Failed to decode error: {}", e))) - } - - #[cfg(not(feature = "codec"))] - fn get_err(self) -> Result { - Ok(ExtError::Some) - } } diff --git a/gcore/src/exec.rs b/gcore/src/exec.rs index 4cfa9c1eb65..b214be27f1e 100644 --- a/gcore/src/exec.rs +++ b/gcore/src/exec.rs @@ -26,8 +26,7 @@ use crate::{ ActorId, MessageId, ReservationId, }; use gsys::{ - BlockNumberWithHash, HashWithValue, LengthWithBlockNumberAndValue, LengthWithGas, - LengthWithHash, + BlockNumberWithHash, ErrorWithBlockNumberAndValue, ErrorWithGas, ErrorWithHash, HashWithValue, }; /// Get the current block height. @@ -107,9 +106,9 @@ pub fn block_timestamp() -> u64 { /// } /// ``` pub fn reply_deposit(message_id: MessageId, amount: u64) -> Result<()> { - let mut len = 0u32; - unsafe { gsys::gr_reply_deposit(message_id.as_ptr(), amount, &mut len as *mut u32) }; - SyscallError(len).into_result() + let mut error_code = 0u32; + unsafe { gsys::gr_reply_deposit(message_id.as_ptr(), amount, &mut error_code) }; + SyscallError(error_code).into_result() } /// Terminate the execution of a program. @@ -171,10 +170,10 @@ pub fn exit(inheritor_id: ActorId) -> ! { /// - [`unreserve_gas`] function unreserves gas identified by [`ReservationId`]. /// - [`system_reserve_gas`] function reserves gas for system usage. pub fn reserve_gas(amount: u64, duration: u32) -> Result { - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); unsafe { gsys::gr_reserve_gas(amount, duration, res.as_mut_ptr()) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(res.hash.into()) } @@ -202,9 +201,9 @@ pub fn reserve_gas(amount: u64, duration: u32) -> Result { /// /// - [`reserve_gas`] function reserves gas for further usage. pub fn system_reserve_gas(amount: u64) -> Result<()> { - let mut len = 0u32; - unsafe { gsys::gr_system_reserve_gas(amount, &mut len as *mut u32) }; - SyscallError(len).into_result() + let mut error_code = 0u32; + unsafe { gsys::gr_system_reserve_gas(amount, &mut error_code) }; + SyscallError(error_code).into_result() } /// Unreserve gas identified by [`ReservationId`]. @@ -219,10 +218,10 @@ pub fn system_reserve_gas(amount: u64) -> Result<()> { /// /// - [`reserve_gas`] function reserves gas for further usage. pub fn unreserve_gas(id: ReservationId) -> Result { - let mut res: LengthWithGas = Default::default(); + let mut res: ErrorWithGas = Default::default(); unsafe { gsys::gr_unreserve_gas(id.as_ptr(), res.as_mut_ptr()) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(res.gas) } @@ -372,9 +371,9 @@ pub fn wake(message_id: MessageId) -> Result<()> { /// Same as [`wake`], but executes after the `delay` expressed in block count. pub fn wake_delayed(message_id: MessageId, delay: u32) -> Result<()> { - let mut len = 0u32; - unsafe { gsys::gr_wake(message_id.as_ptr(), delay, &mut len as *mut u32) }; - SyscallError(len).into_result() + let mut error_code = 0u32; + unsafe { gsys::gr_wake(message_id.as_ptr(), delay, &mut error_code) }; + SyscallError(error_code).into_result() } /// Return the identifier of the current program. @@ -415,11 +414,11 @@ pub fn pay_program_rent(program_id: ActorId, value: u128) -> Result<(u128, u32)> value, }; - let mut res: LengthWithBlockNumberAndValue = Default::default(); + let mut res: ErrorWithBlockNumberAndValue = Default::default(); unsafe { gsys::gr_pay_program_rent(&rent_pid, res.as_mut_ptr()) } - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok((res.value, res.bn)) } diff --git a/gcore/src/msg.rs b/gcore/src/msg.rs index 86c31bb3b50..b56503f2250 100644 --- a/gcore/src/msg.rs +++ b/gcore/src/msg.rs @@ -46,7 +46,7 @@ use crate::{ }; use gear_core_errors::{ExtError, ReplyCode, SignalCode}; use gsys::{ - HashWithValue, LengthWithHandle, LengthWithHash, LengthWithReplyCode, LengthWithSignalCode, + ErrorWithHandle, ErrorWithHash, ErrorWithReplyCode, ErrorWithSignalCode, HashWithValue, TwoHashesWithValue, }; @@ -76,12 +76,12 @@ fn value_ptr(value: &u128) -> *const u128 { /// } /// ``` pub fn reply_code() -> Result { - let mut res: LengthWithReplyCode = Default::default(); + let mut res: ErrorWithReplyCode = Default::default(); unsafe { gsys::gr_reply_code(res.as_mut_ptr()) } - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; - Ok(ReplyCode::from_bytes(res.code)) + Ok(ReplyCode::from_bytes(res.reply_code)) } /// Get the reply code of the message being processed. @@ -100,12 +100,12 @@ pub fn reply_code() -> Result { /// } /// ``` pub fn signal_code() -> Result> { - let mut res: LengthWithSignalCode = Default::default(); + let mut res: ErrorWithSignalCode = Default::default(); unsafe { gsys::gr_signal_code(res.as_mut_ptr()) } - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; - Ok(SignalCode::from_u32(res.code)) + Ok(SignalCode::from_u32(res.signal_code)) } /// Get an identifier of the message that is currently being processed. @@ -158,13 +158,13 @@ pub fn read(buffer: &mut [u8]) -> Result<()> { return Err(ExtError::SyscallUsage); } - let mut len = 0u32; - if size > 0 { - unsafe { gsys::gr_read(0, size as u32, buffer.as_mut_ptr(), &mut len as *mut u32) } + let mut error_code = 0u32; + unsafe { gsys::gr_read(0, size as u32, buffer.as_mut_ptr(), &mut error_code) } + SyscallError(error_code).into_result()?; } - SyscallError(len).into_result() + Ok(()) } // TODO: issue #1859 @@ -196,17 +196,18 @@ pub fn read_at(offset: usize, buffer: &mut [u8]) -> Result<()> { return Err(ExtError::SyscallUsage); } - let mut len = 0u32; unsafe { + let mut error_code = 0u32; gsys::gr_read( offset as u32, buffer.len() as u32, buffer.as_mut_ptr(), - &mut len as *mut u32, - ) + &mut error_code, + ); + SyscallError(error_code).into_result()?; } - SyscallError(len).into_result() + Ok(()) } /// Send a new message as a reply to the message that is currently being @@ -242,7 +243,7 @@ pub fn read_at(offset: usize, buffer: &mut [u8]) -> Result<()> { /// - [`reply_push`] function allows forming a reply message in parts. /// - [`send`] function sends a new message to the program or user. pub fn reply(payload: &[u8], value: u128) -> Result { - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); let payload_len = payload .len() @@ -252,7 +253,7 @@ pub fn reply(payload: &[u8], value: u128) -> Result { let value_ptr = value_ptr(&value); unsafe { gsys::gr_reply(payload.as_ptr(), payload_len, value_ptr, res.as_mut_ptr()) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -284,7 +285,7 @@ pub fn reply(payload: &[u8], value: u128) -> Result { pub fn reply_from_reservation(id: ReservationId, payload: &[u8], value: u128) -> Result { let rid_value = HashWithValue { hash: id.0, value }; - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); let payload_len = payload .len() @@ -299,7 +300,7 @@ pub fn reply_from_reservation(id: ReservationId, payload: &[u8], value: u128) -> res.as_mut_ptr(), ) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -321,7 +322,7 @@ pub fn reply_from_reservation(id: ReservationId, payload: &[u8], value: u128) -> /// /// - [`reply_push`] function allows forming a reply message in parts. pub fn reply_with_gas(payload: &[u8], gas_limit: u64, value: u128) -> Result { - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); let payload_len = payload .len() @@ -339,7 +340,7 @@ pub fn reply_with_gas(payload: &[u8], gas_limit: u64, value: u128) -> Result Result Result { - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); let value_ptr = value_ptr(&value); unsafe { gsys::gr_reply_commit(value_ptr, res.as_mut_ptr()) } - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -409,12 +410,12 @@ pub fn reply_commit(value: u128) -> Result { /// /// - [`reply_push`] function allows forming a reply message in parts. pub fn reply_commit_with_gas(gas_limit: u64, value: u128) -> Result { - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); let value_ptr = value_ptr(&value); unsafe { gsys::gr_reply_commit_wgas(gas_limit, value_ptr, res.as_mut_ptr()) } - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -442,10 +443,10 @@ pub fn reply_commit_with_gas(gas_limit: u64, value: u128) -> Result { pub fn reply_commit_from_reservation(id: ReservationId, value: u128) -> Result { let rid_value = HashWithValue { hash: id.0, value }; - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); unsafe { gsys::gr_reservation_reply_commit(rid_value.as_ptr(), res.as_mut_ptr()) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -476,9 +477,9 @@ pub fn reply_push(payload: &[u8]) -> Result<()> { .try_into() .map_err(|_| ExtError::SyscallUsage)?; - let mut len = 0u32; - unsafe { gsys::gr_reply_push(payload.as_ptr(), payload_len, &mut len as *mut u32) }; - SyscallError(len).into_result() + let mut error_code = 0u32; + unsafe { gsys::gr_reply_push(payload.as_ptr(), payload_len, &mut error_code) }; + SyscallError(error_code).into_result() } /// Get an identifier of the initial message on which the current `handle_reply` @@ -499,10 +500,10 @@ pub fn reply_push(payload: &[u8]) -> Result<()> { /// } /// ``` pub fn reply_to() -> Result { - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); unsafe { gsys::gr_reply_to(res.as_mut_ptr()) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -524,17 +525,17 @@ pub fn reply_to() -> Result { /// } /// ``` pub fn signal_from() -> Result { - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); unsafe { gsys::gr_signal_from(res.as_mut_ptr()) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } /// Same as [`reply`], but relays the incoming message payload. pub fn reply_input(value: u128, offset: u32, len: u32) -> Result { - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); let value_ptr = value_ptr(&value); @@ -542,7 +543,7 @@ pub fn reply_input(value: u128, offset: u32, len: u32) -> Result { gsys::gr_reply_input(offset, len, value_ptr, res.as_mut_ptr()); } - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -571,9 +572,9 @@ pub fn reply_input(value: u128, offset: u32, len: u32) -> Result { /// - [`send_push_input`] function allows using the input buffer as a payload /// source for an outcoming message. pub fn reply_push_input(offset: u32, len: u32) -> Result<()> { - let mut result_len = 0u32; - unsafe { gsys::gr_reply_push_input(offset, len, &mut result_len as _) }; - SyscallError(result_len).into_result() + let mut error_code = 0u32; + unsafe { gsys::gr_reply_push_input(offset, len, &mut error_code as _) }; + SyscallError(error_code).into_result() } /// Same as [`reply_input`], but with explicit gas limit. @@ -583,14 +584,14 @@ pub fn reply_input_with_gas( offset: u32, len: u32, ) -> Result { - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); let value_ptr = value_ptr(&value); unsafe { gsys::gr_reply_input_wgas(offset, len, gas_limit, value_ptr, res.as_mut_ptr()); } - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -636,12 +637,12 @@ pub fn send_input_delayed( value, }; - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); unsafe { gsys::gr_send_input(pid_value.as_ptr(), offset, len, delay, res.as_mut_ptr()); } - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -742,7 +743,7 @@ pub fn send_delayed_from_reservation( value, }; - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); let payload_len = payload .len() @@ -758,7 +759,7 @@ pub fn send_delayed_from_reservation( res.as_mut_ptr(), ) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -790,11 +791,11 @@ pub fn send_delayed_from_reservation( /// - [`reply_push_input`] function allows using the input buffer as a payload /// source for a reply message. pub fn send_push_input(handle: MessageHandle, offset: u32, len: u32) -> Result<()> { - let mut result_len = 0u32; + let mut error_code = 0u32; unsafe { - gsys::gr_send_push_input(handle.0, offset, len, &mut result_len as _); + gsys::gr_send_push_input(handle.0, offset, len, &mut error_code as _); } - SyscallError(result_len).into_result() + SyscallError(error_code).into_result() } /// Same as [`send_input`], but with explicit gas limit. @@ -822,7 +823,7 @@ pub fn send_input_with_gas_delayed( value, }; - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); unsafe { gsys::gr_send_input_wgas( @@ -834,7 +835,7 @@ pub fn send_input_with_gas_delayed( res.as_mut_ptr(), ); } - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -888,12 +889,12 @@ pub fn send_commit_delayed_from_reservation( value, }; - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); unsafe { gsys::gr_reservation_send_commit(handle.0, rid_pid_value.as_ptr(), delay, res.as_mut_ptr()) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -911,7 +912,7 @@ pub fn send_delayed( value, }; - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); let payload_len = payload .len() @@ -927,7 +928,7 @@ pub fn send_delayed( res.as_mut_ptr(), ) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -974,7 +975,7 @@ pub fn send_with_gas_delayed( value, }; - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); let payload_len = payload .len() @@ -991,7 +992,7 @@ pub fn send_with_gas_delayed( res.as_mut_ptr(), ) } - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -1043,10 +1044,10 @@ pub fn send_commit_delayed( value, }; - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); unsafe { gsys::gr_send_commit(handle.0, pid_value.as_ptr(), delay, res.as_mut_ptr()) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -1096,7 +1097,7 @@ pub fn send_commit_with_gas_delayed( value, }; - let mut res: LengthWithHash = Default::default(); + let mut res: ErrorWithHash = Default::default(); unsafe { gsys::gr_send_commit_wgas( @@ -1107,7 +1108,7 @@ pub fn send_commit_with_gas_delayed( res.as_mut_ptr(), ) } - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageId(res.hash)) } @@ -1138,9 +1139,9 @@ pub fn send_commit_with_gas_delayed( /// in parts. pub fn send_init() -> Result { unsafe { - let mut res: LengthWithHandle = Default::default(); + let mut res: ErrorWithHandle = Default::default(); gsys::gr_send_init(res.as_mut_ptr()); - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok(MessageHandle(res.handle)) } } @@ -1181,16 +1182,9 @@ pub fn send_push(handle: MessageHandle, payload: &[u8]) -> Result<()> { .try_into() .map_err(|_| ExtError::SyscallUsage)?; - let mut len = 0u32; - unsafe { - gsys::gr_send_push( - handle.0, - payload.as_ptr(), - payload_len, - &mut len as *mut u32, - ) - }; - SyscallError(len).into_result() + let mut error_code = 0u32; + unsafe { gsys::gr_send_push(handle.0, payload.as_ptr(), payload_len, &mut error_code) }; + SyscallError(error_code).into_result() } /// Get the payload size of the message that is being processed. diff --git a/gcore/src/prog.rs b/gcore/src/prog.rs index d73add4fec8..b53d6508673 100644 --- a/gcore/src/prog.rs +++ b/gcore/src/prog.rs @@ -31,7 +31,7 @@ use crate::{ ActorId, CodeId, MessageId, }; use gear_core_errors::ExtError; -use gsys::{HashWithValue, LengthWithTwoHashes}; +use gsys::{ErrorWithTwoHashes, HashWithValue}; /// Create a new program and returns its address. /// @@ -146,7 +146,7 @@ pub fn create_program_delayed( value, }; - let mut res: LengthWithTwoHashes = Default::default(); + let mut res: ErrorWithTwoHashes = Default::default(); let salt_len = salt.len().try_into().map_err(|_| ExtError::SyscallUsage)?; @@ -166,7 +166,7 @@ pub fn create_program_delayed( res.as_mut_ptr(), ) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok((MessageId(res.hash1), ActorId(res.hash2))) } @@ -186,7 +186,7 @@ pub fn create_program_with_gas_delayed( value, }; - let mut res: LengthWithTwoHashes = Default::default(); + let mut res: ErrorWithTwoHashes = Default::default(); let salt_len = salt.len().try_into().map_err(|_| ExtError::SyscallUsage)?; @@ -207,7 +207,7 @@ pub fn create_program_with_gas_delayed( res.as_mut_ptr(), ) }; - SyscallError(res.length).into_result()?; + SyscallError(res.error_code).into_result()?; Ok((MessageId(res.hash1), ActorId(res.hash2))) } diff --git a/gsdk/src/metadata/generated.rs b/gsdk/src/metadata/generated.rs index af11e7f31a9..d6c4ec9f045 100644 --- a/gsdk/src/metadata/generated.rs +++ b/gsdk/src/metadata/generated.rs @@ -2182,7 +2182,6 @@ pub mod runtime_types { pub gr_send_push_input_per_byte: runtime_types::sp_weights::weight_v2::Weight, pub gr_debug: runtime_types::sp_weights::weight_v2::Weight, pub gr_debug_per_byte: runtime_types::sp_weights::weight_v2::Weight, - pub gr_error: runtime_types::sp_weights::weight_v2::Weight, pub gr_reply_code: runtime_types::sp_weights::weight_v2::Weight, pub gr_exit: runtime_types::sp_weights::weight_v2::Weight, pub gr_leave: runtime_types::sp_weights::weight_v2::Weight, diff --git a/gsys/src/lib.rs b/gsys/src/lib.rs index a15ea0b1fa5..6b17df1c868 100644 --- a/gsys/src/lib.rs +++ b/gsys/src/lib.rs @@ -22,6 +22,9 @@ use core::mem; +/// Represents error code type. +pub type ErrorCode = u32; + /// Represents block number type. pub type BlockNumber = u32; @@ -83,27 +86,27 @@ impl HashWithValue { } } -/// Represents type defining concatenated reply code with length. 8 bytes. +/// Represents type defining concatenated reply code with error code. 8 bytes. #[repr(C, packed)] #[derive(Default, Debug)] -pub struct LengthWithReplyCode { - pub length: Length, - pub code: ReplyCode, +pub struct ErrorWithReplyCode { + pub error_code: ErrorCode, + pub reply_code: ReplyCode, } -impl LengthWithReplyCode { +impl ErrorWithReplyCode { pub fn as_mut_ptr(&mut self) -> *mut Self { self as _ } } -impl From> for LengthWithReplyCode { - fn from(result: Result) -> Self { +impl From> for ErrorWithReplyCode { + fn from(result: Result) -> Self { let mut res: Self = Default::default(); match result { - Ok(code) => res.code = code, - Err(length) => res.length = length, + Ok(code) => res.reply_code = code, + Err(length) => res.error_code = length, } res @@ -113,51 +116,51 @@ impl From> for LengthWithReplyCode { /// Represents type defining concatenated signal code with length. 8 bytes. #[repr(C, packed)] #[derive(Default, Debug)] -pub struct LengthWithSignalCode { - pub length: Length, - pub code: SignalCode, +pub struct ErrorWithSignalCode { + pub error_code: ErrorCode, + pub signal_code: SignalCode, } -impl LengthWithSignalCode { +impl ErrorWithSignalCode { pub fn as_mut_ptr(&mut self) -> *mut Self { self as _ } } -impl From> for LengthWithSignalCode { - fn from(result: Result) -> Self { +impl From> for ErrorWithSignalCode { + fn from(result: Result) -> Self { let mut res: Self = Default::default(); match result { - Ok(code) => res.code = code, - Err(length) => res.length = length, + Ok(code) => res.signal_code = code, + Err(code) => res.error_code = code, } res } } -/// Represents type defining concatenated length with gas. 12 bytes. +/// Represents type defining concatenated error code with gas. 12 bytes. #[repr(C, packed)] #[derive(Default, Debug)] -pub struct LengthWithGas { - pub length: Length, +pub struct ErrorWithGas { + pub error_code: ErrorCode, pub gas: Gas, } -impl LengthWithGas { +impl ErrorWithGas { pub fn as_mut_ptr(&mut self) -> *mut Self { self as _ } } -impl From> for LengthWithGas { - fn from(result: Result) -> Self { +impl From> for ErrorWithGas { + fn from(result: Result) -> Self { let mut res: Self = Default::default(); match result { Ok(gas) => res.gas = gas, - Err(length) => res.length = length, + Err(code) => res.error_code = code, } res @@ -167,24 +170,24 @@ impl From> for LengthWithGas { /// Represents type defining concatenated length with handle. 8 bytes. #[repr(C, packed)] #[derive(Default, Debug)] -pub struct LengthWithHandle { - pub length: Length, +pub struct ErrorWithHandle { + pub error_code: ErrorCode, pub handle: Handle, } -impl LengthWithHandle { +impl ErrorWithHandle { pub fn as_mut_ptr(&mut self) -> *mut Self { self as _ } } -impl From> for LengthWithHandle { - fn from(result: Result) -> Self { +impl From> for ErrorWithHandle { + fn from(result: Result) -> Self { let mut res: Self = Default::default(); match result { Ok(handle) => res.handle = handle, - Err(length) => res.length = length, + Err(code) => res.error_code = code, } res @@ -193,62 +196,62 @@ impl From> for LengthWithHandle { #[repr(C, packed)] #[derive(Default, Debug)] -pub struct LengthBytes([u8; mem::size_of::()]); +pub struct ErrorBytes([u8; mem::size_of::()]); -impl From> for LengthBytes { - fn from(value: Result<(), Length>) -> Self { +impl From> for ErrorBytes { + fn from(value: Result<(), ErrorCode>) -> Self { Self(value.err().unwrap_or_default().to_le_bytes()) } } -/// Represents type defining concatenated hash with length. 36 bytes. +/// Represents type defining concatenated hash with error code. 36 bytes. #[repr(C, packed)] #[derive(Default, Debug)] -pub struct LengthWithHash { - pub length: Length, +pub struct ErrorWithHash { + pub error_code: ErrorCode, pub hash: Hash, } -impl LengthWithHash { +impl ErrorWithHash { pub fn as_mut_ptr(&mut self) -> *mut Self { self as _ } } -impl> From> for LengthWithHash { - fn from(result: Result) -> Self { +impl> From> for ErrorWithHash { + fn from(result: Result) -> Self { let mut res: Self = Default::default(); match result { Ok(v) => res.hash = v.into(), - Err(length) => res.length = length, + Err(code) => res.error_code = code, } res } } -/// Represents type defining concatenated two hashes with length. 68 bytes. +/// Represents type defining concatenated two hashes with error code. 68 bytes. #[repr(C, packed)] #[derive(Default, Debug)] -pub struct LengthWithTwoHashes { - pub length: Length, +pub struct ErrorWithTwoHashes { + pub error_code: ErrorCode, pub hash1: Hash, pub hash2: Hash, } -impl LengthWithTwoHashes { +impl ErrorWithTwoHashes { pub fn as_mut_ptr(&mut self) -> *mut Self { self as _ } } -impl From> for LengthWithTwoHashes +impl From> for ErrorWithTwoHashes where T1: Into<[u8; 32]>, T2: Into<[u8; 32]>, { - fn from(result: Result<(T1, T2), Length>) -> Self { + fn from(result: Result<(T1, T2), ErrorCode>) -> Self { let mut res: Self = Default::default(); match result { @@ -256,30 +259,30 @@ where res.hash1 = v1.into(); res.hash2 = v2.into(); } - Err(length) => res.length = length, + Err(code) => res.error_code = code, } res } } -/// Represents type defining concatenated block number and value with length. 24 bytes. +/// Represents type defining concatenated block number and value with error code. 24 bytes. #[repr(C, packed)] #[derive(Default, Debug)] -pub struct LengthWithBlockNumberAndValue { - pub length: Length, +pub struct ErrorWithBlockNumberAndValue { + pub error_code: ErrorCode, pub bn: BlockNumber, pub value: Value, } -impl LengthWithBlockNumberAndValue { +impl ErrorWithBlockNumberAndValue { pub fn as_mut_ptr(&mut self) -> *mut Self { self as _ } } -impl From> for LengthWithBlockNumberAndValue { - fn from(result: Result<(Value, BlockNumber), Length>) -> Self { +impl From> for ErrorWithBlockNumberAndValue { + fn from(result: Result<(Value, BlockNumber), ErrorCode>) -> Self { let mut res: Self = Default::default(); match result { @@ -287,7 +290,7 @@ impl From> for LengthWithBlockNumberAndValu res.value = v; res.bn = bn; } - Err(length) => res.length = length, + Err(code) => res.error_code = code, } res @@ -347,7 +350,7 @@ extern "C" { /// - `payload_len`: `u32` length of the payload buffer. /// - `gas_limit`: `u64` defining gas limit for sending. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_mid_pid`: `mut ptr` for concatenated error length, message id + /// - `err_mid_pid`: `mut ptr` for concatenated error code, message id /// and program id. pub fn gr_create_program_wgas( cid_value: *const HashWithValue, @@ -357,7 +360,7 @@ extern "C" { payload_len: Length, gas_limit: Gas, delay: BlockNumber, - err_mid_pid: *mut LengthWithTwoHashes, + err_mid_pid: *mut ErrorWithTwoHashes, ); /// Fallible `gr_create_program` send syscall. @@ -370,7 +373,7 @@ extern "C" { /// - `payload_len`: `u32` length of the payload buffer. /// - `gas_limit`: `u64` defining gas limit for sending. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_mid_pid`: `mut ptr` for concatenated error length, message id + /// - `err_mid_pid`: `mut ptr` for concatenated error code, message id /// and program id. pub fn gr_create_program( cid_value: *const HashWithValue, @@ -379,7 +382,7 @@ extern "C" { payload: *const BufferStart, payload_len: Length, delay: BlockNumber, - err_mid_pid: *mut LengthWithTwoHashes, + err_mid_pid: *mut ErrorWithTwoHashes, ); /// Fallible `gr_reply_deposit` syscall. @@ -387,8 +390,8 @@ extern "C" { /// Arguments type: /// - `message_id`: `const ptr` for message id. /// - `gas`: `u64` defining gas limit to deposit. - /// - `err`: `mut ptr` for error length. - pub fn gr_reply_deposit(message_id: *const Hash, gas: Gas, err: *mut Length); + /// - `err`: `mut ptr` for error code. + pub fn gr_reply_deposit(message_id: *const Hash, gas: Gas, err: *mut ErrorCode); /// Infallible `gr_debug` info syscall. /// @@ -409,25 +412,17 @@ extern "C" { /// Infallible `gr_oom_panic` control syscall. pub fn gr_oom_panic() -> !; - // TODO: issue #1859 - /// Fallible `gr_error` get syscall. - /// - /// Arguments type: - /// - `buf`: `mut ptr` for buffer to store previously occurred error. - /// - `len`: `mut ptr` for `u32` current error length. - pub fn gr_error(buf: *mut BufferStart, len: *mut Length); - /// Fallible `gr_reply_code` get syscall. /// /// Arguments type: - /// - `err_code`: `mut ptr` for concatenated error length and reply code. - pub fn gr_reply_code(err_code: *mut LengthWithReplyCode); + /// - `err_code`: `mut ptr` for concatenated error code and reply code. + pub fn gr_reply_code(err_code: *mut ErrorWithReplyCode); /// Fallible `gr_signal_code` get syscall. /// /// Arguments type: - /// - `err_code`: `mut ptr` for concatenated error length and signal code. - pub fn gr_signal_code(err_code: *mut LengthWithSignalCode); + /// - `err_code`: `mut ptr` for concatenated error code and signal code. + pub fn gr_signal_code(err_code: *mut ErrorWithSignalCode); /// Infallible `gr_exit` control syscall. /// @@ -454,10 +449,10 @@ extern "C" { /// /// Arguments type: /// - `rent_pid`: `const ptr` for program id and rent value. - /// - `err_bn_value`: `mut ptr` for concatenated error length, paid block count and unused rent value. + /// - `err_bn_value`: `mut ptr` for concatenated error code, paid block count and unused rent value. pub fn gr_pay_program_rent( rent_pid: *const HashWithValue, - err_bn_value: *mut LengthWithBlockNumberAndValue, + err_bn_value: *mut ErrorWithBlockNumberAndValue, ); /// Infallible `gr_program_id` get syscall. @@ -480,8 +475,8 @@ extern "C" { /// - `at`: `u32` defining offset to read from. /// - `len`: `u32` length of the buffer to read. /// - `buffer`: `mut ptr` for buffer to store requested data. - /// - `err`: `mut ptr` for `u32` error length. - pub fn gr_read(at: Length, len: Length, buffer: *mut BufferStart, err: *mut Length); + /// - `err`: `mut ptr` for `u32` error code. + pub fn gr_read(at: Length, len: Length, buffer: *mut BufferStart, err: *mut ErrorCode); /// Fallible `gr_reply_commit_wgas` send syscall. /// @@ -489,44 +484,44 @@ extern "C" { /// - `gas_limit`: `u64` defining gas limit for sending. /// - `value`: `const ptr` for `u128` defining amount of value to apply. /// Ignored if equals u32::MAX (use this for zero value for optimization). - /// - `err_mid`: `mut ptr` for concatenated error length and message id. - pub fn gr_reply_commit_wgas(gas_limit: Gas, value: *const Value, err_mid: *mut LengthWithHash); + /// - `err_mid`: `mut ptr` for concatenated error code and message id. + pub fn gr_reply_commit_wgas(gas_limit: Gas, value: *const Value, err_mid: *mut ErrorWithHash); /// Fallible `gr_reply_commit` send syscall. /// /// Arguments type: /// - `value`: `const ptr` for `u128` defining amount of value to apply. /// Ignored if equals u32::MAX (use this for zero value for optimization). - /// - `err_mid`: `mut ptr` for concatenated error length and message id. - pub fn gr_reply_commit(value: *const Value, err_mid: *mut LengthWithHash); + /// - `err_mid`: `mut ptr` for concatenated error code and message id. + pub fn gr_reply_commit(value: *const Value, err_mid: *mut ErrorWithHash); /// Fallible `gr_reply_push` send syscall. /// /// Arguments type: /// - `payload`: `const ptr` for the begging of the payload buffer. /// - `len`: `u32` length of the payload buffer. - /// - `err`: `mut ptr` for error length. - pub fn gr_reply_push(payload: *const BufferStart, len: Length, err: *mut Length); + /// - `err`: `mut ptr` for error code. + pub fn gr_reply_push(payload: *const BufferStart, len: Length, err: *mut ErrorCode); /// Fallible `gr_reply_push_input` send syscall. /// /// Arguments type: /// - `offset`: `u32` defining start index of the input buffer to use. /// - `len`: `u32` defining slice length of the input buffer to use. - /// - `err`: `mut ptr` for error length. - pub fn gr_reply_push_input(offset: Index, len: Length, err: *mut Length); + /// - `err`: `mut ptr` for error code. + pub fn gr_reply_push_input(offset: Index, len: Length, err: *mut ErrorCode); /// Fallible `gr_reply_to` get syscall. /// /// Arguments type: - /// - `err_mid`: `mut ptr` for concatenated error length and message id. - pub fn gr_reply_to(err_mid: *mut LengthWithHash); + /// - `err_mid`: `mut ptr` for concatenated error code and message id. + pub fn gr_reply_to(err_mid: *mut ErrorWithHash); /// Fallible `gr_signal_from` get syscall. /// /// Arguments type: - /// - `err_mid`: `mut ptr` for concatenated error length and message id. - pub fn gr_signal_from(err_mid: *mut LengthWithHash); + /// - `err_mid`: `mut ptr` for concatenated error code and message id. + pub fn gr_signal_from(err_mid: *mut ErrorWithHash); /// Fallible `gr_reply_input_wgas` send syscall. /// @@ -536,13 +531,13 @@ extern "C" { /// - `gas_limit`: `u64` defining gas limit for sending. /// - `value`: `const ptr` for `u128` defining amount of value to apply. /// Ignored if equals u32::MAX (use this for zero value for optimization). - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_reply_input_wgas( offset: Index, len: Length, gas_limit: Gas, value: *const Value, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_reply_wgas` send syscall. @@ -553,13 +548,13 @@ extern "C" { /// - `gas_limit`: `u64` defining gas limit for sending. /// - `value`: `const ptr` for `u128` defining amount of value to apply. /// Ignored if equals u32::MAX (use this for zero value for optimization). - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_reply_wgas( payload: *const BufferStart, len: Length, gas_limit: Gas, value: *const Value, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_reply` send syscall. @@ -569,12 +564,12 @@ extern "C" { /// - `len`: `u32` length of the payload buffer. /// - `value`: `const ptr` for `u128` defining amount of value to apply. /// Ignored if equals u32::MAX (use this for zero value for optimization). - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_reply( payload: *const BufferStart, len: Length, value: *const Value, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_reply_input` send syscall. @@ -584,12 +579,12 @@ extern "C" { /// - `len`: `u32` defining slice length of the input buffer to use. /// - `value`: `const ptr` for `u128` defining amount of value to apply. /// Ignored if equals u32::MAX (use this for zero value for optimization). - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_reply_input( offset: Index, len: Length, value: *const Value, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_reservation_reply_commit` send syscall. @@ -598,10 +593,10 @@ extern "C" { /// - `rid_value`: `const ptr` for concatenated reservation id and value. /// - `payload`: `const ptr` for the begging of the payload buffer. /// - `len`: `u32` length of the payload buffer. - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_reservation_reply_commit( rid_value: *const HashWithValue, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_reservation_reply` send syscall. @@ -610,12 +605,12 @@ extern "C" { /// - `rid_value`: `const ptr` for concatenated reservation id and value. /// - `payload`: `const ptr` for the begging of the payload buffer. /// - `len`: `u32` length of the payload buffer. - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_reservation_reply( rid_value: *const HashWithValue, payload: *const BufferStart, len: Length, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_reservation_send_commit` send syscall. @@ -625,12 +620,12 @@ extern "C" { /// - `rid_pid_value`: `const ptr` for concatenated reservation id, /// program id and value. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_reservation_send_commit( handle: Handle, rid_pid_value: *const TwoHashesWithValue, delay: BlockNumber, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_reservation_send` send syscall. @@ -641,13 +636,13 @@ extern "C" { /// - `payload`: `const ptr` for the begging of the payload buffer. /// - `len`: `u32` length of the payload buffer. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_reservation_send( rid_pid_value: *const TwoHashesWithValue, payload: *const BufferStart, len: Length, delay: BlockNumber, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_reserve_gas` control syscall. @@ -655,8 +650,8 @@ extern "C" { /// Arguments type: /// - `gas`: `u64` defining amount of gas to reserve. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_rid`: `mut ptr` for concatenated error length and reservation id. - pub fn gr_reserve_gas(gas: Gas, duration: BlockNumber, err_rid: *mut LengthWithHash); + /// - `err_rid`: `mut ptr` for concatenated error code and reservation id. + pub fn gr_reserve_gas(gas: Gas, duration: BlockNumber, err_rid: *mut ErrorWithHash); /// Fallible `gr_send_commit_wgas` send syscall. /// @@ -665,13 +660,13 @@ extern "C" { /// - `pid_value`: `const ptr` for concatenated program id and value. /// - `gas_limit`: `u64` defining gas limit for sending. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_send_commit_wgas( handle: Handle, pid_value: *const HashWithValue, gas_limit: Gas, delay: BlockNumber, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_send_commit` send syscall. @@ -680,19 +675,19 @@ extern "C" { /// - `handle`: `u32` defining handle of the message to commit. /// - `pid_value`: `const ptr` for concatenated program id and value. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_send_commit( handle: Handle, pid_value: *const HashWithValue, delay: BlockNumber, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_send_init` send syscall. /// /// Arguments type: - /// - `err_handle`: `mut ptr` for concatenated error length and handle. - pub fn gr_send_init(err_handle: *mut LengthWithHandle); + /// - `err_handle`: `mut ptr` for concatenated error code and handle. + pub fn gr_send_init(err_handle: *mut ErrorWithHandle); /// Fallible `gr_send_push` send syscall. /// @@ -700,8 +695,13 @@ extern "C" { /// - `handle`: `u32` defining handle of the message to push into. /// - `payload`: `const ptr` for the begging of the payload buffer. /// - `len`: `u32` length of the payload buffer. - /// - `err`: `mut ptr` for error length. - pub fn gr_send_push(handle: Handle, payload: *const BufferStart, len: Length, err: *mut Length); + /// - `err`: `mut ptr` for error code. + pub fn gr_send_push( + handle: Handle, + payload: *const BufferStart, + len: Length, + err: *mut ErrorCode, + ); /// Fallible `gr_send_push_input` send syscall. /// @@ -709,8 +709,8 @@ extern "C" { /// - `handle`: `u32` defining handle of the message to push into. /// - `offset`: `u32` defining start index of the input buffer to use. /// - `len`: `u32` defining slice length of the input buffer to use. - /// - `err`: `mut ptr` for error length. - pub fn gr_send_push_input(handle: Handle, offset: Index, len: Length, err: *mut Length); + /// - `err`: `mut ptr` for error code. + pub fn gr_send_push_input(handle: Handle, offset: Index, len: Length, err: *mut ErrorCode); /// Fallible `gr_send_input_wgas` send syscall. /// @@ -720,14 +720,14 @@ extern "C" { /// - `len`: `u32` defining slice length of the input buffer to use. /// - `gas_limit`: `u64` defining gas limit for sending. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_send_input_wgas( pid_value: *const HashWithValue, offset: Index, len: Length, gas_limit: Gas, delay: BlockNumber, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_send_wgas` send syscall. @@ -738,14 +738,14 @@ extern "C" { /// - `len`: `u32` length of the payload buffer. /// - `gas_limit`: `u64` defining gas limit for sending. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_send_wgas( pid_value: *const HashWithValue, payload: *const BufferStart, len: Length, gas_limit: Gas, delay: BlockNumber, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_send` send syscall. @@ -755,13 +755,13 @@ extern "C" { /// - `payload`: `const ptr` for the begging of the payload buffer. /// - `len`: `u32` length of the payload buffer. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_send( pid_value: *const HashWithValue, payload: *const BufferStart, len: Length, delay: BlockNumber, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Fallible `gr_send_input` send syscall. @@ -771,13 +771,13 @@ extern "C" { /// - `payload`: `const ptr` for the begging of the payload buffer. /// - `len`: `u32` length of the payload buffer. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_mid`: `mut ptr` for concatenated error length and message id. + /// - `err_mid`: `mut ptr` for concatenated error code and message id. pub fn gr_send_input( pid_value: *const HashWithValue, offset: Index, len: Length, delay: BlockNumber, - err_mid: *mut LengthWithHash, + err_mid: *mut ErrorWithHash, ); /// Infallible `gr_size` get syscall. @@ -796,16 +796,16 @@ extern "C" { /// /// Arguments type: /// - `gas`: `u64` defining amount of gas to reserve. - /// - `err`: `mut ptr` for error length. - pub fn gr_system_reserve_gas(gas: Gas, err: *mut Length); + /// - `err`: `mut ptr` for error code. + pub fn gr_system_reserve_gas(gas: Gas, err: *mut ErrorCode); /// Fallible `gr_unreserve_gas` control syscall. /// /// Arguments type: /// - `reservation_id`: `const ptr` for reservation id. - /// - `err_unreserved`: `mut ptr` for concatenated error length and + /// - `err_unreserved`: `mut ptr` for concatenated error code and /// unreserved gas amount. - pub fn gr_unreserve_gas(reservation_id: *const Hash, err_unreserved: *mut LengthWithGas); + pub fn gr_unreserve_gas(reservation_id: *const Hash, err_unreserved: *mut ErrorWithGas); /// Infallible `gr_value_available` get syscall. /// @@ -839,6 +839,6 @@ extern "C" { /// Arguments type: /// - `message_id`: `const ptr` for message id. /// - `delay`: `u32` amount of blocks to delay. - /// - `err_mid`: `mut ptr` for error length. - pub fn gr_wake(message_id: *const Hash, delay: BlockNumber, err: *mut Length); + /// - `err_mid`: `mut ptr` for error code. + pub fn gr_wake(message_id: *const Hash, delay: BlockNumber, err: *mut ErrorCode); } diff --git a/gtest/src/program.rs b/gtest/src/program.rs index 6814a7c4d35..81c818fe449 100644 --- a/gtest/src/program.rs +++ b/gtest/src/program.rs @@ -716,7 +716,7 @@ mod tests { prog.send_bytes(signer, b"15"); // Charge capacitor with CHARGE = 10 - let response = prog.send_bytes(signer, b"10"); + let response = dbg!(prog.send_bytes(signer, b"10")); let log = Log::builder() .source(prog.id()) .dest(signer) diff --git a/pallets/gear/src/benchmarking/mod.rs b/pallets/gear/src/benchmarking/mod.rs index 43cc746b1b1..93775848bce 100644 --- a/pallets/gear/src/benchmarking/mod.rs +++ b/pallets/gear/src/benchmarking/mod.rs @@ -1434,17 +1434,6 @@ benchmarks! { verify_process(res.unwrap()); } - gr_error { - let r in 0 .. API_BENCHMARK_BATCHES; - let mut res = None; - let exec = Benches::::gr_error(r)?; - }: { - res.replace(run_process(exec)); - } - verify { - verify_process(res.unwrap()); - } - gr_reply_code { let r in 0 .. API_BENCHMARK_BATCHES; let mut res = None; diff --git a/pallets/gear/src/benchmarking/syscalls.rs b/pallets/gear/src/benchmarking/syscalls.rs index 6712e60cbf9..02ecc416720 100644 --- a/pallets/gear/src/benchmarking/syscalls.rs +++ b/pallets/gear/src/benchmarking/syscalls.rs @@ -1247,40 +1247,6 @@ where Self::prepare_handle(module, 0) } - pub fn gr_error(r: u32) -> Result, &'static str> { - let repetitions = r * API_BENCHMARK_BATCH_SIZE; - let res_offset = COMMON_OFFSET; - let err_data_buffer_offset = res_offset + ERR_LEN_SIZE; - - let mut handle_body = body::fallible_syscall( - repetitions, - res_offset, - &[ - // error encoded data buffer offset - InstrI32Const(err_data_buffer_offset), - ], - ); - - // Insert first `gr_error` call, which returns error, so all other `gr_error` calls will be Ok. - handle_body.code_mut().elements_mut().splice( - 0..0, - [ - Instruction::I32Const(0), - Instruction::I32Const(0), - Instruction::Call(0), - ], - ); - - let module = ModuleDefinition { - memory: Some(ImportedMemory::new(SMALL_MEM_SIZE)), - imported_functions: vec![SysCallName::Error], - handle_body: Some(handle_body), - ..Default::default() - }; - - Self::prepare_handle(module, 0) - } - pub fn termination_bench( name: SysCallName, param: Option, diff --git a/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs b/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs index 218aa9b8e64..46d7bd4f122 100644 --- a/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs +++ b/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs @@ -32,7 +32,7 @@ use super::*; use crate::{Event, RentCostPerBlockOf, WaitlistOf}; use frame_support::traits::Randomness; use gear_core::ids::{CodeId, ReservationId}; -use gear_core_errors::{ExtError, MessageError, ReplyCode, SuccessReplyReason}; +use gear_core_errors::{ReplyCode, SuccessReplyReason}; use gear_wasm_instrument::syscalls::SysCallName; use pallet_timestamp::Pallet as TimestampPallet; use parity_scale_codec::Decode; @@ -92,7 +92,6 @@ where SysCallName::Alloc => check_mem::(false), SysCallName::Free => check_mem::(true), SysCallName::OutOfGas | SysCallName::OutOfAllowance => { /*no need for tests */} - SysCallName::Error => check_gr_err::(), SysCallName::Random => check_gr_random::(), SysCallName::ReserveGas => check_gr_reserve_gas::(), SysCallName::UnreserveGas => check_gr_unreserve_gas::(), @@ -343,27 +342,6 @@ where Gear::::reset(); } -fn check_gr_err() -where - T: Config, - T::AccountId: Origin, -{ - run_tester::(|_, _| { - let message_value = u128::MAX; - let expected_err = ExtError::Message(MessageError::NotEnoughValue { - message_value, - value_left: 0, - }); - let expected_err = ::alloc::format!("API error: {expected_err}"); - - let mp = vec![Kind::Error(message_value, expected_err)] - .encode() - .into(); - - (TestCall::send_message(mp), None::) - }); -} - fn check_gr_size() where T: Config, diff --git a/pallets/gear/src/schedule.rs b/pallets/gear/src/schedule.rs index 1c959db79af..d743630ae66 100644 --- a/pallets/gear/src/schedule.rs +++ b/pallets/gear/src/schedule.rs @@ -490,9 +490,6 @@ pub struct HostFnWeights { /// Weight per payload byte by `gr_debug_per_byte`. pub gr_debug_per_byte: Weight, - /// Weight of calling `gr_error`. - pub gr_error: Weight, - /// Weight of calling `gr_reply_code`. pub gr_reply_code: Weight, @@ -893,7 +890,6 @@ impl HostFnWeights { gr_reply_push_input_per_byte: self.gr_reply_push_input_per_byte.ref_time(), gr_debug: self.gr_debug.ref_time(), gr_debug_per_byte: self.gr_debug_per_byte.ref_time(), - gr_error: self.gr_error.ref_time(), gr_reply_to: self.gr_reply_to.ref_time(), gr_signal_from: self.gr_signal_from.ref_time(), gr_reply_code: self.gr_reply_code.ref_time(), @@ -978,7 +974,6 @@ impl Default for HostFnWeights { gr_random: to_weight!(cost_batched!(gr_random)), gr_debug: to_weight!(cost_batched!(gr_debug)), gr_debug_per_byte: to_weight!(cost_byte_batched!(gr_debug_per_kb)), - gr_error: to_weight!(cost_batched!(gr_error)), gr_reply_to: to_weight!(cost_batched!(gr_reply_to)), gr_signal_from: to_weight!(cost_batched!(gr_signal_from)), gr_reply_code: to_weight!(cost_batched!(gr_reply_code)), diff --git a/pallets/gear/src/tests.rs b/pallets/gear/src/tests.rs index 36d1daee6c0..725f097a1dd 100644 --- a/pallets/gear/src/tests.rs +++ b/pallets/gear/src/tests.rs @@ -4649,8 +4649,8 @@ fn test_different_waits_fail() { assert_failed( wait_gas, - ActorExecutionErrorReplyReason::Trap(TrapExplanation::Ext(ExtError::Wait( - WaitError::NotEnoughGas, + ActorExecutionErrorReplyReason::Trap(TrapExplanation::Ext(ExtError::Execution( + ExecutionError::NotEnoughGas, ))), ); @@ -4685,8 +4685,8 @@ fn test_different_waits_fail() { assert_failed( wait_for_gas, - ActorExecutionErrorReplyReason::Trap(TrapExplanation::Ext(ExtError::Wait( - WaitError::NotEnoughGas, + ActorExecutionErrorReplyReason::Trap(TrapExplanation::Ext(ExtError::Execution( + ExecutionError::NotEnoughGas, ))), ); @@ -4721,8 +4721,8 @@ fn test_different_waits_fail() { assert_failed( wait_up_to_gas, - ActorExecutionErrorReplyReason::Trap(TrapExplanation::Ext(ExtError::Wait( - WaitError::NotEnoughGas, + ActorExecutionErrorReplyReason::Trap(TrapExplanation::Ext(ExtError::Execution( + ExecutionError::NotEnoughGas, ))), ); @@ -4759,7 +4759,7 @@ fn test_different_waits_fail() { assert_failed( wait_for_arg, ActorExecutionErrorReplyReason::Trap(TrapExplanation::Ext(ExtError::Wait( - WaitError::InvalidArgument, + WaitError::ZeroDuration, ))), ); @@ -4796,7 +4796,7 @@ fn test_different_waits_fail() { assert_failed( wait_up_to_arg, ActorExecutionErrorReplyReason::Trap(TrapExplanation::Ext(ExtError::Wait( - WaitError::InvalidArgument, + WaitError::ZeroDuration, ))), ); }); @@ -6568,10 +6568,7 @@ fn pay_program_rent_syscall_works() { let error_text = if cfg!(any(feature = "debug", debug_assertions)) { format!( "{PAY_PROGRAM_RENT_EXPECT}: {:?}", - TrapExplanation::Ext(ExtError::Execution(ExecutionError::NotEnoughValueForRent { - rent: program_value, - value_left: balance_before - })) + TrapExplanation::Ext(ExtError::Execution(ExecutionError::NotEnoughValue)) ) } else { String::from("no info") @@ -6616,7 +6613,9 @@ fn pay_program_rent_syscall_works() { let error_text = if cfg!(any(feature = "debug", debug_assertions)) { format!( "{PAY_PROGRAM_RENT_EXPECT}: {:?}", - TrapExplanation::Ext(ExtError::Execution(ExecutionError::MaximumBlockCountPaid)) + TrapExplanation::Ext(ExtError::ProgramRent( + ProgramRentError::MaximumBlockCountPaid + )) ) } else { String::from("no info") @@ -7724,10 +7723,7 @@ fn test_create_program_with_value_lt_ed() { let error_text = if cfg!(any(feature = "debug", debug_assertions)) { format!( "Failed to create program: {:?}", - TrapExplanation::Ext(ExtError::Message(MessageError::InsufficientValue { - message_value: 499, - existential_deposit: 500 - })) + TrapExplanation::Ext(ExtError::Message(MessageError::InsufficientValue)) ) } else { String::from("no info") @@ -7780,10 +7776,7 @@ fn test_create_program_with_exceeding_value() { let error_text = if cfg!(any(feature = "debug", debug_assertions)) { format!( "Failed to create program: {:?}", - TrapExplanation::Ext(ExtError::Message(MessageError::NotEnoughValue { - message_value: msg_value, - value_left: msg_value - 1 - })) + TrapExplanation::Ext(ExtError::Execution(ExecutionError::NotEnoughValue)) ) } else { String::from("no info") diff --git a/pallets/gear/src/weights.rs b/pallets/gear/src/weights.rs index 733693b4c6a..39082005a94 100644 --- a/pallets/gear/src/weights.rs +++ b/pallets/gear/src/weights.rs @@ -110,7 +110,6 @@ pub trait WeightInfo { fn gr_send_push_input_per_kb(n: u32, ) -> Weight; fn gr_debug(r: u32, ) -> Weight; fn gr_debug_per_kb(n: u32, ) -> Weight; - fn gr_error(r: u32, ) -> Weight; fn gr_reply_code(r: u32, ) -> Weight; fn gr_exit(r: u32, ) -> Weight; fn gr_leave(r: u32, ) -> Weight; @@ -999,16 +998,6 @@ impl WeightInfo for SubstrateWeight { .saturating_add(Weight::from_parts(25_856_497, 0).saturating_mul(n.into())) } /// The range of component `r` is `[0, 20]`. - fn gr_error(r: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 102_508_000 picoseconds. - Weight::from_parts(103_664_089, 0) - // Standard Error: 401_054 - .saturating_add(Weight::from_parts(298_907_966, 0).saturating_mul(r.into())) - } - /// The range of component `r` is `[0, 20]`. fn gr_reply_code(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` @@ -2858,16 +2847,6 @@ impl WeightInfo for () { .saturating_add(Weight::from_parts(25_856_497, 0).saturating_mul(n.into())) } /// The range of component `r` is `[0, 20]`. - fn gr_error(r: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 102_508_000 picoseconds. - Weight::from_parts(103_664_089, 0) - // Standard Error: 401_054 - .saturating_add(Weight::from_parts(298_907_966, 0).saturating_mul(r.into())) - } - /// The range of component `r` is `[0, 20]`. fn gr_reply_code(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` diff --git a/runtime/gear/src/weights/pallet_gear.rs b/runtime/gear/src/weights/pallet_gear.rs index f98b4972b99..38bfa7ddbdc 100644 --- a/runtime/gear/src/weights/pallet_gear.rs +++ b/runtime/gear/src/weights/pallet_gear.rs @@ -111,7 +111,6 @@ pub trait WeightInfo { fn gr_send_push_input_per_kb(n: u32, ) -> Weight; fn gr_debug(r: u32, ) -> Weight; fn gr_debug_per_kb(n: u32, ) -> Weight; - fn gr_error(r: u32, ) -> Weight; fn gr_reply_code(r: u32, ) -> Weight; fn gr_exit(r: u32, ) -> Weight; fn gr_leave(r: u32, ) -> Weight; @@ -1000,16 +999,6 @@ impl pallet_gear::WeightInfo for SubstrateWeight { .saturating_add(Weight::from_parts(25_856_497, 0).saturating_mul(n.into())) } /// The range of component `r` is `[0, 20]`. - fn gr_error(r: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 102_508_000 picoseconds. - Weight::from_parts(103_664_089, 0) - // Standard Error: 401_054 - .saturating_add(Weight::from_parts(298_907_966, 0).saturating_mul(r.into())) - } - /// The range of component `r` is `[0, 20]`. fn gr_reply_code(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` @@ -2869,16 +2858,6 @@ impl WeightInfo for () { .saturating_add(Weight::from_parts(25_856_497, 0).saturating_mul(n.into())) } /// The range of component `r` is `[0, 20]`. - fn gr_error(r: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 102_508_000 picoseconds. - Weight::from_parts(103_664_089, 0) - // Standard Error: 401_054 - .saturating_add(Weight::from_parts(298_907_966, 0).saturating_mul(r.into())) - } - /// The range of component `r` is `[0, 20]`. fn gr_reply_code(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` diff --git a/runtime/vara/src/weights/pallet_gear.rs b/runtime/vara/src/weights/pallet_gear.rs index 8746406a7a1..66d55efd782 100644 --- a/runtime/vara/src/weights/pallet_gear.rs +++ b/runtime/vara/src/weights/pallet_gear.rs @@ -111,7 +111,6 @@ pub trait WeightInfo { fn gr_send_push_input_per_kb(n: u32, ) -> Weight; fn gr_debug(r: u32, ) -> Weight; fn gr_debug_per_kb(n: u32, ) -> Weight; - fn gr_error(r: u32, ) -> Weight; fn gr_reply_code(r: u32, ) -> Weight; fn gr_exit(r: u32, ) -> Weight; fn gr_leave(r: u32, ) -> Weight; @@ -1000,16 +999,6 @@ impl pallet_gear::WeightInfo for SubstrateWeight { .saturating_add(Weight::from_parts(30_640_741, 0).saturating_mul(n.into())) } /// The range of component `r` is `[0, 20]`. - fn gr_error(r: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 103_390_000 picoseconds. - Weight::from_parts(136_472_332, 0) - // Standard Error: 446_093 - .saturating_add(Weight::from_parts(278_567_834, 0).saturating_mul(r.into())) - } - /// The range of component `r` is `[0, 20]`. fn gr_reply_code(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` @@ -2869,16 +2858,6 @@ impl WeightInfo for () { .saturating_add(Weight::from_parts(30_640_741, 0).saturating_mul(n.into())) } /// The range of component `r` is `[0, 20]`. - fn gr_error(r: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 103_390_000 picoseconds. - Weight::from_parts(136_472_332, 0) - // Standard Error: 446_093 - .saturating_add(Weight::from_parts(278_567_834, 0).saturating_mul(r.into())) - } - /// The range of component `r` is `[0, 20]`. fn gr_reply_code(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` diff --git a/utils/regression-analysis/src/main.rs b/utils/regression-analysis/src/main.rs index f20424d658a..72214985ebb 100644 --- a/utils/regression-analysis/src/main.rs +++ b/utils/regression-analysis/src/main.rs @@ -338,7 +338,6 @@ fn weights(kind: WeightsKind, input_file: PathBuf, output_file: PathBuf) { gr_send_push_input_per_byte, gr_debug, gr_debug_per_byte, - gr_error, gr_reply_code, gr_exit, gr_leave, diff --git a/utils/wasm-gen/src/lib.rs b/utils/wasm-gen/src/lib.rs index 65368d8e6e4..a0c314c6092 100644 --- a/utils/wasm-gen/src/lib.rs +++ b/utils/wasm-gen/src/lib.rs @@ -38,7 +38,7 @@ use gear_wasm_instrument::{ STACK_END_EXPORT_NAME, }; pub use gsys; -use gsys::{HashWithValue, Length, LengthWithHash}; +use gsys::{ErrorWithHash, HashWithValue, Length}; use wasm_smith::{InstructionKind::*, InstructionKinds, Module as ModuleSmith, SwarmConfig}; mod syscalls; @@ -914,7 +914,7 @@ impl<'a> WasmGen<'a> { let memory_size_in_bytes = memory_pages.memory_size(); let reserve_gas_result_ptr = memory_size_in_bytes.saturating_sub(MEMORY_VALUE_SIZE) as i32; // Pointer to the LengthWithHash struct let rid_pid_value_ptr = reserve_gas_result_ptr + size_of::() as i32; - let pid_value_ptr = reserve_gas_result_ptr + size_of::() as i32; + let pid_value_ptr = reserve_gas_result_ptr + size_of::() as i32; let reservation_send_result_ptr = pid_value_ptr + size_of::() as i32; let func_instructions = Instructions::new(vec![ diff --git a/utils/wasm-instrument/src/syscalls.rs b/utils/wasm-instrument/src/syscalls.rs index 2451fa6c1e0..074d99d8484 100644 --- a/utils/wasm-instrument/src/syscalls.rs +++ b/utils/wasm-instrument/src/syscalls.rs @@ -98,7 +98,6 @@ pub enum SysCallName { // Miscellaneous ReplyDeposit, Debug, - Error, Random, ReserveGas, UnreserveGas, @@ -118,7 +117,6 @@ impl SysCallName { SysCallName::Debug => "gr_debug", SysCallName::Panic => "gr_panic", SysCallName::OomPanic => "gr_oom_panic", - SysCallName::Error => "gr_error", SysCallName::Exit => "gr_exit", SysCallName::Free => "free", SysCallName::GasAvailable => "gr_gas_available", @@ -185,7 +183,6 @@ impl SysCallName { Self::Debug, Self::Panic, Self::OomPanic, - Self::Error, Self::BlockHeight, Self::BlockTimestamp, Self::Exit, @@ -248,7 +245,6 @@ impl SysCallName { Self::Debug => SysCallSignature::gr([Ptr, Size]), Self::Panic => SysCallSignature::gr([Ptr, Size]), Self::OomPanic => SysCallSignature::gr([]), - Self::Error => SysCallSignature::gr([Ptr, Ptr]), Self::BlockHeight => SysCallSignature::gr([Ptr]), Self::BlockTimestamp => SysCallSignature::gr([Ptr]), Self::Exit => SysCallSignature::gr([Ptr]), diff --git a/utils/wasm-proc/metadata-js/index.js b/utils/wasm-proc/metadata-js/index.js index 9972f2933f3..cdd64953e70 100644 --- a/utils/wasm-proc/metadata-js/index.js +++ b/utils/wasm-proc/metadata-js/index.js @@ -49,7 +49,6 @@ exports.getWasmMetadata = async (wasmBytes) => { gr_wait_for: () => { }, gr_wait_up_to: () => { }, gr_wake: () => { }, - gr_error: () => { }, } };