Skip to content

Commit

Permalink
Merge branch 'master' into hc/update-registration-pallet-test
Browse files Browse the repository at this point in the history
  • Loading branch information
HCastano committed Aug 22, 2024
2 parents 5c4e869 + 260e953 commit 99bde7e
Show file tree
Hide file tree
Showing 15 changed files with 417 additions and 205 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ At the moment this project **does not** adhere to
### Changed
- Fix TSS `AccountId` keys in chainspec ([#993](https://github.com/entropyxyz/entropy-core/pull/993))

### Removed
- Remove `prune_registration` extrinsic ([#1022](https://github.com/entropyxyz/entropy-core/pull/1022))

## [0.2.0](https://github.com/entropyxyz/entropy-core/compare/release/v0.1.0...release/v0.2.0) - 2024-07-11

### Breaking Changes
Expand Down
Binary file modified crates/client/entropy_metadata.scale
Binary file not shown.
4 changes: 3 additions & 1 deletion crates/testing-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ pub mod constants;
pub mod create_test_keyshares;
mod node_proc;
pub mod substrate_context;
pub use entropy_tss::helpers::tests::spawn_testing_validators;
pub use entropy_tss::helpers::tests::{
jump_start_network_with_signer as jump_start_network, spawn_testing_validators,
};
pub use node_proc::TestNodeProcess;
pub use substrate_context::*;
23 changes: 23 additions & 0 deletions crates/threshold-signature-server/src/helpers/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use crate::{
},
logger::{Instrumentation, Logger},
substrate::{query_chain, submit_transaction},
validator::get_signer_and_x25519_secret_from_mnemonic,
},
signing_client::ListenerState,
AppState,
Expand Down Expand Up @@ -264,3 +265,25 @@ pub async fn unsafe_get(client: &reqwest::Client, query_key: String, port: u32)

get_result.bytes().await.unwrap().into()
}

/// Mock the network being jump started by confirming a jump start even though no DKG took place,
/// so that we can use pre-store parent keyshares for testing
pub async fn jump_start_network_with_signer(
api: &OnlineClient<EntropyConfig>,
rpc: &LegacyRpcMethods<EntropyConfig>,
signer: &PairSigner<EntropyConfig, sr25519::Pair>,
) {
let jump_start_request = entropy::tx().registry().jump_start_network();
let _result = submit_transaction(api, rpc, signer, &jump_start_request, None).await.unwrap();

let validators_names = vec![ValidatorName::Bob, ValidatorName::Charlie, ValidatorName::Dave];
for validator_name in validators_names {
let mnemonic = development_mnemonic(&Some(validator_name));
let (tss_signer, _static_secret) =
get_signer_and_x25519_secret_from_mnemonic(&mnemonic.to_string()).unwrap();
let jump_start_confirm_request =
entropy::tx().registry().confirm_jump_start(BoundedVec(EVE_VERIFYING_KEY.to_vec()));

submit_transaction(api, rpc, &tss_signer, &jump_start_confirm_request, None).await.unwrap();
}
}
20 changes: 5 additions & 15 deletions crates/threshold-signature-server/src/user/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ use crate::{
substrate::{get_oracle_data, query_chain, submit_transaction},
tests::{
check_has_confirmation, check_if_confirmation, create_clients, initialize_test_logger,
remove_program, run_to_block, setup_client, spawn_testing_validators, unsafe_get,
jump_start_network_with_signer, remove_program, run_to_block, setup_client,
spawn_testing_validators, unsafe_get,
},
user::compute_hash,
validator::get_signer_and_x25519_secret_from_mnemonic,
Expand Down Expand Up @@ -1559,6 +1560,7 @@ async fn test_new_registration_flow() {

clean_tests();
}

#[tokio::test]
#[serial]
async fn test_mutiple_confirm_done() {
Expand Down Expand Up @@ -1755,24 +1757,12 @@ pub async fn get_sign_tx_data(
(validators_info, generic_msg, validator_ips_and_keys)
}

/// Mock jump starting the network
pub async fn jump_start_network(
api: &OnlineClient<EntropyConfig>,
rpc: &LegacyRpcMethods<EntropyConfig>,
) {
let alice = AccountKeyring::Alice;
let signer = PairSigner::<EntropyConfig, sr25519::Pair>::new(alice.clone().into());

let jump_start_request = entropy::tx().registry().jump_start_network();
let _result = submit_transaction(api, rpc, &signer, &jump_start_request, None).await.unwrap();

let validators_names = vec![ValidatorName::Bob, ValidatorName::Charlie, ValidatorName::Dave];
for validator_name in validators_names {
let mnemonic = development_mnemonic(&Some(validator_name));
let (tss_signer, _static_secret) =
get_signer_and_x25519_secret_from_mnemonic(&mnemonic.to_string()).unwrap();
let jump_start_confirm_request =
entropy::tx().registry().confirm_jump_start(BoundedVec(EVE_VERIFYING_KEY.to_vec()));

submit_transaction(api, rpc, &tss_signer, &jump_start_confirm_request, None).await.unwrap();
}
jump_start_network_with_signer(api, rpc, &signer).await;
}
107 changes: 107 additions & 0 deletions crates/threshold-signature-server/tests/register_and_sign.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright (C) 2023 Entropy Cryptography Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use entropy_client::{
chain_api::{
entropy::runtime_types::bounded_collections::bounded_vec::BoundedVec,
entropy::runtime_types::pallet_registry::pallet::ProgramInstance, get_api, get_rpc,
EntropyConfig,
},
client as test_client, Hasher,
};
use entropy_kvdb::clean_tests;
use entropy_testing_utils::{
constants::{
AUXILARY_DATA_SHOULD_SUCCEED, PREIMAGE_SHOULD_SUCCEED, TEST_PROGRAM_WASM_BYTECODE,
},
jump_start_network, spawn_testing_validators, test_node_process_testing_state,
};
use serial_test::serial;
use sp_core::{sr25519, Pair};
use sp_keyring::AccountKeyring;
use subxt::{tx::PairSigner, utils::AccountId32};
use synedrion::k256::ecdsa::VerifyingKey;

#[tokio::test]
#[serial]
async fn integration_test_register_and_sign() {
clean_tests();
let account_owner = AccountKeyring::Ferdie.pair();
let signature_request_author = AccountKeyring::One;

let add_parent_key = true;
let (_validator_ips, _validator_ids) = spawn_testing_validators(add_parent_key).await;

let force_authoring = true;
let substrate_context = test_node_process_testing_state(force_authoring).await;
let api = get_api(&substrate_context.ws_url).await.unwrap();
let rpc = get_rpc(&substrate_context.ws_url).await.unwrap();

// Jumpstart the network
let alice = AccountKeyring::Alice;
let signer = PairSigner::<EntropyConfig, sr25519::Pair>::new(alice.clone().into());
jump_start_network(&api, &rpc, &signer).await;

// Store a program
let program_pointer = test_client::store_program(
&api,
&rpc,
&account_owner,
TEST_PROGRAM_WASM_BYTECODE.to_owned(),
vec![],
vec![],
vec![],
)
.await
.unwrap();

// Register, using that program
let register_on_chain = true;
let (verifying_key, _registered_info) = test_client::register(
&api,
&rpc,
account_owner.clone(),
AccountId32(account_owner.public().0),
BoundedVec(vec![ProgramInstance { program_pointer, program_config: vec![] }]),
register_on_chain,
)
.await
.unwrap();

// Sign a message
let recoverable_signature = test_client::sign(
&api,
&rpc,
signature_request_author.pair(),
verifying_key,
PREIMAGE_SHOULD_SUCCEED.to_vec(),
Some(AUXILARY_DATA_SHOULD_SUCCEED.to_vec()),
)
.await
.unwrap();

// Check the signature
let message_should_succeed_hash = Hasher::keccak(PREIMAGE_SHOULD_SUCCEED);
let recovery_key_from_sig = VerifyingKey::recover_from_prehash(
&message_should_succeed_hash,
&recoverable_signature.signature,
recoverable_signature.recovery_id,
)
.unwrap();
assert_eq!(
verifying_key.to_vec(),
recovery_key_from_sig.to_encoded_point(true).to_bytes().to_vec()
);
}
28 changes: 0 additions & 28 deletions pallets/registry/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,34 +251,6 @@ benchmarks! {
assert!(RegisteredOnChain::<T>::contains_key(expected_verifying_key));
}

prune_registration {
let p in 1 .. T::MaxProgramHashes::get();
let program_modification_account: T::AccountId = whitelisted_caller();
let program = vec![0u8];
let configuration_schema = vec![1u8];
let auxiliary_data_schema = vec![2u8];
let oracle_data_pointer = vec![3u8];
let program_hash = T::Hashing::hash(&program);
let programs_info = BoundedVec::try_from(vec![ProgramInstance {
program_pointer: program_hash,
program_config: vec![],
}]).unwrap();
Programs::<T>::insert(program_hash, ProgramInfo {bytecode: program, configuration_schema, auxiliary_data_schema, oracle_data_pointer, deployer: program_modification_account.clone(), ref_counter: 1});
let sig_req_account: T::AccountId = whitelisted_caller();
let balance = <T as pallet_staking_extension::Config>::Currency::minimum_balance() * 100u32.into();
let _ = <T as pallet_staking_extension::Config>::Currency::make_free_balance_be(&sig_req_account, balance);
<Registering<T>>::insert(&sig_req_account, RegisteringDetails::<T> {
program_modification_account: sig_req_account.clone(),
confirmations: vec![],
programs_data: programs_info,
verifying_key: Some(BoundedVec::default()),
version_number: T::KeyVersionNumber::get()
});
}: _(RawOrigin::Signed(sig_req_account.clone()))
verify {
assert_last_event::<T>(Event::RegistrationCancelled(sig_req_account.clone()).into());
}

change_program_instance {
let n in 1 .. T::MaxProgramHashes::get();
let o in 1 .. T::MaxProgramHashes::get();
Expand Down
32 changes: 4 additions & 28 deletions pallets/registry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,32 +447,8 @@ pub mod pallet {
Ok(Some(<T as Config>::WeightInfo::register(programs_data.len() as u32)).into())
}

/// Allows a user to remove themselves from registering state if it has been longer than prune block
#[pallet::call_index(3)]
#[pallet::weight({
<T as Config>::WeightInfo::prune_registration(<T as Config>::MaxProgramHashes::get())
})]
pub fn prune_registration(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
let registering_info = Self::registering(&who).ok_or(Error::<T>::NotRegistering)?;
for program_instance in &registering_info.programs_data {
pallet_programs::Programs::<T>::mutate(
program_instance.program_pointer,
|maybe_program_info| {
if let Some(program_info) = maybe_program_info {
program_info.ref_counter = program_info.ref_counter.saturating_sub(1);
}
},
);
}
let program_length = registering_info.programs_data.len();
Registering::<T>::remove(&who);
Self::deposit_event(Event::RegistrationCancelled(who));
Ok(Some(<T as Config>::WeightInfo::register(program_length as u32)).into())
}

/// Allows a user's program modification account to change their program pointer
#[pallet::call_index(4)]
#[pallet::call_index(3)]
#[pallet::weight({
<T as Config>::WeightInfo::change_program_instance(
<T as Config>::MaxProgramHashes::get(),
Expand Down Expand Up @@ -539,7 +515,7 @@ pub mod pallet {
}

/// Allows a user's program modification account to change itself.
#[pallet::call_index(5)]
#[pallet::call_index(4)]
#[pallet::weight({
<T as Config>::WeightInfo::change_program_modification_account(MAX_MODIFIABLE_KEYS)
})]
Expand Down Expand Up @@ -602,7 +578,7 @@ pub mod pallet {
///
/// After a validator from each partition confirms they have a keyshare the user will be
/// considered as registered on the network.
#[pallet::call_index(6)]
#[pallet::call_index(5)]
#[pallet::weight({
let weight =
<T as Config>::WeightInfo::confirm_register_registering(pallet_session::Pallet::<T>::validators().len() as u32)
Expand Down Expand Up @@ -711,7 +687,7 @@ pub mod pallet {
///
/// Note: Substrate origins are allowed to register as many accounts as they wish. Each
/// registration request will produce a different verifying key.
#[pallet::call_index(7)]
#[pallet::call_index(6)]
#[pallet::weight({
<T as Config>::WeightInfo::register_on_chain(<T as Config>::MaxProgramHashes::get())
})]
Expand Down
43 changes: 0 additions & 43 deletions pallets/registry/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ use entropy_shared::{NETWORK_PARENT_KEY, VERIFICATION_KEY_LENGTH};
use frame_support::{
assert_noop, assert_ok,
dispatch::{GetDispatchInfo, Pays},
traits::Currency,
BoundedVec,
};
use pallet_programs::ProgramInfo;
Expand Down Expand Up @@ -772,48 +771,6 @@ fn it_fails_on_non_matching_verifying_keys() {
})
}

#[test]
fn it_tests_prune_registration() {
new_test_ext().execute_with(|| {
let inital_program = vec![10];
let program_hash = <Test as frame_system::Config>::Hashing::hash(&inital_program);
let programs_info = BoundedVec::try_from(vec![ProgramInstance {
program_pointer: program_hash,
program_config: vec![],
}])
.unwrap();

pallet_programs::Programs::<Test>::insert(
program_hash,
ProgramInfo {
bytecode: inital_program.clone(),
configuration_schema: inital_program.clone(),
auxiliary_data_schema: inital_program.clone(),
oracle_data_pointer: inital_program.clone(),
deployer: 1,
ref_counter: 1,
},
);

Balances::make_free_balance_be(&2, 100);
// register a user
assert_ok!(Registry::register(RuntimeOrigin::signed(1), 2, programs_info,));
assert_eq!(
pallet_programs::Programs::<Test>::get(program_hash).unwrap().ref_counter,
2,
"ref counter is increment"
);
assert!(Registry::registering(1).is_some(), "Make sure there is registering state");
assert_ok!(Registry::prune_registration(RuntimeOrigin::signed(1)));
assert_eq!(Registry::registering(1), None, "Make sure registering is pruned");
assert_eq!(
pallet_programs::Programs::<Test>::get(program_hash).unwrap().ref_counter,
1,
"ref counter is decremented"
);
});
}

#[test]
fn it_provides_free_txs_confirm_done() {
new_test_ext().execute_with(|| {
Expand Down
Loading

0 comments on commit 99bde7e

Please sign in to comment.