Skip to content

Commit

Permalink
Implementation of CAP-58 - constructor support for Soroban.
Browse files Browse the repository at this point in the history
The implementation itself is fairly simple (thanks to not needing to support v21 semantics) and follows the CAP. It only has a few caveats:

- Pre-v22 protocol Wasms are treated as if they don't have a constructor (they shouldn't have it anyway, but just in case they do we ignore it in order to not break the contract semantics). Thus we don't need to even try calling constructor for them
- We try to call constructor for all v22+ contracts, so we charge for VM instantiation, which increases the creation cost to some degree. I'm not sure if we can discount calling non-existent functions; if we find that necessary, we can still improve this before the protocol release.

Bulk of this change is tests, and testing is really not trivial as we want to cover a set product of several different options:
- p21 vs p22 contracts
- v1 vs v2 host function
- Constructor return values and errors
- constructor arguments present/not present/'default' constructor
- auth for constructor itself and inside the constructor
- deployer support
- invoker auth support
- custom account support

To make things worse, a contract may only have a single constructor, so this needed a lot of new test Wasms.

I'm sure I haven't covered every possible combination, but at least tried to have some basic coverage for most of the cases and most obvious combinations.
  • Loading branch information
dmkozh committed Aug 21, 2024
1 parent 81a4239 commit d37e8c5
Show file tree
Hide file tree
Showing 51 changed files with 2,394 additions and 390 deletions.
20 changes: 16 additions & 4 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
2 changes: 1 addition & 1 deletion soroban-env-host/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ 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.", &[]));
}
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),
CreateContractV2HostFn(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::CreateContractV2HostFn(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
Loading

0 comments on commit d37e8c5

Please sign in to comment.