Skip to content

Commit

Permalink
Update user facing panic messages
Browse files Browse the repository at this point in the history
  • Loading branch information
ByteNacked committed Sep 4, 2024
1 parent fa6c58a commit d776149
Show file tree
Hide file tree
Showing 10 changed files with 64 additions and 58 deletions.
10 changes: 10 additions & 0 deletions gtest/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,13 @@ pub enum TestError {
#[display(fmt = "Reading of program state failed: `{_0}`")]
GbuildArtifactNotFound(String),
}

macro_rules! _user_panic {
($($arg:tt)*) => {{
use colored::Colorize;
let panic_msg = format!($($arg)*).red().bold();
panic!("{}", panic_msg);
}};
}

pub(crate) use _user_panic as user_panic;
15 changes: 8 additions & 7 deletions gtest/src/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use crate::{
error::user_panic,
program::{Gas, ProgramIdWrapper},
Value, GAS_MULTIPLIER,
};
Expand Down Expand Up @@ -227,11 +228,11 @@ impl Log {
/// Set the payload of the log with bytes.
pub fn payload_bytes(mut self, payload: impl AsRef<[u8]>) -> Self {
if self.payload.is_some() {
panic!("Payload was already set for this log");
user_panic!("Payload was already set for this log");
}

if let Some(ReplyCode::Success(SuccessReplyReason::Auto)) = self.reply_code {
panic!("Cannot set payload for auto reply");
user_panic!("Cannot set payload for auto reply");
}

self.payload = Some(payload.as_ref().to_vec().try_into().unwrap());
Expand All @@ -242,7 +243,7 @@ impl Log {
/// Set the source of the log.
pub fn source(mut self, source: impl Into<ProgramIdWrapper>) -> Self {
if self.source.is_some() {
panic!("Source was already set for this log");
user_panic!("Source was already set for this log");
}

self.source = Some(source.into().0);
Expand All @@ -253,7 +254,7 @@ impl Log {
/// Set the destination of the log.
pub fn dest(mut self, dest: impl Into<ProgramIdWrapper>) -> Self {
if self.destination.is_some() {
panic!("Destination was already set for this log");
user_panic!("Destination was already set for this log");
}
self.destination = Some(dest.into().0);

Expand All @@ -263,10 +264,10 @@ impl Log {
/// Set the reply code for this log.
pub fn reply_code(mut self, reply_code: ReplyCode) -> Self {
if self.reply_code.is_some() {
panic!("Reply code was already set for this log");
user_panic!("Reply code was already set for this log");
}
if self.payload.is_some() && reply_code == ReplyCode::Success(SuccessReplyReason::Auto) {
panic!("Cannot set auto reply for log with payload");
user_panic!("Cannot set auto reply for log with payload");
}

self.reply_code = Some(reply_code);
Expand All @@ -277,7 +278,7 @@ impl Log {
/// Set the reply destination for this log.
pub fn reply_to(mut self, reply_to: MessageId) -> Self {
if self.reply_to.is_some() {
panic!("Reply destination was already set for this log");
user_panic!("Reply destination was already set for this log");
}

self.reply_to = Some(reply_to);
Expand Down
6 changes: 4 additions & 2 deletions gtest/src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ mod wait_wake;

use crate::{
constants::Value,
error::user_panic,
log::{BlockRunResult, CoreLog},
program::{Gas, WasmProgram},
state::{
Expand Down Expand Up @@ -221,8 +222,9 @@ impl ExtManager {
#[track_caller]
pub(crate) fn override_balance(&mut self, &id: &ProgramId, balance: Value) {
if Actors::is_user(id) && balance < crate::EXISTENTIAL_DEPOSIT {
panic!(
"An attempt to override balance with value ({}) less than existential deposit ({})",
user_panic!(
"An attempt to override balance with value ({}) less than existential deposit ({}. \
Please try to use bigger balance value",
balance,
crate::EXISTENTIAL_DEPOSIT
);
Expand Down
17 changes: 8 additions & 9 deletions gtest/src/manager/block_exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,18 @@ impl ExtManager {
let destination = dispatch.destination();

if Actors::is_program(source) {
panic!("Sending messages allowed only from users id");
}

if dispatch.is_reply() && !Actors::is_active_program(destination) {
panic!("Can't send reply to a non-active program {destination:?}");
user_panic!(
"Sending messages allowed only from users id. Please, provide user id as source."
);
}

// User must exist
if !Accounts::exists(source) {
panic!("User's {source} balance is zero; mint value to it first.");
user_panic!("User's {source} balance is zero; mint value to it first.");
}

if !Actors::is_active_program(destination) {
panic!("User message can't be sent to non active program");
user_panic!("User message can't be sent to non active program");
}

let is_init_msg = dispatch.kind().is_init();
Expand All @@ -73,9 +71,10 @@ impl ExtManager {

// Check sender has enough balance to cover dispatch costs
if balance < { dispatch.value() + gas_value + maybe_ed } {
panic!(
user_panic!(
"Insufficient balance: user ({}) tries to send \
({}) value, ({}) gas and ED ({}), while his balance ({:?})",
({}) value, ({}) gas and ED ({}), while his balance ({:?}). \
Please, mint more balance to the user.",
source,
dispatch.value(),
gas_value,
Expand Down
6 changes: 0 additions & 6 deletions gtest/src/manager/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,6 @@ impl JournalHandler for ExtManager {
);
}

#[track_caller]
fn update_pages_data(
&mut self,
program_id: ProgramId,
Expand All @@ -261,7 +260,6 @@ impl JournalHandler for ExtManager {
self.update_storage_pages(&program_id, pages_data);
}

#[track_caller]
fn update_allocations(&mut self, program_id: ProgramId, allocations: IntervalsTree<WasmPage>) {
self.update_genuine_program(program_id, |program| {
program
Expand All @@ -277,7 +275,6 @@ impl JournalHandler for ExtManager {
.expect("no genuine program was found");
}

#[track_caller]
fn send_value(&mut self, from: ProgramId, to: Option<ProgramId>, value: Value) {
if value.is_zero() {
// Nothing to do
Expand All @@ -288,7 +285,6 @@ impl JournalHandler for ExtManager {
self.bank.transfer_value(from, to, value);
}

#[track_caller]
fn store_new_programs(
&mut self,
program_id: ProgramId,
Expand Down Expand Up @@ -324,7 +320,6 @@ impl JournalHandler for ExtManager {
}
}

#[track_caller]
fn stop_processing(&mut self, dispatch: StoredDispatch, gas_burned: u64) {
log::debug!(
"Not enough gas for processing msg id {}, allowance equals {}, gas tried to burn at least {}",
Expand Down Expand Up @@ -424,7 +419,6 @@ impl JournalHandler for ExtManager {
});
}

#[track_caller]
fn update_gas_reservation(&mut self, program_id: ProgramId, reserver: GasReserver) {
let block_height = self.block_height();
self.update_genuine_program(program_id, |program| {
Expand Down
31 changes: 16 additions & 15 deletions gtest/src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

use crate::{
default_users_list,
error::user_panic,
manager::ExtManager,
state::actors::{Actors, GenuineProgram, Program as InnerProgram, TestActor},
system::System,
Expand Down Expand Up @@ -154,7 +155,6 @@ impl From<[u8; 32]> for ProgramIdWrapper {
}

impl From<&[u8]> for ProgramIdWrapper {
#[track_caller]
fn from(other: &[u8]) -> Self {
ProgramId::try_from(other)
.expect("invalid identifier")
Expand All @@ -181,7 +181,6 @@ impl From<String> for ProgramIdWrapper {
}

impl From<&str> for ProgramIdWrapper {
#[track_caller]
fn from(other: &str) -> Self {
ProgramId::from_str(other)
.expect("invalid identifier")
Expand Down Expand Up @@ -249,7 +248,6 @@ impl ProgramBuilder {
}

/// Create a program instance from wasm file.
#[track_caller]
pub fn from_file(path: impl AsRef<Path>) -> Self {
Self::from_binary(fs::read(path).expect("Failed to read WASM file"))
}
Expand Down Expand Up @@ -297,15 +295,13 @@ impl ProgramBuilder {
/// It looks up the wasm binary of the root crate that contains
/// the current test, uploads it to the testing system, then
/// returns the program instance.
#[track_caller]
pub fn current() -> Self {
Self::inner_current(false)
}

/// Get optimized program of the root crate with provided `system`,
///
/// See also [`ProgramBuilder::current`].
#[track_caller]
pub fn current_opt() -> Self {
Self::inner_current(true)
}
Expand All @@ -325,13 +321,11 @@ impl ProgramBuilder {
/// Set metadata for future program from file.
///
/// See also [`ProgramBuilder::with_meta`].
#[track_caller]
pub fn with_meta_file(self, path: impl AsRef<Path>) -> Self {
self.with_meta(fs::read(path).expect("Failed to read metadata file"))
}

/// Build program with set parameters.
#[track_caller]
pub fn build(self, system: &System) -> Program {
let id = self
.id
Expand Down Expand Up @@ -407,7 +401,10 @@ impl<'a> Program<'a> {
let program_id = id.clone().into().0;

if default_users_list().contains(&(program_id.into_bytes()[0] as u64)) {
panic!("Can't create program with id {id:?}, because it's reserved for default users")
user_panic!(
"Can't create program with id {id:?}, because it's reserved for default users.\
Please, use another id."
)
}

if system
Expand All @@ -416,9 +413,9 @@ impl<'a> Program<'a> {
.store_new_actor(program_id, program, None)
.is_some()
{
panic!(
"Can't create program with id {:?}, because Program with this id already exists",
id
user_panic!(
"Can't create program with id {id:?}, because Program with this id already exists. \
Please, use another id."
)
}

Expand Down Expand Up @@ -537,7 +534,6 @@ impl<'a> Program<'a> {
}

/// Send the message to the program with bytes payload and value.
#[track_caller]
pub fn send_bytes_with_value<ID, T>(&self, from: ID, payload: T, value: u128) -> MessageId
where
ID: Into<ProgramIdWrapper>,
Expand Down Expand Up @@ -800,7 +796,10 @@ pub fn calculate_program_id(code_id: CodeId, salt: &[u8], id: Option<MessageId>)

/// `cargo-gbuild` utils
pub mod gbuild {
use crate::{error::TestError as Error, Result};
use crate::{
error::{user_panic, TestError as Error},
Result,
};
use cargo_toml::Manifest;
use std::{path::PathBuf, process::Command};

Expand Down Expand Up @@ -856,7 +855,10 @@ pub mod gbuild {
.expect("cargo-gbuild is not installed, try `cargo install cargo-gbuild` first.")
.success()
{
panic!("Error occurs while compiling the current program, please run `cargo gbuild` directly for the current project to detect the problem, manifest path: {manifest:?}")
user_panic!(
"Error occurs while compiling the current program, please run `cargo gbuild` directly for the current project to detect the problem, \
manifest path: {manifest:?}"
)
}
}
}
Expand Down Expand Up @@ -1134,7 +1136,6 @@ mod tests {
}

impl Drop for CleanupFolderOnDrop {
#[track_caller]
fn drop(&mut self) {
std::fs::remove_dir_all(&self.path).expect("Failed to cleanup after test")
}
Expand Down
4 changes: 1 addition & 3 deletions gtest/src/state/actors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub(crate) struct Actors;

impl Actors {
// Accesses actor by program id.
#[track_caller]

pub(crate) fn access<R>(
program_id: ProgramId,
access: impl FnOnce(Option<&TestActor>) -> R,
Expand All @@ -47,7 +47,6 @@ impl Actors {
}

// Modifies actor by program id.
#[track_caller]
pub(crate) fn modify<R>(
program_id: ProgramId,
modify: impl FnOnce(Option<&mut TestActor>) -> R,
Expand Down Expand Up @@ -120,7 +119,6 @@ impl TestActor {

// # Panics
// If actor is initialized or dormant
#[track_caller]
pub(crate) fn set_initialized(&mut self) {
assert!(
self.is_uninitialized(),
Expand Down
6 changes: 1 addition & 5 deletions gtest/src/state/bank.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub(crate) struct Bank {

impl Bank {
// Create a new bank.
#[track_caller]

pub(crate) fn deposit_value(&mut self, id: ProgramId, value: Value, keep_alive: bool) {
Accounts::decrease(id, value, keep_alive);
self.accounts
Expand All @@ -46,7 +46,6 @@ impl Bank {
}

// Deposit gas.
#[track_caller]
pub(crate) fn deposit_gas(&mut self, id: ProgramId, gas: Gas, keep_alive: bool) {
let gas_value = GAS_MULTIPLIER.gas_to_value(gas);
Accounts::decrease(id, gas_value, keep_alive);
Expand All @@ -57,7 +56,6 @@ impl Bank {
}

// Withdraw gas.
#[track_caller]
pub(crate) fn spend_gas(
&mut self,
id: ProgramId,
Expand All @@ -72,7 +70,6 @@ impl Bank {
}

// Withdraw gas.
#[track_caller]
pub(crate) fn withdraw_gas(
&mut self,
id: ProgramId,
Expand All @@ -95,7 +92,6 @@ impl Bank {
}

// Transfer value.
#[track_caller]
pub(crate) fn transfer_value(&mut self, from: ProgramId, to: ProgramId, value: Value) {
self.accounts
.get_mut(&from)
Expand Down
3 changes: 2 additions & 1 deletion gtest/src/state/mailbox/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use crate::{
error::user_panic,
manager::ExtManager,
state::{accounts::Accounts, actors::Actors},
Log, Value, GAS_ALLOWANCE,
Expand Down Expand Up @@ -132,7 +133,7 @@ impl<'a> ActorMailbox<'a> {

// User must exist
if !Accounts::exists(self.user_id) {
panic!(
user_panic!(
"User's {} balance is zero; mint value to it first.",
self.user_id
);
Expand Down
Loading

0 comments on commit d776149

Please sign in to comment.