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

e2e tests for keyless feature gating #12296

Merged
merged 4 commits into from
Mar 1, 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
15 changes: 14 additions & 1 deletion aptos-move/aptos-vm/src/aptos_vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1320,7 +1320,20 @@

let authenticators = aptos_types::keyless::get_authenticators(transaction)
.map_err(|_| VMStatus::error(StatusCode::INVALID_SIGNATURE, None))?;
keyless_validation::validate_authenticators(&authenticators, self.features(), resolver)?;

// If there are keyless TXN authenticators, validate them all.
if !authenticators.is_empty() {

Check warning on line 1325 in aptos-move/aptos-vm/src/aptos_vm.rs

View check run for this annotation

Codecov / codecov/patch

aptos-move/aptos-vm/src/aptos_vm.rs#L1325

Added line #L1325 was not covered by tests
// Feature-gating keyless TXNs: if they are *not* enabled, return `FEATURE_UNDER_GATING`,
// which will discard the TXN from being put on-chain.
if !self.features().is_keyless_enabled() {
return Err(VMStatus::error(StatusCode::FEATURE_UNDER_GATING, None));
}
keyless_validation::validate_authenticators(
&authenticators,
self.features(),
resolver,
)?;
}

Check warning on line 1336 in aptos-move/aptos-vm/src/aptos_vm.rs

View check run for this annotation

Codecov / codecov/patch

aptos-move/aptos-vm/src/aptos_vm.rs#L1328-L1336

Added lines #L1328 - L1336 were not covered by tests

// The prologue MUST be run AFTER any validation. Otherwise you may run prologue and hit
// SEQUENCE_NUMBER_TOO_NEW if there is more than one transaction from the same sender and
Expand Down
16 changes: 6 additions & 10 deletions aptos-move/aptos-vm/src/keyless_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,22 +103,17 @@
features: &Features,
resolver: &impl AptosMoveResolver,
) -> Result<(), VMStatus> {
// Feature gating
for (_, sig) in authenticators {
if !features.is_keyless_enabled() && matches!(sig.sig, ZkpOrOpenIdSig::Groth16Zkp { .. }) {
return Err(VMStatus::error(StatusCode::FEATURE_UNDER_GATING, None));
}
if (!features.is_keyless_enabled() || !features.is_keyless_zkless_enabled())
&& matches!(sig.sig, ZkpOrOpenIdSig::OpenIdSig { .. })
// Feature-gating for keyless-but-zkless TXNs: If keyless TXNs *are* enabled, and (1) this
// is a ZKless transaction but (2) ZKless TXNs are not yet enabled, discard the TXN from
// being put on-chain.
if matches!(sig.sig, ZkpOrOpenIdSig::OpenIdSig { .. })
&& !features.is_keyless_zkless_enabled()

Check warning on line 111 in aptos-move/aptos-vm/src/keyless_validation.rs

View check run for this annotation

Codecov / codecov/patch

aptos-move/aptos-vm/src/keyless_validation.rs#L110-L111

Added lines #L110 - L111 were not covered by tests
{
return Err(VMStatus::error(StatusCode::FEATURE_UNDER_GATING, None));
}
}

if authenticators.is_empty() {
return Ok(());
}

let config = &get_configs_onchain(resolver)?;
if authenticators.len() > config.max_signatures_per_txn as usize {
return Err(invalid_signature!("Too many keyless authenticators"));
Expand Down Expand Up @@ -213,5 +208,6 @@
},
}
}

Ok(())
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc 0d06e418a86d5a07e5ac65d22e86d78a819989e1e0815db4750efcc12dc9d905 # shrinks to block_split = Whole
cc c5ad38cf3be8dea3f90d1504b070a030228a03829c63964d2855e8946d17ffe6 # shrinks to block_split = Whole
2 changes: 2 additions & 0 deletions aptos-move/e2e-move-tests/src/harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,7 @@ impl MoveHarness {
}

/// Reads the resource data `T`.
/// WARNING: Does not work with resource groups (because set_resource does not work?).
pub fn read_resource<T: DeserializeOwned>(
&self,
addr: &AccountAddress,
Expand Down Expand Up @@ -714,6 +715,7 @@ impl MoveHarness {
}

/// Write the resource data `T`.
/// WARNING: Does not work with resource groups.
pub fn set_resource<T: Serialize>(
&mut self,
addr: AccountAddress,
Expand Down
188 changes: 188 additions & 0 deletions aptos-move/e2e-move-tests/src/tests/keyless_feature_gating.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
// Copyright © Aptos Foundation

use crate::{assert_success, build_package, tests::common, MoveHarness};
use aptos_cached_packages::aptos_stdlib;
use aptos_crypto::{hash::CryptoHash, SigningKey};
use aptos_language_e2e_tests::account::{Account, AccountPublicKey, TransactionBuilder};
use aptos_types::{
keyless::{
test_utils::{
get_sample_esk, get_sample_groth16_sig_and_pk, get_sample_iss, get_sample_jwk,
get_sample_openid_sig_and_pk,
},
Configuration, KeylessPublicKey, KeylessSignature, ZkpOrOpenIdSig,
},
on_chain_config::FeatureFlag,
transaction::{
authenticator::{AnyPublicKey, AuthenticationKey, EphemeralSignature},
Script, SignedTransaction, Transaction, TransactionStatus,
},
};
use move_core_types::{
account_address::AccountAddress, transaction_argument::TransactionArgument,
vm_status::StatusCode::FEATURE_UNDER_GATING,
};

#[test]
fn test_keyless_disabled() {
let mut h = MoveHarness::new_with_features(vec![], vec![FeatureFlag::KEYLESS_ACCOUNTS]);

let (sig, pk) = get_sample_groth16_sig_and_pk();
let bob = h.new_account_at(AccountAddress::from_hex_literal("0xb0b").unwrap());

let transaction = get_keyless_txn(&mut h, sig, pk, bob);

let output = h.run_raw(transaction);
match output.status() {
TransactionStatus::Discard(status) => {
assert_eq!(*status, FEATURE_UNDER_GATING)
},
_ => {
panic!("Expected to get FEATURE_UNDER_GATING DiscardedVMStatus")
},
}
}

#[test]
fn test_keyless_enabled() {
let mut h = MoveHarness::new_with_features(vec![FeatureFlag::KEYLESS_ACCOUNTS], vec![]);

let (sig, pk) = get_sample_groth16_sig_and_pk();
let bob = h.new_account_at(AccountAddress::from_hex_literal("0xb0b").unwrap());

// initialize JWK
run_setup_script(&mut h);

let transaction = get_keyless_txn(&mut h, sig, pk, bob);

let output = h.run_raw(transaction);
assert_success!(output.status().clone());
}

#[test]
fn test_keyless_enabled_but_zkless_disabled() {
let mut h = MoveHarness::new_with_features(vec![FeatureFlag::KEYLESS_ACCOUNTS], vec![
FeatureFlag::KEYLESS_BUT_ZKLESS_ACCOUNTS,
]);

let (sig, pk) = get_sample_openid_sig_and_pk();
let bob = h.new_account_at(AccountAddress::from_hex_literal("0xb0b").unwrap());

// initialize JWK
run_setup_script(&mut h);

let transaction = get_keyless_txn(&mut h, sig, pk, bob);

let output = h.run_raw(transaction);
match output.status() {
TransactionStatus::Discard(status) => {
assert_eq!(*status, FEATURE_UNDER_GATING)
},
_ => {
panic!("Expected to get FEATURE_UNDER_GATING DiscardedVMStatus")
},
}
}

#[test]
fn test_keyless_enabled_but_zkless_enabled() {
let mut h = MoveHarness::new_with_features(vec![FeatureFlag::KEYLESS_ACCOUNTS], vec![]);

let (sig, pk) = get_sample_openid_sig_and_pk();
let bob = h.new_account_at(AccountAddress::from_hex_literal("0xb0b").unwrap());

// initialize JWK
run_setup_script(&mut h);

let transaction = get_keyless_txn(&mut h, sig, pk, bob);

let output = h.run_raw(transaction);
assert_success!(output.status().clone());
}

/// Creates and funds a new account at `pk` and sends coins to `recipient`.
fn get_keyless_txn(
h: &mut MoveHarness,
mut sig: KeylessSignature,
pk: KeylessPublicKey,
recipient: Account,
) -> SignedTransaction {
let apk = AnyPublicKey::keyless(pk.clone());
let addr = AuthenticationKey::any_key(apk.clone()).account_address();
let account = h.store_and_fund_account(
&Account::new_from_addr(addr, AccountPublicKey::Keyless(pk.clone())),
100000000,
0,
);

println!("Actual address: {}", addr.to_hex());
println!("Account address: {}", account.address().to_hex());

let payload = aptos_stdlib::aptos_coin_transfer(*recipient.address(), 1);
//println!("Payload: {:?}", payload);
let raw_txn = TransactionBuilder::new(account.clone())
.payload(payload)
.sequence_number(h.sequence_number(account.address()))
.max_gas_amount(1_000_000)
.gas_unit_price(1)
.raw();

println!("RawTxn sender: {:?}", raw_txn.sender());

let esk = get_sample_esk();
sig.ephemeral_signature = EphemeralSignature::ed25519(esk.sign(&raw_txn).unwrap());

// Compute the training wheels signature if not present
match &mut sig.sig {
ZkpOrOpenIdSig::Groth16Zkp(proof) => {
// Training wheels should be disabled.
proof.training_wheels_signature = None
},
ZkpOrOpenIdSig::OpenIdSig(_) => {},
}

let transaction = SignedTransaction::new_keyless(raw_txn, pk, sig);
println!(
"Submitted TXN hash: {}",
Transaction::UserTransaction(transaction.clone()).hash()
);
transaction
}

fn run_setup_script(h: &mut MoveHarness) {
let core_resources = h.new_account_at(AccountAddress::from_hex_literal("0xA550C18").unwrap());

let package = build_package(
common::test_dir_path("keyless_setup.data/pack"),
aptos_framework::BuildOptions::default(),
)
.expect("building package must succeed");

let txn = h.create_publish_built_package(&core_resources, &package, |_| {});
assert_success!(h.run(txn));

let script = package.extract_script_code()[0].clone();

let iss = get_sample_iss();
let jwk = get_sample_jwk();
let config = Configuration::new_for_testing();

let txn = TransactionBuilder::new(core_resources.clone())
.script(Script::new(script, vec![], vec![
TransactionArgument::U8Vector(iss.into_bytes()),
TransactionArgument::U8Vector(jwk.kid.into_bytes()),
TransactionArgument::U8Vector(jwk.alg.into_bytes()),
TransactionArgument::U8Vector(jwk.e.into_bytes()),
TransactionArgument::U8Vector(jwk.n.into_bytes()),
TransactionArgument::U64(config.max_exp_horizon_secs),
]))
.sequence_number(h.sequence_number(core_resources.address()))
.max_gas_amount(1_000_000)
.gas_unit_price(1)
.sign();

// NOTE: We cannot write the Configuration and Groth16Verification key via MoveHarness::set_resource
// because it does not (yet) work with resource groups.

assert_success!(h.run(txn));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = 'InsertJwk'
version = "0.0.0"

[dependencies]
AptosFramework = { local = "../../../../../framework/aptos-framework" }
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
script {
use aptos_framework::jwks;
use aptos_framework::aptos_governance;
use aptos_framework::keyless_account;
use std::string::utf8;

fun main(core_resources: &signer, iss: vector<u8>, kid: vector<u8>, alg: vector<u8>, e: vector<u8>, n: vector<u8>, max_exp_horizon_secs: u64) {
let fx = aptos_governance::get_signer_testnet_only(core_resources, @aptos_framework);
let jwk = jwks::new_rsa_jwk(
utf8(kid),
utf8(alg),
utf8(e),
utf8(n)
);

let patches = vector[
jwks::new_patch_remove_all(),
jwks::new_patch_upsert_jwk(iss, jwk),
];
jwks::set_patches(&fx, patches);

keyless_account::update_max_exp_horizon(&fx, max_exp_horizon_secs);
}
}
1 change: 1 addition & 0 deletions aptos-move/e2e-move-tests/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ mod generate_upgrade_script;
mod governance_updates;
mod infinite_loop;
mod init_module;
mod keyless_feature_gating;
mod lazy_natives;
mod max_loop_depth;
mod memory_quota;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub fn offer_rotation_capability_v2(
aptos_stdlib::account_offer_rotation_capability(
rotation_proof_signed.to_bytes().to_vec(),
0,
offerer_account.pubkey.to_bytes().to_vec(),
offerer_account.pubkey.to_bytes(),
*delegate_account.address(),
)
));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fn offer_signer_capability_v2() {
aptos_stdlib::account_offer_signer_capability(
signature.to_bytes().to_vec(),
0,
account_alice.pubkey.to_bytes().to_vec(),
account_alice.pubkey.to_bytes(),
*account_bob.address(),
)
));
Expand Down
Loading
Loading