Skip to content

Commit

Permalink
Tidy AppState interface
Browse files Browse the repository at this point in the history
  • Loading branch information
ameba23 committed Dec 16, 2024
1 parent e71cc72 commit 6831f49
Show file tree
Hide file tree
Showing 7 changed files with 34 additions and 36 deletions.
4 changes: 2 additions & 2 deletions crates/threshold-signature-server/src/attestation/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub async fn attest(
validate_new_attestation(block_number, &attestation_requests, &app_state.kv_store).await?;

// Check whether there is an attestion request for us
if !attestation_requests.tss_account_ids.contains(&app_state.signer.public().0) {
if !attestation_requests.tss_account_ids.contains(&app_state.pair.public().0) {
return Ok(StatusCode::OK);
}

Expand Down Expand Up @@ -96,7 +96,7 @@ pub async fn get_attest(
let rpc = get_rpc(&app_state.configuration.endpoint).await?;

// Request attestation to get nonce
let nonce = request_attestation(&api, &rpc, &app_state.signer).await?;
let nonce = request_attestation(&api, &rpc, &app_state.pair).await?;

let context = context_querystring.as_quote_context()?;

Expand Down
2 changes: 1 addition & 1 deletion crates/threshold-signature-server/src/helpers/signing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub async fn do_signing(
let info = SignInit::new(relayer_signature_request.clone(), signing_session_info.clone());
let signing_service = ThresholdSigningService::new(state, kv_manager);
let x25519_secret_key = &app_state.x25519_secret;
let signer = &app_state.signer;
let signer = &app_state.pair;

let account_id = AccountId32(signer.public().0);

Expand Down
24 changes: 14 additions & 10 deletions crates/threshold-signature-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,8 @@ use crate::{
#[derive(Clone)]
pub struct AppState {
listener_state: ListenerState,
signer: sr25519::Pair,
pair: sr25519::Pair,
x25519_secret: StaticSecret,
x25519_public_key: [u8; 32],
pub configuration: Configuration,
pub kv_store: KvManager,
}
Expand All @@ -215,36 +214,41 @@ impl AppState {
kv_store: KvManager,
validator_name: &Option<ValidatorName>,
) -> Self {
let (signer, x25519_secret) = if cfg!(test) || validator_name.is_some() {
let (pair, x25519_secret) = if cfg!(test) || validator_name.is_some() {
get_signer_and_x25519_secret(&development_mnemonic(validator_name).to_string()).unwrap()
} else {
let (pair, _seed) = sr25519::Pair::generate();
let x25519_secret = StaticSecret::random_from_rng(OsRng);
(pair, x25519_secret)
};

let x25519_public_key = x25519_dalek::PublicKey::from(&x25519_secret).to_bytes();

Self {
signer,
pair,
x25519_secret,
x25519_public_key,
listener_state: ListenerState::default(),
configuration,
kv_store,
}
}

/// Get a [PairSigner] for submitting extrinsics with subxt
pub fn signer(&self) -> PairSigner<EntropyConfig, sr25519::Pair> {
PairSigner::<EntropyConfig, sr25519::Pair>::new(self.signer.clone())
PairSigner::<EntropyConfig, sr25519::Pair>::new(self.pair.clone())
}

/// Get the [AccountId32]
pub fn account_id(&self) -> AccountId32 {
AccountId32::new(self.signer.public().0)
AccountId32::new(self.pair.public().0)
}

/// Get the subxt account ID
pub fn subxt_account_id(&self) -> SubxtAccountId32 {
SubxtAccountId32(self.signer.public().0)
SubxtAccountId32(self.pair.public().0)
}

/// Get the x25519 public key
pub fn x25519_public_key(&self) -> [u8; 32] {
x25519_dalek::PublicKey::from(&self.x25519_secret).to_bytes()
}
}

Expand Down
7 changes: 4 additions & 3 deletions crates/threshold-signature-server/src/node_info/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ use crate::{node_info::errors::GetInfoError, AppState};
use axum::{extract::State, Json};
use entropy_shared::{types::HashingAlgorithm, X25519PublicKey};
use serde::{Deserialize, Serialize};
use sp_core::Pair;
use strum::IntoEnumIterator;
use subxt::utils::AccountId32;

Expand All @@ -43,6 +42,8 @@ pub struct TssPublicKeys {
/// Returns the TS server's public keys and HTTP endpoint
#[tracing::instrument(skip_all)]
pub async fn info(State(app_state): State<AppState>) -> Result<Json<TssPublicKeys>, GetInfoError> {
let tss_account = AccountId32(app_state.signer.public().0);
Ok(Json(TssPublicKeys { x25519_public_key: app_state.x25519_public_key, tss_account }))
Ok(Json(TssPublicKeys {
x25519_public_key: app_state.x25519_public_key(),
tss_account: app_state.subxt_account_id(),
}))
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub async fn proactive_refresh(
let api = get_api(&app_state.configuration.endpoint).await?;
let rpc = get_rpc(&app_state.configuration.endpoint).await?;

check_in_registration_group(&ocw_data.validators_info, app_state.signer().account_id())
check_in_registration_group(&ocw_data.validators_info, &app_state.subxt_account_id())
.map_err(|e| ProtocolErr::UserError(e.to_string()))?;
validate_proactive_refresh(&api, &rpc, &app_state.kv_store, &ocw_data).await?;

Expand Down
10 changes: 5 additions & 5 deletions crates/threshold-signature-server/src/user/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ pub async fn relay_tx(

signers_info
.iter()
.find(|signer_info| signer_info.tss_account == *app_state.signer().account_id())
.find(|signer_info| signer_info.tss_account == app_state.subxt_account_id())
.map_or(Ok(()), |_| Err(UserErr::RelayMessageSigner))?;

let signed_message = encrypted_msg.decrypt(&app_state.x25519_secret, &[])?;
Expand Down Expand Up @@ -152,7 +152,7 @@ pub async fn relay_tx(
.iter()
.map(|signer_info| async {
let signed_message = EncryptedSignedMessage::new(
&app_state.signer,
&app_state.pair,
serde_json::to_vec(&relayer_sig_req.clone())?,
&signer_info.x25519_public_key,
&[],
Expand Down Expand Up @@ -338,7 +338,7 @@ pub async fn sign_tx(

// Do the signing protocol in another task, so we can already respond
tokio::spawn(async move {
let signer = app_state.clone().signer;
let signer = app_state.pair.clone();
let signing_protocol_output = do_signing(
&rpc,
relayer_sig_request,
Expand Down Expand Up @@ -394,7 +394,7 @@ pub async fn generate_network_key(
if in_registration_group.is_err() {
tracing::warn!(
"The account {:?} is not in the registration group for block_number {:?}",
app_state.signer().account_id(),
app_state.subxt_account_id(),
data.block_number
);

Expand Down Expand Up @@ -454,7 +454,7 @@ async fn setup_dkg(
.ok_or_else(|| UserErr::OptionUnwrapError("Error getting block hash".to_string()))?;

let nonce_call =
entropy::apis().account_nonce_api().account_nonce(app_state.signer().account_id().clone());
entropy::apis().account_nonce_api().account_nonce(app_state.subxt_account_id());
let nonce = api.runtime_api().at(block_hash).call(nonce_call).await?;

// TODO: Error handling really complex needs to be thought about.
Expand Down
21 changes: 7 additions & 14 deletions crates/threshold-signature-server/src/validator/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ pub use entropy_protocol::{
};
use entropy_shared::{OcwMessageReshare, NETWORK_PARENT_KEY, NEXT_NETWORK_PARENT_KEY};
use parity_scale_codec::{Decode, Encode};
use sp_core::Pair;
use std::{collections::BTreeSet, str::FromStr};
use subxt::{
backend::legacy::LegacyRpcMethods, ext::sp_core::sr25519, tx::PairSigner, utils::AccountId32,
Expand Down Expand Up @@ -71,7 +70,7 @@ pub async fn new_reshare(

let is_proper_signer = validators_info
.iter()
.any(|validator_info| validator_info.tss_account == *app_state.signer().account_id());
.any(|validator_info| validator_info.tss_account == app_state.subxt_account_id());

if !is_proper_signer {
return Ok(StatusCode::MISDIRECTED_REQUEST);
Expand Down Expand Up @@ -111,7 +110,7 @@ async fn do_reshare(
.map_err(|_| ValidatorErr::Conversion("Verifying key conversion"))?,
)
.map_err(|e| ValidatorErr::VerifyingKeyError(e.to_string()))?;
let my_stash_address = get_stash_address(api, rpc, app_state.signer().account_id())
let my_stash_address = get_stash_address(api, rpc, &app_state.subxt_account_id())
.await
.map_err(|e| ValidatorErr::UserError(e.to_string()))?;

Expand Down Expand Up @@ -155,7 +154,7 @@ async fn do_reshare(
};

let session_id = SessionId::Reshare { verifying_key, block_number: data.block_number };
let account_id = AccountId32(app_state.signer.public().0);
let account_id = app_state.subxt_account_id();

let mut converted_validator_info = vec![];
let mut tss_accounts = vec![];
Expand All @@ -178,15 +177,9 @@ async fn do_reshare(
&app_state.x25519_secret,
)
.await?;
let (new_key_share, aux_info) = execute_reshare(
session_id.clone(),
channels,
&app_state.signer,
inputs,
&new_holders,
None,
)
.await?;
let (new_key_share, aux_info) =
execute_reshare(session_id.clone(), channels, &app_state.pair, inputs, &new_holders, None)
.await?;

let serialized_key_share = key_serialize(&(new_key_share, aux_info))
.map_err(|_| ProtocolErr::KvSerialize("Kv Serialize Error".to_string()))?;
Expand Down Expand Up @@ -227,7 +220,7 @@ pub async fn rotate_network_key(
.map_err(|e| ValidatorErr::UserError(e.to_string()))?;

let is_proper_signer = is_signer_or_delete_parent_key(
app_state.signer().account_id(),
&app_state.subxt_account_id(),
validators_info.clone(),
&app_state.kv_store,
)
Expand Down

0 comments on commit 6831f49

Please sign in to comment.