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

GH-2463: Provide smart contract access to associated keys that signed a deploy #2468

Merged
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
40 changes: 32 additions & 8 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions execution_engine/src/core/resolvers/v1_function_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub(crate) enum FunctionIndex {
DictionaryGetFuncIndex,
DictionaryPutFuncIndex,
LoadCallStack,
LoadAuthorizationKeys,
}

impl From<FunctionIndex> for usize {
Expand Down
4 changes: 4 additions & 0 deletions execution_engine/src/core/resolvers/v1_resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,10 @@ impl ModuleImportResolver for RuntimeModuleImportResolver {
Signature::new(&[ValueType::I32; 1][..], Some(ValueType::I32)),
FunctionIndex::NewDictionaryFuncIndex.into(),
),
"casper_load_authorization_keys" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], Some(ValueType::I32)),
FunctionIndex::LoadAuthorizationKeys.into(),
),
_ => {
return Err(InterpreterError::Function(format!(
"host module doesn't export function with name {}",
Expand Down
11 changes: 11 additions & 0 deletions execution_engine/src/core/runtime/externals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -993,6 +993,17 @@ where
let ret = self.load_call_stack(call_stack_len_ptr, result_size_ptr)?;
Ok(Some(RuntimeValue::I32(api_error::i32_from(ret))))
}
FunctionIndex::LoadAuthorizationKeys => {
// args(0) (Output) Pointer to number of authorization keys.
// args(1) (Output) Pointer to size in bytes of the total bytes.
let (len_ptr, result_size_ptr) = Args::parse(args)?;
self.charge_host_function_call(
&HostFunction::fixed(10_000),
[len_ptr, result_size_ptr],
)?;
let ret = self.load_authorization_keys(len_ptr, result_size_ptr)?;
Ok(Some(RuntimeValue::I32(api_error::i32_from(ret))))
}
}
}
}
42 changes: 41 additions & 1 deletion execution_engine/src/core/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::{
cmp,
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
convert::TryFrom,
iter::IntoIterator,
iter::{FromIterator, IntoIterator},
};

use itertools::Itertools;
Expand Down Expand Up @@ -3650,6 +3650,46 @@ where
}
}
}

fn load_authorization_keys(
&mut self,
len_ptr: u32,
result_size_ptr: u32,
) -> Result<Result<(), ApiError>, Trap> {
if !self.can_write_to_host_buffer() {
// Exit early if the host buffer is already occupied
return Ok(Err(ApiError::HostBufferFull));
}

// A set of keys is converted into a vector so it can be written to a host buffer
let authorization_keys =
Vec::from_iter(self.context.authorization_keys().clone().into_iter());

let total_keys = authorization_keys.len() as u32;
let total_keys_bytes = total_keys.to_le_bytes();
Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't we be using to_bytes() instead? It will call to_le_bytes() on u32 as well but we would be using a higher-level API that we had defined ourselves.

Copy link
Collaborator Author

@mpapierski mpapierski Dec 15, 2021

Choose a reason for hiding this comment

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

Currently, bytesrepr represents u32 as four little-endian bytes, but it may not be the case in the future. The intention is to write u32 as LE bytes under a pointer, rather than 'ABI serialized u32 integer', which is different (and more expensive). This approach also saves us from calling bytesrepr::deserialize on this memory.

Copy link
Contributor

Choose a reason for hiding this comment

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

So what are the rules about this? When do we choose ToBytes/FromBytes and when we do not?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

When you need to pass a single value of a type statically known on the Wasm side like a pointer to u32, then write to_le_bytes(), but if you need something more complex like Vec<AccountHash>, you should consider bytesrepr. Historically we weren't always careful, and we overused bytesrepr a lot on the Wasm side, but I hope to address this in 2.0 - for now, I'm trying to stay consistent and pass plain values as LE bytes

if let Err(error) = self.memory.set(len_ptr, &total_keys_bytes) {
return Err(Error::Interpreter(error.into()).into());
}

if total_keys == 0 {
// No need to do anything else, we leave host buffer empty.
return Ok(Ok(()));
}

let authorization_keys = CLValue::from_t(authorization_keys).map_err(Error::CLValue)?;

let length = authorization_keys.inner_bytes().len() as u32;
if let Err(error) = self.write_host_buffer(authorization_keys) {
return Ok(Err(error));
}

let length_bytes = length.to_le_bytes();
if let Err(error) = self.memory.set(result_size_ptr, &length_bytes) {
return Err(Error::Interpreter(error.into()).into());
}

Ok(Ok(()))
}
}

#[cfg(test)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,24 @@ use casper_types::{
RuntimeArgs, U512,
};

const CONTRACT_ADD_ASSOCIATED_KEY: &str = "add_associated_key.wasm";
const CONTRACT_ADD_UPDATE_ASSOCIATED_KEY: &str = "add_update_associated_key.wasm";
const CONTRACT_AUTHORIZED_KEYS: &str = "authorized_keys.wasm";
const CONTRACT_SET_ACTION_THRESHOLDS: &str = "set_action_thresholds.wasm";
const ARG_KEY_MANAGEMENT_THRESHOLD: &str = "key_management_threshold";
const ARG_DEPLOY_THRESHOLD: &str = "deploy_threshold";
const ARG_ACCOUNT: &str = "account";
const ARG_WEIGHT: &str = "weight";
const KEY_1: AccountHash = AccountHash::new([254; 32]);
const KEY_2: AccountHash = AccountHash::new([253; 32]);
const KEY_2_WEIGHT: Weight = Weight::new(100);
const KEY_3: AccountHash = AccountHash::new([252; 32]);

#[ignore]
#[test]
fn should_deploy_with_authorized_identity_key() {
let exec_request = ExecuteRequestBuilder::standard(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(1),
ARG_DEPLOY_THRESHOLD => Weight::new(1),
Expand All @@ -54,7 +57,7 @@ fn should_raise_auth_failure_with_invalid_key() {
.with_address(*DEFAULT_ACCOUNT_ADDR)
.with_empty_payment_bytes(runtime_args! { ARG_AMOUNT => *DEFAULT_PAYMENT, })
.with_session_code(
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(1),
ARG_DEPLOY_THRESHOLD => Weight::new(1)
Expand Down Expand Up @@ -103,7 +106,7 @@ fn should_raise_auth_failure_with_invalid_keys() {
.with_address(*DEFAULT_ACCOUNT_ADDR)
.with_empty_payment_bytes(runtime_args! { ARG_AMOUNT => *DEFAULT_PAYMENT, })
.with_session_code(
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(1),
ARG_DEPLOY_THRESHOLD => Weight::new(1)
Expand Down Expand Up @@ -167,7 +170,7 @@ fn should_raise_deploy_authorization_failure() {
// a key with weight=2.
let exec_request_4 = ExecuteRequestBuilder::standard(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(4),
ARG_DEPLOY_THRESHOLD => Weight::new(3)
Expand Down Expand Up @@ -200,7 +203,7 @@ fn should_raise_deploy_authorization_failure() {
.with_empty_payment_bytes(runtime_args! { ARG_AMOUNT => *DEFAULT_PAYMENT, })
// Next deploy will see deploy threshold == 4, keymgmnt == 5
.with_session_code(
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(5),
ARG_DEPLOY_THRESHOLD => Weight::new(4)
Expand Down Expand Up @@ -236,7 +239,7 @@ fn should_raise_deploy_authorization_failure() {
.with_empty_payment_bytes(runtime_args! { ARG_AMOUNT => *DEFAULT_PAYMENT, })
// change deployment threshold to 4
.with_session_code(
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(6),
ARG_DEPLOY_THRESHOLD => Weight::new(5)
Expand All @@ -260,7 +263,7 @@ fn should_raise_deploy_authorization_failure() {
.with_empty_payment_bytes(runtime_args! { ARG_AMOUNT => *DEFAULT_PAYMENT, })
// change deployment threshold to 4
.with_session_code(
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(0),
ARG_DEPLOY_THRESHOLD => Weight::new(0)
Expand Down Expand Up @@ -298,7 +301,7 @@ fn should_raise_deploy_authorization_failure() {
.with_empty_payment_bytes(runtime_args! { ARG_AMOUNT => *DEFAULT_PAYMENT, })
// change deployment threshold to 4
.with_session_code(
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(0),
ARG_DEPLOY_THRESHOLD => Weight::new(0)
Expand Down Expand Up @@ -358,7 +361,7 @@ fn should_authorize_deploy_with_multiple_keys() {
.with_address(*DEFAULT_ACCOUNT_ADDR)
.with_empty_payment_bytes(runtime_args! { ARG_AMOUNT => *DEFAULT_PAYMENT, })
.with_session_code(
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(0),
ARG_DEPLOY_THRESHOLD => Weight::new(0),
Expand Down Expand Up @@ -390,7 +393,17 @@ fn should_not_authorize_deploy_with_duplicated_keys() {

let exec_request_2 = ExecuteRequestBuilder::standard(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_ADD_ASSOCIATED_KEY,
runtime_args! {
ARG_ACCOUNT => KEY_2,
ARG_WEIGHT => KEY_2_WEIGHT,
},
)
.build();

let exec_request_3 = ExecuteRequestBuilder::standard(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(4),
ARG_DEPLOY_THRESHOLD => Weight::new(3)
Expand All @@ -399,24 +412,26 @@ fn should_not_authorize_deploy_with_duplicated_keys() {
.build();
// Basic deploy with single key
let mut builder = InMemoryWasmTestBuilder::default();
builder.run_genesis(&DEFAULT_RUN_GENESIS_REQUEST);

builder
.run_genesis(&DEFAULT_RUN_GENESIS_REQUEST)
// Reusing a test contract that would add new key
.exec(exec_request_1)
.expect_success()
.commit()
.exec(exec_request_2)
.expect_success()
.commit();

builder.exec(exec_request_2).expect_success().commit();

builder.exec(exec_request_3).expect_success().commit();

let exec_request_3 = {
let deploy = DeployItemBuilder::new()
.with_address(*DEFAULT_ACCOUNT_ADDR)
.with_empty_payment_bytes(runtime_args! {
ARG_AMOUNT => *DEFAULT_PAYMENT,
})
.with_session_code(
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(0),
ARG_DEPLOY_THRESHOLD => Weight::new(0)
Expand Down Expand Up @@ -472,7 +487,7 @@ fn should_not_authorize_transfer_without_deploy_key_threshold() {
.build();
let update_thresholds_request = ExecuteRequestBuilder::standard(
*DEFAULT_ACCOUNT_ADDR,
CONTRACT_AUTHORIZED_KEYS,
CONTRACT_SET_ACTION_THRESHOLDS,
runtime_args! {
ARG_KEY_MANAGEMENT_THRESHOLD => Weight::new(5),
ARG_DEPLOY_THRESHOLD => Weight::new(5),
Expand Down
Loading