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 CAP-58 (constructor support) #1447

Merged
merged 7 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 1 addition & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ wasmparser = "=0.116.1"
# NB: When updating, also update the version in rs-soroban-env dev-dependencies
[workspace.dependencies.stellar-xdr]
version = "=21.2.0"
# git = "https://github.com/stellar/rs-stellar-xdr"
# rev = "d0138770652a615e3cd99447f2f2727658c17450"
git = "https://github.com/stellar/rs-stellar-xdr"
rev = "953ad1c6103146121871a3e2fa5aaca3d6256891"
default-features = false

[workspace.dependencies.wasmi]
Expand All @@ -47,7 +47,8 @@ rev = "122a74a7c491929e5ac9de876099154ef7c06d06"
features = ["no-hash-maps"]

# [patch."https://github.com/stellar/rs-stellar-xdr"]
# stellar-xdr = { path = "../rs-stellar-xdr/" }
# [patch.crates-io]
# stellar-xdr = { path = "../rs-stellar-xdr" }
# [patch."https://github.com/stellar/wasmi"]
# soroban-wasmi = { path = "../wasmi/crates/wasmi/" }
# soroban-wasmi_core = { path = "../wasmi/crates/core/" }
Expand Down
25 changes: 25 additions & 0 deletions soroban-env-common/env.json
Original file line number Diff line number Diff line change
Expand Up @@ -1489,6 +1489,31 @@
"return": "Void",
"docs": "If the TTL for the provided contract's code (if applicable) is below `threshold` ledgers, extend `live_until_ledger_seq` such that TTL == `extend_to`, where TTL is defined as live_until_ledger_seq - current ledger. If attempting to extend past the maximum allowed value (defined as the current ledger + `max_entry_ttl` - 1), the new `live_until_ledger_seq` will be clamped to the max.",
"min_supported_protocol": 21
},
{
"export": "e",
"name": "create_contract_with_constructor",
"args": [
{
"name": "deployer",
"type": "AddressObject"
},
{
"name": "wasm_hash",
"type": "BytesObject"
},
{
"name": "salt",
"type": "BytesObject"
},
{
"name": "constructor_args",
"type": "VecObject"
}
],
"return": "AddressObject",
"docs": "Creates the contract instance on behalf of `deployer`. Created contract must be created from a Wasm that has a constructor. `deployer` must authorize this call via Soroban auth framework, i.e. this calls `deployer.require_auth` with respective arguments. `wasm_hash` must be a hash of the contract code that has already been uploaded on this network. `salt` is used to create a unique contract id. `constructor_args` are forwarded into created contract's constructor (`__constructor`) function. Returns the address of the created contract.",
"min_supported_protocol": 22
}
]
},
Expand Down
6 changes: 3 additions & 3 deletions soroban-env-host/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,14 @@ p256 = {version = "0.13.2", default-features = false, features = ["alloc"]}

[dev-dependencies.stellar-xdr]
version = "=21.2.0"
# git = "https://github.com/stellar/rs-stellar-xdr"
# rev = "d0138770652a615e3cd99447f2f2727658c17450"
git = "https://github.com/stellar/rs-stellar-xdr"
rev = "953ad1c6103146121871a3e2fa5aaca3d6256891"
default-features = false
features = ["arbitrary"]

[features]
testutils = ["soroban-env-common/testutils", "recording_mode", "dep:backtrace"]
next = ["soroban-env-common/next"]
next = ["soroban-env-common/next", "stellar-xdr/next"]
tracy = ["dep:tracy-client", "soroban-env-common/tracy"]
recording_mode = []
bench = []
Expand Down
28 changes: 15 additions & 13 deletions soroban-env-host/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,10 @@ use crate::{
},
host_object::HostVec,
xdr::{
ContractDataEntry, CreateContractArgs, HashIdPreimage, HashIdPreimageSorobanAuthorization,
InvokeContractArgs, LedgerEntry, LedgerEntryData, LedgerEntryExt, ScAddress, ScErrorCode,
ScErrorType, ScNonceKey, ScVal, SorobanAuthorizationEntry, SorobanAuthorizedFunction,
SorobanCredentials,
ContractDataEntry, CreateContractArgsV2, HashIdPreimage,
HashIdPreimageSorobanAuthorization, InvokeContractArgs, LedgerEntry, LedgerEntryData,
LedgerEntryExt, ScAddress, ScErrorCode, ScErrorType, ScNonceKey, ScVal,
SorobanAuthorizationEntry, SorobanAuthorizedFunction, SorobanCredentials,
},
AddressObject, Compare, Host, HostError, Symbol, TryFromVal, TryIntoVal, Val, VecObject,
};
Expand Down Expand Up @@ -480,7 +480,7 @@ pub(crate) struct InvokerContractAuthorizationTracker {
#[derive(Clone, Hash)]
pub(crate) enum AuthStackFrame {
Contract(ContractInvocation),
CreateContractHostFn(CreateContractArgs),
CreateContractHostFn(CreateContractArgsV2),
}

#[derive(Clone, Hash)]
Expand All @@ -499,7 +499,7 @@ pub(crate) struct ContractFunction {
#[derive(Clone, Hash)]
pub(crate) enum AuthorizedFunction {
ContractFn(ContractFunction),
CreateContractHostFn(CreateContractArgs),
CreateContractHostFn(CreateContractArgsV2),
}

// A single node in the authorized invocation tree.
Expand Down Expand Up @@ -602,7 +602,10 @@ impl AuthorizedFunction {
args: host.scvals_to_val_vec(xdr_contract_fn.args.as_slice())?,
})
}
SorobanAuthorizedFunction::CreateContractHostFn(xdr_args) => {
SorobanAuthorizedFunction::CreateContractHostFn(_) => {
return Err(host.err(ScErrorType::Auth, ScErrorCode::InvalidInput, "SorobanAuthorizedFunction::CreateContractHostFn is deprecated in authorization payloads. Please use SorobanAuthorizedFunction::CreateContractHostFnV2 instead.", &[]));
sisuresh marked this conversation as resolved.
Show resolved Hide resolved
}
SorobanAuthorizedFunction::CreateContractV2HostFn(xdr_args) => {
AuthorizedFunction::CreateContractHostFn(xdr_args)
}
})
Expand All @@ -620,7 +623,7 @@ impl AuthorizedFunction {
}))
}
AuthorizedFunction::CreateContractHostFn(create_contract_args) => {
Ok(SorobanAuthorizedFunction::CreateContractHostFn(
Ok(SorobanAuthorizedFunction::CreateContractV2HostFn(
create_contract_args.metered_clone(host)?,
))
}
Expand Down Expand Up @@ -1265,9 +1268,9 @@ impl AuthorizationManager {
pub(crate) fn push_create_contract_host_fn_frame(
&self,
host: &Host,
args: CreateContractArgs,
args: CreateContractArgsV2,
) -> Result<(), HostError> {
Vec::<CreateContractArgs>::charge_bulk_init_cpy(1, host)?;
Vec::<CreateContractArgsV2>::charge_bulk_init_cpy(1, host)?;
self.try_borrow_call_stack_mut(host)?
.push(AuthStackFrame::CreateContractHostFn(args));
self.push_tracker_frame(host)
Expand Down Expand Up @@ -2251,7 +2254,7 @@ impl Host {
}

#[cfg(any(test, feature = "testutils"))]
use crate::{host::frame::ContractReentryMode, xdr::SorobanAuthorizedInvocation};
use crate::{host::frame::CallParams, xdr::SorobanAuthorizedInvocation};

#[cfg(any(test, feature = "testutils"))]
impl Host {
Expand All @@ -2272,8 +2275,7 @@ impl Host {
&contract_id,
ACCOUNT_CONTRACT_CHECK_AUTH_FN_NAME.try_into_val(self)?,
args_vec.as_slice(),
ContractReentryMode::Prohibited,
true,
CallParams::default_internal_call(),
);
if let Err(e) = &res {
self.error(
Expand Down
50 changes: 38 additions & 12 deletions soroban-env-host/src/builtin_contracts/account_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ use crate::{
contract_error::ContractError,
},
err,
host::{frame::ContractReentryMode, Host},
host::{
frame::{CallParams, ContractReentryMode},
Host,
},
xdr::{
self, AccountId, ContractIdPreimage, Hash, ScErrorCode, ScErrorType, ThresholdIndexes,
Uint256,
Expand Down Expand Up @@ -42,9 +45,18 @@ pub(crate) struct CreateContractHostFnContext {

#[derive(Clone)]
#[contracttype]
enum AuthorizationContext {
pub(crate) struct CreateContractWithConstructorHostFnContext {
pub(crate) executable: ContractExecutable,
pub(crate) salt: BytesN<32>,
pub(crate) constructor_args: HostVec,
}

#[derive(Clone)]
#[contracttype]
pub(crate) enum AuthorizationContext {
Contract(ContractAuthorizationContext),
CreateContractHostFn(CreateContractHostFnContext),
CreateContractWithCtorHostFn(CreateContractWithConstructorHostFnContext),
}

#[derive(Clone)]
Expand Down Expand Up @@ -90,12 +102,23 @@ impl AuthorizationContext {
&[],
)),
};
Ok(AuthorizationContext::CreateContractHostFn(
CreateContractHostFnContext {
executable: ContractExecutable::Wasm(wasm_hash),
salt,
},
))
if args.constructor_args.is_empty() {
Ok(AuthorizationContext::CreateContractHostFn(
CreateContractHostFnContext {
executable: ContractExecutable::Wasm(wasm_hash),
salt,
},
))
} else {
let args_vec = host.scvals_to_val_vec(&args.constructor_args.as_slice())?;
Ok(AuthorizationContext::CreateContractWithCtorHostFn(
CreateContractWithConstructorHostFnContext {
executable: ContractExecutable::Wasm(wasm_hash),
salt,
constructor_args: args_vec.try_into_val(host)?,
},
))
}
}
}
}
Expand Down Expand Up @@ -133,10 +156,13 @@ pub(crate) fn check_account_contract_auth(
account_contract,
ACCOUNT_CONTRACT_CHECK_AUTH_FN_NAME.try_into_val(host)?,
&[payload_obj.into(), signature, auth_context_vec.into()],
// Allow self reentry for this function in order to be able to do
// wallet admin ops using the auth framework itself.
ContractReentryMode::SelfAllowed,
true,
CallParams {
// Allow self reentry for this function in order to be able to do
// wallet admin ops using the auth framework itself.
reentry_mode: ContractReentryMode::SelfAllowed,
internal_host_call: true,
treat_missing_function_as_noop: false,
},
)?
.try_into()?)
}
Expand Down
9 changes: 9 additions & 0 deletions soroban-env-host/src/builtin_contracts/base_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,15 @@ impl TryFromVal<Host, Val> for Address {
}
}

impl TryFromVal<Host, ScAddress> for Address {
type Error = HostError;

fn try_from_val(env: &Host, addr: &ScAddress) -> Result<Self, Self::Error> {
let obj = env.add_host_object(addr.clone())?;
Address::try_from_val(env, &obj)
}
}

impl TryFromVal<Host, Address> for Val {
type Error = HostError;

Expand Down
41 changes: 38 additions & 3 deletions soroban-env-host/src/builtin_contracts/invoker_contract_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@ use crate::{
auth::{AuthorizedFunction, AuthorizedInvocation, ContractFunction},
budget::AsBudget,
builtin_contracts::{
account_contract::{ContractAuthorizationContext, CreateContractHostFnContext},
account_contract::{
ContractAuthorizationContext, CreateContractHostFnContext,
CreateContractWithConstructorHostFnContext,
},
base_types::Vec as ContractTypeVec,
common_types::ContractExecutable,
},
host::metered_clone::{MeteredClone, MeteredContainer},
host_object::HostVec,
xdr::{
self, ContractIdPreimage, ContractIdPreimageFromAddress, CreateContractArgs, ScAddress,
self, ContractIdPreimage, ContractIdPreimageFromAddress, CreateContractArgsV2, ScAddress,
ScErrorCode, ScErrorType,
},
Host, HostError, TryFromVal, TryIntoVal, Val,
Expand All @@ -32,6 +35,7 @@ pub(crate) struct SubContractInvocation {
pub(crate) enum InvokerContractAuthEntry {
Contract(SubContractInvocation),
CreateContractHostFn(CreateContractHostFnContext),
CreateContractWithCtorHostFn(CreateContractWithConstructorHostFnContext),
}

// metering: covered
Expand Down Expand Up @@ -84,7 +88,7 @@ impl InvokerContractAuthEntry {
));
}
};
let function = AuthorizedFunction::CreateContractHostFn(CreateContractArgs {
let function = AuthorizedFunction::CreateContractHostFn(CreateContractArgsV2 {
contract_id_preimage: ContractIdPreimage::Address(
ContractIdPreimageFromAddress {
address: invoker_contract_addr.metered_clone(host)?,
Expand All @@ -95,6 +99,37 @@ impl InvokerContractAuthEntry {
},
),
executable: xdr::ContractExecutable::Wasm(wasm_hash),
constructor_args: Default::default(),
});
Ok(AuthorizedInvocation::new(function, vec![]))
}
InvokerContractAuthEntry::CreateContractWithCtorHostFn(create_contract_fn) => {
let wasm_hash = match &create_contract_fn.executable {
ContractExecutable::Wasm(b) => {
host.hash_from_bytesobj_input("wasm_ref", b.as_object())?
}
ContractExecutable::StellarAsset => {
return Err(host.err(
ScErrorType::Auth,
ScErrorCode::InternalError,
"unexpected authorized StellarAsset contract creation",
&[],
));
}
};
let function = AuthorizedFunction::CreateContractHostFn(CreateContractArgsV2 {
contract_id_preimage: ContractIdPreimage::Address(
ContractIdPreimageFromAddress {
address: invoker_contract_addr.metered_clone(host)?,
salt: host.u256_from_bytesobj_input(
"salt",
create_contract_fn.salt.as_object(),
)?,
},
),
executable: xdr::ContractExecutable::Wasm(wasm_hash),
constructor_args: host
.vecobject_to_scval_vec(create_contract_fn.constructor_args.as_object())?,
});
Ok(AuthorizedInvocation::new(function, vec![]))
}
Expand Down
7 changes: 6 additions & 1 deletion soroban-env-host/src/cost_runner/cost_types/invoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,12 @@ impl CostRunner for InvokeVmFunctionRun {
let rv = black_box(
sample
.0
.metered_func_call(host, &sym, sample.1.as_slice())
.metered_func_call(
host,
&sym,
sample.1.as_slice(),
/* treat_missing_function_as_noop */ false,
)
.unwrap(),
);
(Some(rv), sample)
Expand Down
14 changes: 12 additions & 2 deletions soroban-env-host/src/cost_runner/cost_types/wasm_insn_exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,12 @@ macro_rules! impl_wasm_insn_runner {
let rv = black_box(
sample
.vm
.invoke_function_raw(host, &TEST_SYM, &[])
.invoke_function_raw(
host,
&TEST_SYM,
&[],
/* treat_missing_function_as_noop */ false,
)
.unwrap_or_default(),
);
(Some(rv), sample)
Expand All @@ -234,7 +239,12 @@ macro_rules! impl_wasm_insn_runner {
let rv = black_box(
base_sample
.vm
.invoke_function_raw(host, &TEST_SYM, &[])
.invoke_function_raw(
host,
&TEST_SYM,
&[],
/* treat_missing_function_as_noop */ false,
)
.unwrap_or_default(),
);
(Some(rv), base_sample)
Expand Down
Loading