Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement seal_is_contract and seal_caller_is_origin #1129

Merged
merged 20 commits into from
Feb 23, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
b817ff8
[env][lang] add support for new `is_contract` API
agryaznov Feb 9, 2022
9c39937
added `is_contract()` to ink_lang::EnvAccess to use from within contr…
agryaznov Feb 9, 2022
2a58c38
added `is-contract` example
agryaznov Feb 9, 2022
5e1bc60
add support for `caller_is_origin()` API
agryaznov Feb 9, 2022
ff08823
updated is-contract example to use `caller_is_origin()` as well
agryaznov Feb 9, 2022
623b044
Merge branch 'master' of github.com:agryaznov/ink into is_contract
agryaznov Feb 9, 2022
b1310fb
Corrections in response to @HCastrano review
agryaznov Feb 15, 2022
81ec866
Merge branch 'master' of /~https://github.com/paritytech/ink into is_co…
agryaznov Feb 15, 2022
444c497
removed `examples/is-contract`
agryaznov Feb 15, 2022
5617aeb
turned back whitespaces in `env_access.rs` not to mess up with the ch…
agryaznov Feb 15, 2022
0bfcd80
Merge branch 'master' of /~https://github.com/paritytech/ink into is_co…
agryaznov Feb 18, 2022
4f76c30
added new functions to `experimental_offchain_engine`
agryaznov Feb 18, 2022
a40fab1
fixed `wrong_self_convention` clippy warning for `is_` functions
agryaznov Feb 18, 2022
123474e
supressed `wrong_self_convention` clippy warning for `is_` functions
agryaznov Feb 18, 2022
6ac81a7
Update crates/env/src/api.rs
agryaznov Feb 22, 2022
f5d9384
Merge branch 'master' of /~https://github.com/paritytech/ink into is_co…
agryaznov Feb 22, 2022
68d7cc4
set `is_contract` and `caller_is_origin` as `unimplemented` in experi…
agryaznov Feb 22, 2022
b00e7e4
Apply suggestions from code review
agryaznov Feb 23, 2022
2061940
message cant take ref as a param: revert suggested change
agryaznov Feb 23, 2022
7d463d6
Merge branch 'master' of /~https://github.com/paritytech/ink into is_co…
agryaznov Feb 23, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions crates/env/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,3 +498,38 @@ pub fn ecdsa_recover(
instance.ecdsa_recover(signature, message_hash, output)
})
}

/// Checks whether a specified account belongs to a contract.
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn is_contract<T>(account: T::AccountId) -> bool
where
T: Environment,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::is_contract::<T>(instance, account)
})
}

/// Checks whether the caller of the current contract is the origin of the whole call stack.
///
/// Prefer this over `seal_is_contract` when checking whether your contract is being called by a contract
/// or a plain account. The reason is that it performs better since it does not need to
/// do any storage lookups.
///
/// A return value of`true` indicates that this contract is being called by a plain account
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
/// and `false` indicates that the caller is another contract.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn caller_is_origin<T>() -> bool
where
T: Environment,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::caller_is_origin::<T>(instance)
})
}
18 changes: 18 additions & 0 deletions crates/env/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,4 +426,22 @@ pub trait TypedEnvBackend: EnvBackend {
fn random<T>(&mut self, subject: &[u8]) -> Result<(T::Hash, T::BlockNumber)>
where
T: Environment;

/// Checks whether a specified account belongs to a contract.
///
/// # Note
///
/// For more details visit: [`is_contract`][`crate::is_contract`]
fn is_contract<T>(&mut self, account: T::AccountId) -> bool
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
where
T: Environment;

/// Checks whether the caller of the current contract is the origin of the whole call stack.
///
/// # Note
///
/// For more details visit: [`caller_is_origin`][`crate::caller_is_origin`]
fn caller_is_origin<T>(&mut self) -> bool
where
T: Environment;
}
16 changes: 16 additions & 0 deletions crates/env/src/engine/off_chain/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,4 +471,20 @@ impl TypedEnvBackend for EnvInstance {
let block = self.current_block().expect(UNINITIALIZED_EXEC_CONTEXT);
Ok((block.random::<T>(subject)?, block.number::<T>()?))
}

fn is_contract<T>(&mut self, _account: T::AccountId) -> bool
where
T: Environment,
{
// always false, as off-chain environment does not support contract instantiation
false
}

fn caller_is_origin<T>(&mut self) -> bool
where
T: Environment,
{
// always true, as off-chain environment does not support contract instantiation
true
}
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
}
14 changes: 14 additions & 0 deletions crates/env/src/engine/on_chain/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,10 @@ mod sys {
message_hash_ptr: Ptr32<[u8]>,
output_ptr: Ptr32Mut<[u8]>,
) -> ReturnCode;

pub fn seal_is_contract(account_id_ptr: Ptr32<[u8]>) -> ReturnCode;

pub fn seal_caller_is_origin() -> ReturnCode;
}
}

Expand Down Expand Up @@ -626,3 +630,13 @@ pub fn ecdsa_recover(
};
ret_code.into()
}

pub fn is_contract(account_id: &[u8]) -> bool {
let ret_val = unsafe { sys::seal_is_contract(Ptr32::from_slice(account_id)) };
!(ret_val.0 == 0)
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
}

pub fn caller_is_origin() -> bool {
let ret_val = unsafe { sys::seal_caller_is_origin() };
!(ret_val.0 == 0)
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
}
16 changes: 16 additions & 0 deletions crates/env/src/engine/on_chain/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -490,4 +490,20 @@ impl TypedEnvBackend for EnvInstance {
ext::random(enc_subject, output);
scale::Decode::decode(&mut &output[..]).map_err(Into::into)
}

fn is_contract<T>(&mut self, account_id: T::AccountId) -> bool
where
T: Environment,
{
let mut scope = self.scoped_buffer();
let enc_account_id = scope.take_encoded(&account_id);
ext::is_contract(enc_account_id)
}

fn caller_is_origin<T>(&mut self) -> bool
where
T: Environment,
{
ext::caller_is_origin()
}
}
18 changes: 18 additions & 0 deletions crates/lang/src/env_access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -839,4 +839,22 @@ where
.map(|_| output.into())
.map_err(|_| Error::EcdsaRecoveryFailed)
}

/// Checks whether a specified account belongs to a contract.
///
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
/// # Note
///
/// For more details visit: [`ink_env::is_contract`]
pub fn is_contract(self, account_id: T::AccountId) -> bool {
ink_env::is_contract::<T>(account_id)
}

/// Checks whether the caller of the current contract is the origin of the whole call stack.
///
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
/// # Note
///
/// For more details visit: [`ink_env::caller_is_origin`]
pub fn caller_is_origin(self) -> bool {
ink_env::caller_is_origin::<T>()
}
}
11 changes: 11 additions & 0 deletions examples/is-contract/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Ignore build artifacts from the local tests sub-crate.
/target/

# Ignore backup files creates by cargo fmt.
**/*.rs.bk

# Remove Cargo.lock when creating an executable, leave it for libraries
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Cargo.lock

*~
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
37 changes: 37 additions & 0 deletions examples/is-contract/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
[package]
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
name = "is_contract"
version = "3.0.0-rc8"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"

[dependencies]
ink_primitives = { version = "3.0.0-rc8", path = "../../crates/primitives", default-features = false }
ink_metadata = { version = "3.0.0-rc8", path = "../../crates/metadata", default-features = false, features = ["derive"], optional = true }
ink_env = { version = "3.0.0-rc8", path = "../../crates/env", default-features = false, features = [ "ink-debug" ] }
ink_storage = { version = "3.0.0-rc8", path = "../../crates/storage", default-features = false }
ink_lang = { version = "3.0.0-rc8", path = "../../crates/lang", default-features = false }
ink_prelude = { version = "3.0.0-rc8", path = "../../crates/prelude", default-features = false }

scale = { package = "parity-scale-codec", version = "2", default-features = false, features = ["derive"] }
scale-info = { version = "1", default-features = false, features = ["derive"], optional = true }

[lib]
name = "is_contract"
path = "lib.rs"
crate-type = ["cdylib"]

[features]
default = ["std"]
std = [
"ink_primitives/std",
"ink_metadata",
"ink_metadata/std",
"ink_env/std",
"ink_storage/std",
"ink_lang/std",
"scale/std",
"scale-info",
"scale-info/std",
]
ink-as-dependency = []
ink-experimental-engine = ["ink_env/ink-experimental-engine"]
159 changes: 159 additions & 0 deletions examples/is-contract/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
//! A smart contract which demonstrates behavior of the `self.env().is_contract()`
//! and `self.env().caller_is_origin()` functions.
//! It checks whether a specified account_id is a contract

#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::new_without_default)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would address this instead of suppressing the Clippy warning


use ink_lang as ink;

#[ink::contract]
pub mod is_contract {
use ink_env::call::{
build_call,
utils::{
EmptyArgumentList,
ReturnType,
},
ExecutionInput,
Selector,
};

#[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
/// Error types
pub enum Error {
SomeError,
}

/// Event emitted when Winning block is detected.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left-over copy-pasta

#[ink(event)]
pub struct AccountIsContract {
account_id: AccountId,
is_contract: bool,
}

/// Event emitted when a winner is detected.
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
#[ink(event)]
pub struct CallerIsOrigin {
is_origin: bool,
}

/// No storage is needed for this simple contract.
#[ink(storage)]
pub struct IsContract {}

impl IsContract {
/// Creates a new instance of this contract.
#[ink(constructor)]
pub fn new() -> Self {
Self {}
}

/// Cross contract invocation method
fn invoke_contract(
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
&self,
contract: AccountId,
input: ExecutionInput<EmptyArgumentList>,
) {
let params = build_call::<Environment>()
.callee(contract)
.exec_input(input)
.returns::<ReturnType<Result<(), Error>>>();

match params.fire() {
Ok(_v) => {}
Err(e) => {
match e {
ink_env::Error::CodeNotFound | ink_env::Error::NotCallable => {
// Our recipient wasn't a smart contract, so there's nothing more for
// us to do
let msg = ink_prelude::format!(
"Recipient at {:#04X?} from is not a smart contract ({:?})",
contract,
e
);
panic!("{}", msg)
}
_ => {
// We got some sort of error from the call to our recipient smart
// contract, and as such we must revert this call
let msg = ink_prelude::format!(
"Got error \"{:?}\" while trying to call {:?}",
e,
contract,
);
panic!("{}", msg)
}
}
}
}
}

/// Checks if the specified account_id belogns to a contract
agryaznov marked this conversation as resolved.
Show resolved Hide resolved
#[ink(message, selector = 0xBABEFEED)]
pub fn is_contract(&mut self, account_id: AccountId) -> bool {
ink_env::debug_println!(
"checking if account_id is contract: {:?}",
account_id
);

let is_contract = self.env().is_contract(account_id);

self.env().emit_event(AccountIsContract {
account_id: account_id.clone(),
is_contract: is_contract.clone(),
});

is_contract
}

/// Checks if the caller is the origin of the whole call stack.
#[ink(message)]
pub fn caller_is_origin(&mut self) -> bool {
ink_env::debug_println!("checking if caller is the origin",);

let is_origin = self.env().caller_is_origin();

self.env().emit_event(CallerIsOrigin {
is_origin: is_origin.clone(),
});

is_origin
}

/// Checks if the caller is the origin of the whole call stack.
#[ink(message)]
pub fn call_contract(&mut self, address: AccountId) {
let selector = Selector::new([0xBA, 0xBE, 0xFE, 0xED]);
let input = ExecutionInput::new(selector);
self.invoke_contract(address, input);
}
}

#[cfg(not(feature = "ink-experimental-engine"))]
#[cfg(test)]
mod tests {
use super::*;

use ink_lang as ink;

fn accounts() -> ink_env::test::DefaultAccounts<Environment> {
ink_env::test::default_accounts::<Environment>().unwrap()
}

#[ink::test]
fn is_contract_works() {
// to be honest, this is just a boilerplate
// since off_chain env does not support contracts
assert!(!ink_env::is_contract::<Environment>(accounts().alice));
}

#[ink::test]
fn caller_is_origin_works() {
// to be honest, this is just a boilerplate
// since off_chain env does not support contracts
assert!(ink_env::caller_is_origin::<Environment>());
}
}
}