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

[pallet-revive] implement tx origin API #6105

Merged
merged 22 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
14 changes: 14 additions & 0 deletions prdoc/pr_6105.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
title: '[pallet-revive] implement tx origin API'

doc:
- audience:
- Runtime Dev
description: Implement a syscall to retreive the transaction origin.

crates:
- name: pallet-revive
bump: minor
- name: pallet-revive-uapi
bump: minor
- name: pallet-revive-fixtures
bump: patch
41 changes: 41 additions & 0 deletions substrate/frame/revive/fixtures/contracts/origin.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Tests that the `origin` syscall works.

#![no_std]
#![no_main]

use common::input;
use uapi::{HostFn, HostFnImpl as api};

#[no_mangle]
#[polkavm_derive::polkavm_export]
pub extern "C" fn deploy() {
call()
}

#[no_mangle]
#[polkavm_derive::polkavm_export]
pub extern "C" fn call() {
input!(expected: &[u8; 20],);

let mut received = [0; 20];
api::origin(&mut received);

assert_eq!(expected, &received);
}
18 changes: 18 additions & 0 deletions substrate/frame/revive/src/benchmarking/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,24 @@ mod benchmarks {
);
}

#[benchmark(pov_mode = Measured)]
fn seal_origin() {
let len = H160::len_bytes();
build_runtime!(runtime, memory: [vec![0u8; len as _], ]);

let result;
#[block]
{
result = runtime.bench_origin(memory.as_mut_slice(), 0);
}

assert_ok!(result);
assert_eq!(
<H160 as Decode>::decode(&mut &memory[..]).unwrap(),
T::AddressMapper::to_address(&runtime.ext().origin().account_id().unwrap())
);
}

#[benchmark(pov_mode = Measured)]
fn seal_is_contract() {
let Contract { account_id, .. } =
Expand Down
72 changes: 72 additions & 0 deletions substrate/frame/revive/src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,9 @@ pub trait Ext: sealing::Sealed {
/// Returns the caller.
fn caller(&self) -> Origin<Self::T>;

/// Return the origin of the whole call stack.
fn origin(&self) -> Origin<Self::T>;

/// Check if a contract lives at the specified `address`.
fn is_contract(&self, address: &H160) -> bool;

Expand Down Expand Up @@ -1532,6 +1535,10 @@ where
}
}

fn origin(&self) -> Origin<T> {
self.origin.clone()
}
Copy link
Member

Choose a reason for hiding this comment

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

Why not return a reference?

Copy link
Member Author

Choose a reason for hiding this comment

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

Copy paste from fn caller which returns a value too. But I don't see why it can't be a reference. Changed it


fn is_contract(&self, address: &H160) -> bool {
ContractInfoOf::<T>::contains_key(&address)
}
Expand Down Expand Up @@ -2356,6 +2363,71 @@ mod tests {
assert_eq!(WitnessedCallerCharlie::get(), Some(BOB_ADDR));
}

#[test]
fn origin_returns_proper_values() {
parameter_types! {
static WitnessedCallerBob: Option<H160> = None;
static WitnessedCallerCharlie: Option<H160> = None;
}

let bob_ch = MockLoader::insert(Call, |ctx, _| {
// Record the origin for bob.
WitnessedCallerBob::mutate(|witness| {
let origin = ctx.ext.origin();
*witness = Some(<Test as Config>::AddressMapper::to_address(
&origin.account_id().unwrap(),
));
});

// Call into CHARLIE contract.
assert_matches!(
ctx.ext.call(
Weight::zero(),
U256::zero(),
&CHARLIE_ADDR,
U256::zero(),
vec![],
true,
false
),
Ok(_)
);
exec_success()
});
let charlie_ch = MockLoader::insert(Call, |ctx, _| {
// Record the origin for charlie.
WitnessedCallerCharlie::mutate(|witness| {
let origin = ctx.ext.origin();
*witness = Some(<Test as Config>::AddressMapper::to_address(
&origin.account_id().unwrap(),
));
});
exec_success()
});

ExtBuilder::default().build().execute_with(|| {
place_contract(&BOB, bob_ch);
place_contract(&CHARLIE, charlie_ch);
let origin = Origin::from_account_id(ALICE);
let mut storage_meter = storage::meter::Meter::new(&origin, 0, 0).unwrap();

let result = MockStack::run_call(
origin,
BOB_ADDR,
&mut GasMeter::<Test>::new(GAS_LIMIT),
&mut storage_meter,
0,
vec![],
None,
);

assert_matches!(result, Ok(_));
});

assert_eq!(WitnessedCallerBob::get(), Some(ALICE_ADDR));
assert_eq!(WitnessedCallerCharlie::get(), Some(ALICE_ADDR));
}

#[test]
fn is_contract_returns_proper_values() {
let bob_ch = MockLoader::insert(Call, |ctx, _| {
Expand Down
14 changes: 14 additions & 0 deletions substrate/frame/revive/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4442,4 +4442,18 @@ mod run_tests {
);
});
}

#[test]
fn origin_api_works() {
let (code, _) = compile_module("origin").unwrap();

ExtBuilder::default().existential_deposit(100).build().execute_with(|| {
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1_000_000);

// Create fixture: Constructor tests the origin to be equal the input data
builder::bare_instantiate(Code::Upload(code))
.data(ALICE_ADDR.0.to_vec())
.build_and_unwrap_contract();
});
Copy link
Member

Choose a reason for hiding this comment

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

Caller = Origin in this case. I think it should also test where this is not the case.

Copy link
Member Author

Choose a reason for hiding this comment

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

Deemed it unnecessary as this is already covered by the unit tests. Changed the fixture to go through both paths.

}
}
18 changes: 18 additions & 0 deletions substrate/frame/revive/src/wasm/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,8 @@ pub enum RuntimeCosts {
CopyToContract(u32),
/// Weight of calling `seal_caller`.
Caller,
/// Weight of calling `seal_origin`.
Origin,
/// Weight of calling `seal_is_contract`.
IsContract,
/// Weight of calling `seal_code_hash`.
Expand Down Expand Up @@ -453,6 +455,7 @@ impl<T: Config> Token<T> for RuntimeCosts {
CopyToContract(len) => T::WeightInfo::seal_input(len),
CopyFromContract(len) => T::WeightInfo::seal_return(len),
Caller => T::WeightInfo::seal_caller(),
Origin => T::WeightInfo::seal_origin(),
IsContract => T::WeightInfo::seal_is_contract(),
CodeHash => T::WeightInfo::seal_code_hash(),
OwnCodeHash => T::WeightInfo::seal_own_code_hash(),
Expand Down Expand Up @@ -1393,6 +1396,21 @@ pub mod env {
)?)
}

/// Stores the address of the call stack origin into the supplied buffer.
/// See [`pallet_revive_uapi::HostFn::caller`].
xermicus marked this conversation as resolved.
Show resolved Hide resolved
#[api_version(0)]
fn origin(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
self.charge_gas(RuntimeCosts::Origin)?;
let caller = <E::T as Config>::AddressMapper::to_address(self.ext.origin().account_id()?);
xermicus marked this conversation as resolved.
Show resolved Hide resolved
Ok(self.write_fixed_sandbox_output(
memory,
out_ptr,
caller.as_bytes(),
xermicus marked this conversation as resolved.
Show resolved Hide resolved
false,
already_charged,
)?)
}

/// Checks whether a specified address belongs to a contract.
/// See [`pallet_revive_uapi::HostFn::is_contract`].
#[api_version(0)]
Expand Down
Loading
Loading