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

Changes for Economic Protocol scenario 3 - "contract pays for gas" #352

Merged
merged 5 commits into from
May 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions contracts/c-example/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ use std::ptr;
#[no_mangle]
pub static mut A: [u8; 65536] = [0; 65536];

// Define second argument buffer for the Economic Protocol
#[no_mangle]
pub static mut ECO_MODE: [u8; 16] = [0; 16];

// ==== Host functions ====
//
// These functions are provided by the host. See `piecrust-uplink` for a full
Expand Down
4 changes: 2 additions & 2 deletions contracts/callcenter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl Callcenter {
fn_arg: Vec<u8>,
) -> Result<Vec<u8>, ContractError> {
uplink::debug!("raw query {fn_name} at {contract_id:?}");
uplink::call_raw(contract_id, &fn_name, &fn_arg)
uplink::call_raw(contract_id, &fn_name, &fn_arg).map(|r|r.data)
}

/// Pass the current query
Expand All @@ -62,7 +62,7 @@ impl Callcenter {
fn_name: String,
fn_arg: Vec<u8>,
) -> Vec<u8> {
uplink::call_raw(contract_id, &fn_name, &fn_arg).unwrap()
uplink::call_raw(contract_id, &fn_name, &fn_arg).unwrap().data
}

/// Check whether the current caller is the contract itself
Expand Down
6 changes: 3 additions & 3 deletions contracts/grower/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ static mut STATE: Grower = Grower(Vec::new());
impl Grower {
/// Appends the bytes sent in the argument buffer to the state vector.
fn append(&mut self, len: usize) {
with_arg_buf(|buf| {
with_arg_buf(|buf, _| {
self.0.extend_from_slice(&buf[..len]);
});
}

/// Parses offset and length from the argument buffer, and copies the bytes
/// at said offset and length on the state vector to the argument buffer.
fn view(&self, arg_len: usize) -> usize {
with_arg_buf(|buf| {
with_arg_buf(|buf, _| {
if arg_len != 8 {
panic!("Bad arguments");
}
Expand All @@ -62,7 +62,7 @@ impl Grower {

/// Emplace the length of the state vector into the argument buffer.
fn len(&self) -> usize {
with_arg_buf(|buf| {
with_arg_buf(|buf, _| {
let len = self.0.len() as u32;
let len_bytes = len.to_le_bytes();
buf[..4].copy_from_slice(&len_bytes);
Expand Down
7 changes: 7 additions & 0 deletions piecrust-uplink/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Add contract charge setting method [#353]
- Add contract allowance setting method and a corresponding passing mechanism [#350]

## [0.11.0] - 2024-02-14

### Added
Expand Down Expand Up @@ -162,6 +167,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- First `piecrust-uplink` release

<!-- ISSUES -->
[#353]: https://github.com/dusk-network/piecrust/issues/353
[#350]: https://github.com/dusk-network/piecrust/issues/350
[#324]: https://github.com/dusk-network/piecrust/issues/324
[#301]: https://github.com/dusk-network/piecrust/issues/301
[#271]: https://github.com/dusk-network/piecrust/issues/271
Expand Down
2 changes: 1 addition & 1 deletion piecrust-uplink/src/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ impl Write for ArgbufWriter {
return Err(fmt::Error);
}

state::with_arg_buf(|buf| {
state::with_arg_buf(|buf, _| {
buf[self.0..new_ofs].copy_from_slice(bytes);
});

Expand Down
4 changes: 2 additions & 2 deletions piecrust-uplink/src/abi/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ where
R: for<'a> Serialize<StandardBufSerializer<'a>>,
F: Fn(A) -> R,
{
with_arg_buf(|buf| {
with_arg_buf(|buf, _| {
let slice = &buf[..arg_len as usize];

let aa: &A::Archived = check_archived_root::<A>(slice)
Expand Down Expand Up @@ -60,7 +60,7 @@ where
R: for<'a> Serialize<StandardBufSerializer<'a>>,
F: Fn(A) -> R,
{
with_arg_buf(|buf| {
with_arg_buf(|buf, _| {
let slice = &buf[..arg_len as usize];

let aa: &A::Archived = unsafe { archived_root::<A>(slice) };
Expand Down
81 changes: 58 additions & 23 deletions piecrust-uplink/src/abi/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use alloc::vec::Vec;
use core::ptr;

use rkyv::{
Expand All @@ -15,31 +14,46 @@ use rkyv::{
};

use crate::{
ContractError, ContractId, StandardBufSerializer, CONTRACT_ID_BYTES,
SCRATCH_BUF_BYTES,
ContractError, ContractId, EconomicMode, RawResult, StandardBufSerializer,
CONTRACT_ID_BYTES, ECO_MODE_BUF_LEN, ECO_MODE_LEN, SCRATCH_BUF_BYTES,
};

pub mod arg_buf {
use crate::ARGBUF_LEN;

use crate::{EconomicMode, ARGBUF_LEN, ECO_MODE_BUF_LEN, ECO_MODE_LEN};
use core::ptr;
use core::slice;

#[no_mangle]
static mut A: [u64; ARGBUF_LEN / 8] = [0; ARGBUF_LEN / 8];

#[no_mangle]
static mut ECO_MODE: [u8; ECO_MODE_BUF_LEN] = [0u8; ECO_MODE_BUF_LEN];

pub fn with_arg_buf<F, R>(f: F) -> R
where
F: FnOnce(&mut [u8]) -> R,
F: FnOnce(&mut [u8], &mut [u8]) -> R,
{
unsafe {
let addr = ptr::addr_of_mut!(A);
let slice = slice::from_raw_parts_mut(addr as _, ARGBUF_LEN);
f(slice)
let addr_eco_mode = ptr::addr_of_mut!(ECO_MODE);
let slice_eco_mode =
slice::from_raw_parts_mut(addr_eco_mode as _, ECO_MODE_BUF_LEN);
f(slice, slice_eco_mode)
}
}

pub fn set_eco_mode(eco_mode: EconomicMode) {
unsafe {
let addr_eco_mode = ptr::addr_of_mut!(ECO_MODE);
let slice_eco_mode =
slice::from_raw_parts_mut(addr_eco_mode as _, ECO_MODE_LEN);
eco_mode.write(slice_eco_mode);
miloszm marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

pub(crate) use arg_buf::set_eco_mode;
pub(crate) use arg_buf::with_arg_buf;

mod ext {
Expand Down Expand Up @@ -73,7 +87,7 @@ where
Ret: Archive,
Ret::Archived: Deserialize<Ret, Infallible>,
{
let arg_len = with_arg_buf(|buf| {
let arg_len = with_arg_buf(|buf, _| {
let mut sbuf = [0u8; SCRATCH_BUF_BYTES];
let scratch = BufferScratch::new(&mut sbuf);
let ser = BufferSerializer::new(buf);
Expand All @@ -88,7 +102,7 @@ where

let ret_len = unsafe { ext::hq(name_ptr, name_len, arg_len) };

with_arg_buf(|buf| {
with_arg_buf(|buf, _| {
let slice = &buf[..ret_len as usize];
let ret = unsafe { archived_root::<Ret>(slice) };
ret.deserialize(&mut Infallible).expect("Infallible")
Expand Down Expand Up @@ -132,7 +146,7 @@ where
Ret: Archive,
Ret::Archived: Deserialize<Ret, Infallible>,
{
let arg_len = with_arg_buf(|buf| {
let arg_len = with_arg_buf(|buf, _| {
let mut sbuf = [0u8; SCRATCH_BUF_BYTES];
let scratch = BufferScratch::new(&mut sbuf);
let ser = BufferSerializer::new(buf);
Expand All @@ -155,7 +169,7 @@ where
)
};

with_arg_buf(|buf| {
with_arg_buf(|buf, _| {
if ret_len < 0 {
Err(ContractError::from_parts(ret_len, buf))
} else {
Expand All @@ -175,10 +189,26 @@ pub fn call_raw(
contract: ContractId,
fn_name: &str,
fn_arg: &[u8],
) -> Result<Vec<u8>, ContractError> {
) -> Result<RawResult, ContractError> {
call_raw_with_limit(contract, fn_name, fn_arg, 0)
}

/// Allows the contract to set allowance which will be used
/// to pay for the current call, under the condition that contract's
/// current balance is greater or equal to the allowance
/// and the allowance is sufficient to cover gas cost.
/// This call is of no consequence if the above conditions are not met.
pub fn set_allowance(allowance: u64) {
set_eco_mode(EconomicMode::Allowance(allowance));
}

/// Allows the contract to set charge which will be used
/// as a fee. If charge is greater than gas spent,
/// the difference will be added to contract's balance.
pub fn set_charge(charge: u64) {
set_eco_mode(EconomicMode::Charge(charge));
}

/// Calls the function with name `fn_name` of the given `contract` using
/// `fn_arg` as argument, allowing it to spend the given `gas_limit`.
///
Expand All @@ -192,8 +222,8 @@ pub fn call_raw_with_limit(
fn_name: &str,
fn_arg: &[u8],
gas_limit: u64,
) -> Result<Vec<u8>, ContractError> {
with_arg_buf(|buf| {
) -> Result<RawResult, ContractError> {
with_arg_buf(|buf, _| {
buf[..fn_arg.len()].copy_from_slice(fn_arg);
});

Expand All @@ -210,11 +240,16 @@ pub fn call_raw_with_limit(
)
};

with_arg_buf(|buf| {
with_arg_buf(|buf, eco_mode_buf| {
if ret_len < 0 {
Err(ContractError::from_parts(ret_len, buf))
} else {
Ok(buf[..ret_len as usize].to_vec())
Ok(RawResult::new(
buf[..ret_len as usize].to_vec(),
EconomicMode::read(
&eco_mode_buf[ECO_MODE_LEN..ECO_MODE_BUF_LEN],
),
))
}
})
}
Expand All @@ -234,7 +269,7 @@ where
unsafe {
match ext::hd(name, name_len) as usize {
0 => None,
arg_pos => Some(with_arg_buf(|buf| {
arg_pos => Some(with_arg_buf(|buf, _| {
let ret = archived_root::<D>(&buf[..arg_pos]);
ret.deserialize(&mut Infallible).expect("Infallible")
})),
Expand All @@ -249,7 +284,7 @@ pub fn owner<const N: usize>(contract: ContractId) -> Option<[u8; N]> {
unsafe {
match ext::owner(contract_id_ptr) {
0 => None,
_ => Some(with_arg_buf(|buf| {
_ => Some(with_arg_buf(|buf, _| {
let ret = archived_root::<[u8; N]>(&buf[..N]);
ret.deserialize(&mut Infallible).expect("Infallible")
})),
Expand All @@ -261,7 +296,7 @@ pub fn owner<const N: usize>(contract: ContractId) -> Option<[u8; N]> {
pub fn self_owner<const N: usize>() -> [u8; N] {
unsafe { ext::owner(ptr::null()) };

with_arg_buf(|buf| {
with_arg_buf(|buf, _| {
let ret = unsafe { archived_root::<[u8; N]>(&buf[..N]) };
ret.deserialize(&mut Infallible).expect("Infallible")
})
Expand All @@ -270,7 +305,7 @@ pub fn self_owner<const N: usize>() -> [u8; N] {
/// Return the current contract's id.
pub fn self_id() -> ContractId {
unsafe { ext::self_id() };
let id: ContractId = with_arg_buf(|buf| {
let id: ContractId = with_arg_buf(|buf, _| {
let ret =
unsafe { archived_root::<ContractId>(&buf[..CONTRACT_ID_BYTES]) };
ret.deserialize(&mut Infallible).expect("Infallible")
Expand All @@ -283,7 +318,7 @@ pub fn self_id() -> ContractId {
/// to be called.
pub fn caller() -> ContractId {
unsafe { ext::caller() };
with_arg_buf(|buf| {
with_arg_buf(|buf, _| {
let ret = unsafe {
archived_root::<ContractId>(
&buf[..core::mem::size_of::<Archived<ContractId>>()],
Expand All @@ -308,7 +343,7 @@ pub fn emit<D>(topic: &'static str, data: D)
where
for<'a> D: Serialize<StandardBufSerializer<'a>>,
{
with_arg_buf(|buf| {
with_arg_buf(|buf, _| {
let mut sbuf = [0u8; SCRATCH_BUF_BYTES];
let scratch = BufferScratch::new(&mut sbuf);
let ser = BufferSerializer::new(buf);
Expand All @@ -334,7 +369,7 @@ pub fn feed<D>(data: D)
where
for<'a> D: Serialize<StandardBufSerializer<'a>>,
{
with_arg_buf(|buf| {
with_arg_buf(|buf, _| {
let mut sbuf = [0u8; SCRATCH_BUF_BYTES];
let scratch = BufferScratch::new(&mut sbuf);
let ser = BufferSerializer::new(buf);
Expand Down
6 changes: 6 additions & 0 deletions piecrust-uplink/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,9 @@ pub const SCRATCH_BUF_BYTES: usize = 64;

/// The size of the argument buffer in bytes
pub const ARGBUF_LEN: usize = 64 * 1024;

/// The size of the economic mode buffer in bytes
pub const ECO_MODE_BUF_LEN: usize = ECO_MODE_LEN * 2;

/// Size of a single economic mode object
pub const ECO_MODE_LEN: usize = 9;
Loading