Skip to content

Commit

Permalink
feat: add transaction for adding full access key
Browse files Browse the repository at this point in the history
  • Loading branch information
aleksuss committed Oct 11, 2023
1 parent eccae2f commit e0a6e78
Show file tree
Hide file tree
Showing 11 changed files with 151 additions and 22 deletions.
18 changes: 8 additions & 10 deletions engine-sdk/src/near_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,16 +409,14 @@ impl crate::promise::PromiseHandler for Runtime {
});
}
PromiseAction::AddFullAccessKey { public_key, nonce } => {
feature_gated!("all-promise-actions", {
let pk: RawPublicKey = public_key.into();
let pk_bytes = pk.as_bytes();
exports::promise_batch_action_add_key_with_full_access(
id,
pk_bytes.len() as _,
pk_bytes.as_ptr() as _,
*nonce,
);
});
let pk: RawPublicKey = public_key.into();
let pk_bytes = pk.as_bytes();
exports::promise_batch_action_add_key_with_full_access(
id,
pk_bytes.len() as _,
pk_bytes.as_ptr() as _,
*nonce,
);
}
PromiseAction::AddFunctionCallKey {
public_key,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crate::utils::workspace::deploy_engine;
use aurora_engine_types::parameters::engine::{RelayerKeyArgs, RelayerKeyManagerArgs};
use aurora_engine_types::parameters::engine::{
FullAccessKeyArgs, RelayerKeyArgs, RelayerKeyManagerArgs, SetUpgradeDelayBlocksArgs,
};
use aurora_engine_types::public_key::PublicKey;
use aurora_engine_types::types::Address;
use aurora_engine_workspace::parse_near;
Expand Down Expand Up @@ -275,6 +277,62 @@ async fn test_call_not_allowed_contract() {
assert_error_message(&err, "unable to broadcast the transaction to the network");
}

#[tokio::test]
async fn test_attach_full_access_key() {
let aurora = deploy_engine().await;
let secret_key = SecretKey::from_random(KeyType::ED25519);
let public_key = public_key(&secret_key);
let admin = aurora.create_account(&aurora.id(), secret_key);

let err = admin
.call(&aurora.id(), "set_upgrade_delay_blocks")
.args_borsh(SetUpgradeDelayBlocksArgs {
upgrade_delay_blocks: 5,
})
.max_gas()
.transact()
.await;
assert_error_message(&err, "Failed to query access key");

let result = aurora
.attach_full_access_key(FullAccessKeyArgs { public_key })
.max_gas()
.transact()
.await
.unwrap();
assert!(result.is_success());

let result = admin
.call(&aurora.id(), "set_upgrade_delay_blocks")
.args_borsh(SetUpgradeDelayBlocksArgs {
upgrade_delay_blocks: 5,
})
.max_gas()
.transact()
.await
.unwrap();
assert!(result.is_success()); // because owner_account_id == current_account_id

// Change the owner
let result = aurora
.set_owner(&"some_owner.root".parse().unwrap())
.max_gas()
.transact()
.await
.unwrap();
assert!(result.is_success());

let err = admin
.call(&aurora.id(), "set_upgrade_delay_blocks")
.args_borsh(SetUpgradeDelayBlocksArgs {
upgrade_delay_blocks: 5,
})
.max_gas()
.transact()
.await;
assert_error_message(&err, "ERR_NOT_ALLOWED");
}

fn public_key(sk: &SecretKey) -> PublicKey {
let pk_str = serde_json::to_string(&sk.public_key()).unwrap();
PublicKey::from_str(pk_str.trim_matches('"')).unwrap()
Expand Down
2 changes: 1 addition & 1 deletion engine-tests/src/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod access_keys;
mod account_id_precompiles;
mod contract_call;
mod ecrecover;
Expand All @@ -16,7 +17,6 @@ mod pause_contract;
mod prepaid_gas_precompile;
mod promise_results_precompile;
mod random;
mod relayer_keys;
mod repro;
pub mod sanity;
mod self_destruct_state;
Expand Down
2 changes: 1 addition & 1 deletion engine-tests/src/tests/sanity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ fn test_num_wasm_functions() {
let module = walrus::ModuleConfig::default()
.parse(runner.code.code())
.unwrap();
let expected_number = 1524;
let expected_number = 1550;
let actual_number = module.funcs.iter().count();

assert!(
Expand Down
2 changes: 2 additions & 0 deletions engine-types/src/parameters/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,8 @@ pub struct RelayerKeyArgs {
pub public_key: PublicKey,
}

pub type FullAccessKeyArgs = RelayerKeyArgs;

pub mod errors {
use crate::{account_id::ParseAccountError, String, ToString};

Expand Down
3 changes: 2 additions & 1 deletion engine-workspace/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ impl Account {

pub fn public_key(&self) -> anyhow::Result<PublicKey> {
let pk = self.inner.secret_key().public_key();
PublicKey::from_str(&serde_json::to_string(&pk)?).map_err(|e| anyhow::anyhow!("{e:?}"))
PublicKey::from_str(serde_json::to_string(&pk)?.trim_matches('"'))
.map_err(|e| anyhow::anyhow!("{e:?}"))
}
}
19 changes: 14 additions & 5 deletions engine-workspace/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use crate::account::Account;
use crate::node::Node;
use crate::operation::{
CallAddEntryToWhitelist, CallAddEntryToWhitelistBatch, CallAddRelayerKey, CallCall,
CallDeployCode, CallDeployErc20Token, CallDeployUpgrade, CallDeposit,
CallFactorySetWNearAddress, CallFactoryUpdate, CallFactoryUpdateAddressVersion,
CallAddEntryToWhitelist, CallAddEntryToWhitelistBatch, CallAddRelayerKey,
CallAttachFullAccessKey, CallCall, CallDeployCode, CallDeployErc20Token, CallDeployUpgrade,
CallDeposit, CallFactorySetWNearAddress, CallFactoryUpdate, CallFactoryUpdateAddressVersion,
CallFtOnTransfer, CallFtTransfer, CallFtTransferCall, CallFundXccSubAccount, CallMintAccount,
CallMirrorErc20Token, CallNew, CallNewEthConnector, CallPauseContract, CallPausePrecompiles,
CallRefundOnError, CallRegisterRelayer, CallRemoveEntryFromWhitelist, CallRemoveRelayerKey,
CallResumeContract, CallResumePrecompiles, CallSetErc20Metadata,
CallSetEthConnectorContractAccount, CallSetEthConnectorContractData, CallSetFixedGasCost,
CallSetKeyManager, CallSetPausedFlags, CallSetSiloParams, CallSetWhitelistStatus,
CallSetKeyManager, CallSetOwner, CallSetPausedFlags, CallSetSiloParams, CallSetWhitelistStatus,
CallStageUpgrade, CallStateMigration, CallStorageDeposit, CallStorageUnregister,
CallStorageWithdraw, CallSubmit, CallWithdraw, ViewAccountsCounter, ViewBalance, ViewBlockHash,
ViewBridgeProver, ViewChainId, ViewCode, ViewErc20FromNep141, ViewFactoryWnearAddress,
Expand All @@ -27,7 +27,8 @@ use aurora_engine_types::parameters::connector::{
SetErc20MetadataArgs, SetEthConnectorContractAccountArgs, WithdrawSerializeType,
};
use aurora_engine_types::parameters::engine::{
CallArgs, FunctionCallArgsV2, NewCallArgs, NewCallArgsV2, RelayerKeyArgs, RelayerKeyManagerArgs,
CallArgs, FullAccessKeyArgs, FunctionCallArgsV2, NewCallArgs, NewCallArgsV2, RelayerKeyArgs,
RelayerKeyManagerArgs,
};
use aurora_engine_types::parameters::silo::{
FixedGasCostArgs, SiloParamsArgs, WhitelistArgs, WhitelistKindArgs, WhitelistStatusArgs,
Expand Down Expand Up @@ -352,6 +353,14 @@ impl EngineContract {
pub fn set_erc20_metadata(&self, metadata: SetErc20MetadataArgs) -> CallSetErc20Metadata {
CallSetErc20Metadata::call(&self.contract).args_json(metadata)
}

pub fn attach_full_access_key(&self, args: FullAccessKeyArgs) -> CallAttachFullAccessKey {
CallAttachFullAccessKey::call(&self.contract).args_json(args)
}

pub fn set_owner(&self, account: &AccountId) -> CallSetOwner {
CallSetOwner::call(&self.contract).args_borsh(account)
}
}

/// View functions
Expand Down
10 changes: 8 additions & 2 deletions engine-workspace/src/operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ impl_call_return![
CallFactoryUpdateAddressVersion,
Call::FactoryUpdateAddressVersion
),
(CallSetOwner, Call::SetOwner),
(CallRegisterRelayer, Call::RegisterRelayer),
(CallRefundOnError, Call::RefundOnError),
(CallFactoryUpdate, Call::FactoryUpdate),
Expand Down Expand Up @@ -56,7 +57,8 @@ impl_call_return![
(CallAddEntryToWhitelist, Call::AddEntryToWhitelist),
(CallAddEntryToWhitelistBatch, Call::AddEntryToWhitelistBatch),
(CallRemoveEntryFromWhitelist, Call::RemoveEntryFromWhitelist),
(CallSetErc20Metadata, Call::SetErc20Metadata)
(CallSetErc20Metadata, Call::SetErc20Metadata),
(CallAttachFullAccessKey, Call::AttachFullAccessKey)
];

impl_call_return![
Expand All @@ -79,7 +81,7 @@ impl_view_return![
(ViewStorageBalanceOf => StorageBalance, View::StorageBalanceOf, json),
(ViewFtMetadata => FungibleTokenMetadata, View::FtMetadata, json),
(ViewVersion => String, View::Version, borsh),
(ViewOwner => AccountId, View::Owner, borsh),
(ViewOwner => AccountId, View::Owner, from_bytes),
(ViewBridgeProver => AccountId, View::BridgeProver, borsh),
(ViewChainId => U256, View::ChainId, borsh_U256),
(ViewUpgradeIndex => u64, View::UpgradeIndex, borsh),
Expand Down Expand Up @@ -116,6 +118,7 @@ pub(crate) enum Call {
MirrorErc20Token,
Call,
Submit,
SetOwner,
RegisterRelayer,
FtOnTransfer,
Withdraw,
Expand Down Expand Up @@ -151,6 +154,7 @@ pub(crate) enum Call {
AddEntryToWhitelistBatch,
RemoveEntryFromWhitelist,
SetErc20Metadata,
AttachFullAccessKey,
}

impl AsRef<str> for Call {
Expand All @@ -163,6 +167,7 @@ impl AsRef<str> for Call {
Call::MirrorErc20Token => "mirror_erc20_token",
Call::Call => "call",
Call::Submit => "submit",
Call::SetOwner => "set_owner",
Call::RegisterRelayer => "register_relayer",
Call::FtOnTransfer => "ft_on_transfer",
Call::Withdraw => "withdraw",
Expand Down Expand Up @@ -198,6 +203,7 @@ impl AsRef<str> for Call {
Call::AddEntryToWhitelistBatch => "add_entry_to_whitelist_batch",
Call::RemoveEntryFromWhitelist => "remove_entry_from_whitelist",
Call::SetErc20Metadata => "set_erc20_metadata",
Call::AttachFullAccessKey => "attach_full_access_key",
}
}
}
Expand Down
14 changes: 14 additions & 0 deletions engine-workspace/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use aurora_engine_types::types::Address;
use aurora_engine_types::{H256, U256};
use near_sdk::{json_types::U128, PromiseOrValue};
use serde::de::DeserializeOwned;
use std::fmt::Debug;
use workspaces::result::{ExecutionFinalResult, ExecutionOutcome, ViewResultDetails};
use workspaces::types::Gas;

Expand Down Expand Up @@ -63,6 +64,19 @@ impl ViewResult<H256> {
}
}

impl<T> ViewResult<T>
where
T: for<'a> TryFrom<&'a [u8]>,
{
pub fn from_bytes(view: ViewResultDetails) -> anyhow::Result<Self> {
Ok(Self {
result: T::try_from(view.result.as_slice())
.map_err(|_| anyhow::anyhow!("couldn't create T from bytes"))?,
logs: view.logs,
})
}
}

#[derive(Debug)]
pub struct ExecutionResult<T> {
inner: workspaces::result::ExecutionSuccess,
Expand Down
30 changes: 30 additions & 0 deletions engine/src/contract_methods/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use aurora_engine_sdk::{
io::{StorageIntermediate, IO},
promise::PromiseHandler,
};
use aurora_engine_types::parameters::engine::FullAccessKeyArgs;
use aurora_engine_types::{
borsh::BorshDeserialize,
parameters::{
Expand Down Expand Up @@ -426,6 +427,35 @@ pub fn get_latest_hashchain<I: IO>(io: &mut I) -> Result<(), ContractError> {
Ok(())
}

pub fn attach_full_access_key<I: IO + Copy, E: Env, H: PromiseHandler>(
io: I,
env: &E,
handler: &mut H,
) -> Result<(), ContractError> {
let state = state::get_state(&io)?;

require_running(&state)?;
require_owner_only(&state, &env.predecessor_account_id())?;

let public_key = serde_json::from_slice::<FullAccessKeyArgs>(&io.read_input().to_vec())
.map(|args| args.public_key)
.map_err(|_| errors::ERR_JSON_DESERIALIZE)?;
let current_account_id = env.current_account_id();
let action = PromiseAction::AddFullAccessKey {
public_key,
nonce: 0, // not actually used - depends on block height
};
let promise = PromiseBatchAction {
target_account_id: current_account_id,
actions: vec![action],
};
let promise_id = unsafe { handler.promise_create_batch(&promise) };

handler.promise_return(promise_id);

Ok(())
}

fn internal_get_upgrade_index<I: IO>(io: &I) -> Result<u64, ContractError> {
match io.read_u64(&storage::bytes_to_key(KeyPrefix::Config, CODE_STAGE_KEY)) {
Ok(index) => Ok(index),
Expand Down
13 changes: 12 additions & 1 deletion engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -452,8 +452,19 @@ mod contract {
.sdk_unwrap();
}

/// Attach a full access key.
#[no_mangle]
pub extern "C" fn attach_full_access_key() {
let io = Runtime;
let env = Runtime;
let mut handler = Runtime;
contract_methods::admin::attach_full_access_key(io, &env, &mut handler)
.map_err(ContractError::msg)
.sdk_unwrap();
}

///
/// NONMUTATIVE METHODS
/// READ-ONLY METHODS
///
#[no_mangle]
pub extern "C" fn view() {
Expand Down

0 comments on commit e0a6e78

Please sign in to comment.