Skip to content

Commit

Permalink
Fixes for tests and test helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
ameba23 committed Dec 16, 2024
1 parent 15d3bbe commit 1ca0a0c
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 71 deletions.
2 changes: 1 addition & 1 deletion crates/testing-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ pub use entropy_tss::helpers::tests::{spawn_testing_validators, ChainSpecType};
pub use node_proc::TestNodeProcess;
pub use substrate_context::*;

pub use entropy_tss::helpers::validator::get_signer_and_x25519_secret_from_mnemonic;
// pub use entropy_tss::helpers::validator::get_signer_and_x25519_secret_from_mnemonic;
54 changes: 17 additions & 37 deletions crates/threshold-signature-server/src/helpers/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,11 @@ use crate::{
},
EntropyConfig,
},
get_signer,
helpers::{
launch::{
development_mnemonic, setup_latest_block_number, setup_mnemonic, Configuration,
ValidatorName, DEFAULT_ENDPOINT,
},
launch::{setup_latest_block_number, Configuration, ValidatorName, DEFAULT_ENDPOINT},
logger::{Instrumentation, Logger},
substrate::submit_transaction,
},
signing_client::ListenerState,
AppState,
};
use axum::{routing::IntoMakeService, Router};
Expand Down Expand Up @@ -74,13 +69,10 @@ pub async fn setup_client() -> KvManager {
KvManager::new(get_db_path(true).into(), PasswordMethod::NoPassword.execute().unwrap())
.unwrap();

let mnemonic = development_mnemonic(&Some(ValidatorName::Alice));
setup_mnemonic(&kv_store, mnemonic).await;

let _ = setup_latest_block_number(&kv_store).await;
let listener_state = ListenerState::default();
let configuration = Configuration::new(DEFAULT_ENDPOINT.to_string());
let app_state = AppState { listener_state, configuration, kv_store: kv_store.clone() };
let app_state = AppState::new(configuration, kv_store.clone(), &Some(ValidatorName::Alice));

let app = app(app_state).into_make_service();

let listener = tokio::net::TcpListener::bind("0.0.0.0:3001")
Expand All @@ -98,8 +90,7 @@ pub async fn create_clients(
values: Vec<Vec<u8>>,
keys: Vec<String>,
validator_name: &Option<ValidatorName>,
) -> (IntoMakeService<Router>, KvManager) {
let listener_state = ListenerState::default();
) -> (IntoMakeService<Router>, KvManager, SubxtAccountId32) {
let configuration = Configuration::new(DEFAULT_ENDPOINT.to_string());

let path = format!(".entropy/testing/test_db_{key_number}");
Expand All @@ -108,21 +99,20 @@ pub async fn create_clients(
let kv_store =
KvManager::new(path.into(), PasswordMethod::NoPassword.execute().unwrap()).unwrap();

let mnemonic = development_mnemonic(validator_name);
crate::launch::setup_mnemonic(&kv_store, mnemonic).await;

let _ = setup_latest_block_number(&kv_store).await;

for (i, value) in values.into_iter().enumerate() {
let reservation = kv_store.clone().kv().reserve_key(keys[i].to_string()).await.unwrap();
let _ = kv_store.clone().kv().put(reservation, value).await;
}

let app_state = AppState { listener_state, configuration, kv_store: kv_store.clone() };
let app_state = AppState::new(configuration, kv_store.clone(), validator_name);

let account_id = app_state.subxt_account_id();

let app = app(app_state).into_make_service();

(app, kv_store)
(app, kv_store, account_id)
}

/// A way to specify which chainspec to use in testing
Expand Down Expand Up @@ -156,26 +146,18 @@ pub async fn spawn_testing_validators(
) -> (Vec<String>, Vec<PartyId>) {
let ports = [3001i64, 3002, 3003, 3004];

let (alice_axum, alice_kv) =
let (alice_axum, alice_kv, alice_id) =
create_clients("validator1".to_string(), vec![], vec![], &Some(ValidatorName::Alice)).await;
let alice_id = PartyId::new(SubxtAccountId32(
*get_signer(&alice_kv).await.unwrap().account_id().clone().as_ref(),
));
let alice_id = PartyId::new(alice_id);

let (bob_axum, bob_kv) =
let (bob_axum, bob_kv, bob_id) =
create_clients("validator2".to_string(), vec![], vec![], &Some(ValidatorName::Bob)).await;
let bob_id = PartyId::new(SubxtAccountId32(
*get_signer(&bob_kv).await.unwrap().account_id().clone().as_ref(),
));
let bob_id = PartyId::new(bob_id);

let (charlie_axum, charlie_kv) =
let (charlie_axum, charlie_kv, charlie_id) =
create_clients("validator3".to_string(), vec![], vec![], &Some(ValidatorName::Charlie))
.await;
let charlie_id = PartyId::new(SubxtAccountId32(
*get_signer(&charlie_kv).await.unwrap().account_id().clone().as_ref(),
));

let mut ids = vec![alice_id, bob_id, charlie_id];
let charlie_id = PartyId::new(charlie_id);

let listener_alice = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", ports[0]))
.await
Expand All @@ -198,7 +180,7 @@ pub async fn spawn_testing_validators(
axum::serve(listener_charlie, charlie_axum).await.unwrap();
});

let (dave_axum, dave_kv) =
let (dave_axum, _dave_kv, dave_id) =
create_clients("validator4".to_string(), vec![], vec![], &Some(ValidatorName::Dave)).await;

let listener_dave = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", ports[3]))
Expand All @@ -207,10 +189,8 @@ pub async fn spawn_testing_validators(
tokio::spawn(async move {
axum::serve(listener_dave, dave_axum).await.unwrap();
});
let dave_id = PartyId::new(SubxtAccountId32(
*get_signer(&dave_kv).await.unwrap().account_id().clone().as_ref(),
));
ids.push(dave_id);
let dave_id = PartyId::new(dave_id);
let ids = vec![alice_id, bob_id, charlie_id, dave_id];

if chain_spec_type == ChainSpecType::IntegrationJumpStarted {
put_keyshares_in_db(ValidatorName::Alice, alice_kv).await;
Expand Down
5 changes: 3 additions & 2 deletions crates/threshold-signature-server/src/helpers/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,10 @@ fn get_x25519_secret_from_hkdf(hkdf: &Hkdf<Sha256>) -> Result<StaticSecret, User
#[cfg(any(test, feature = "test_helpers"))]
pub fn get_signer_and_x25519_secret_from_mnemonic(
mnemonic: &str,
) -> Result<(PairSigner<EntropyConfig, sr25519::Pair>, StaticSecret), UserErr> {
) -> Result<(subxt::tx::PairSigner<crate::EntropyConfig, sr25519::Pair>, StaticSecret), UserErr> {
let hkdf = get_hkdf_from_mnemonic(mnemonic)?;
let pair_signer = get_signer_from_hkdf(&hkdf)?;
let pair = get_signer_from_hkdf(&hkdf)?;
let pair_signer = subxt::tx::PairSigner::new(pair);
let static_secret = get_x25519_secret_from_hkdf(&hkdf)?;
Ok((pair_signer, static_secret))
}
6 changes: 5 additions & 1 deletion crates/threshold-signature-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ use axum::{
use entropy_kvdb::kv_manager::KvManager;
use rand_core::OsRng;
use sp_core::{sr25519, Pair};
use subxt::tx::PairSigner;
use subxt::{tx::PairSigner, utils::AccountId32 as SubxtAccountId32};
use tower_http::{
cors::{Any, CorsLayer},
trace::{self, TraceLayer},
Expand Down Expand Up @@ -239,6 +239,10 @@ impl AppState {
pub fn signer(&self) -> PairSigner<EntropyConfig, sr25519::Pair> {
PairSigner::<EntropyConfig, sr25519::Pair>::new(self.signer.clone())
}

pub fn subxt_account_id(&self) -> SubxtAccountId32 {
SubxtAccountId32(self.signer.public().0)
}
}

pub fn app(app_state: AppState) -> Router {
Expand Down
32 changes: 2 additions & 30 deletions crates/threshold-signature-server/src/user/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,12 @@ use schemars::{schema_for, JsonSchema};
use schnorrkel::{signing_context, Keypair as Sr25519Keypair, Signature as Sr25519Signature};
use serde::{Deserialize, Serialize};
use serial_test::serial;
use sp_core::{crypto::Ss58Codec, Pair as OtherPair};
use sp_keyring::{AccountKeyring, Sr25519Keyring};
use std::{str, str::FromStr, time::Duration};
use subxt::{
backend::legacy::LegacyRpcMethods,
config::PolkadotExtrinsicParamsBuilder as Params,
ext::{
sp_core::{hashing::blake2_256, sr25519, sr25519::Signature, Pair},
sp_runtime::AccountId32,
},
ext::sp_core::{hashing::blake2_256, sr25519, sr25519::Signature, Pair},
tx::{PairSigner, TxStatus},
utils::{AccountId32 as subxtAccountId32, MultiAddress, MultiSignature},
OnlineClient,
Expand All @@ -78,12 +74,8 @@ use crate::{
entropy::runtime_types::pallet_registry::pallet::ProgramInstance, get_api, get_rpc,
EntropyConfig,
},
get_signer,
helpers::{
launch::{
development_mnemonic, load_kv_store, setup_mnemonic, threshold_account_id,
ValidatorName,
},
launch::{development_mnemonic, load_kv_store, ValidatorName},
signing::Hasher,
substrate::{get_oracle_data, get_signers_from_chain, query_chain, submit_transaction},
tests::{
Expand All @@ -101,26 +93,6 @@ use crate::{
validation::EncryptedSignedMessage,
};

#[tokio::test]
#[serial]
async fn test_get_signer_does_not_throw_err() {
initialize_test_logger().await;
clean_tests();

let pair = <sr25519::Pair as Pair>::from_phrase(crate::helpers::launch::DEFAULT_MNEMONIC, None)
.expect("Issue converting mnemonic to pair");
let expected_account_id = AccountId32::new(pair.0.public().into()).to_ss58check();

let kv_store = load_kv_store(&None, None).await;
setup_mnemonic(&kv_store, development_mnemonic(&None)).await;
development_mnemonic(&None).to_string();
let account = threshold_account_id(&kv_store).await;

assert_eq!(account, expected_account_id);
get_signer(&kv_store).await.unwrap();
clean_tests();
}

#[tokio::test]
#[serial]
async fn test_signature_requests_fail_on_different_conditions() {
Expand Down

0 comments on commit 1ca0a0c

Please sign in to comment.