Skip to content

Commit

Permalink
Allow for entropy-tss to be put in a non-ready state
Browse files Browse the repository at this point in the history
  • Loading branch information
ameba23 committed Dec 16, 2024
1 parent 6831f49 commit 1c36ae0
Show file tree
Hide file tree
Showing 11 changed files with 66 additions and 8 deletions.
2 changes: 2 additions & 0 deletions crates/protocol/src/protocol_transport/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ pub enum WsError {
Serialization(#[from] bincode::Error),
#[error("Received bad subscribe message")]
BadSubscribeMessage,
#[error("Node has started fresh and not yet successfully set up")]
NotReady,
}

/// An error relating to handling a `ProtocolMessage`
Expand Down
15 changes: 15 additions & 0 deletions crates/threshold-signature-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ use axum::{
use entropy_kvdb::kv_manager::KvManager;
use rand_core::OsRng;
use sp_core::{crypto::AccountId32, sr25519, Pair};
use std::sync::{Arc, RwLock};
use subxt::{tx::PairSigner, utils::AccountId32 as SubxtAccountId32};
use tower_http::{
cors::{Any, CorsLayer},
Expand All @@ -201,6 +202,7 @@ use crate::{

#[derive(Clone)]
pub struct AppState {
ready: Arc<RwLock<bool>>,
listener_state: ListenerState,
pair: sr25519::Pair,
x25519_secret: StaticSecret,
Expand All @@ -223,6 +225,7 @@ impl AppState {
};

Self {
ready: Arc::new(RwLock::new(false)),
pair,
x25519_secret,
listener_state: ListenerState::default(),
Expand All @@ -231,6 +234,18 @@ impl AppState {
}
}

pub fn is_ready(&self) -> bool {
match self.ready.read() {
Ok(r) => *r,
_ => false,
}
}

pub fn make_ready(&self) {
let mut is_ready = self.ready.write().unwrap();
*is_ready = true;
}

/// Get a [PairSigner] for submitting extrinsics with subxt
pub fn signer(&self) -> PairSigner<EntropyConfig, sr25519::Pair> {
PairSigner::<EntropyConfig, sr25519::Pair>::new(self.pair.clone())
Expand Down
22 changes: 14 additions & 8 deletions crates/threshold-signature-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,21 @@ async fn main() {

setup_latest_block_number(&kv_store).await.expect("Issue setting up Latest Block Number");

// Below deals with syncing the kvdb
let addr = SocketAddr::from_str(&args.threshold_url).expect("failed to parse threshold url.");

entropy_tss::launch::check_node_prerequisites(
&app_state.configuration.endpoint,
&app_state.account_id().to_ss58check(),
)
.await;
{
let app_state = app_state.clone();
tokio::spawn(async move {
// Check for a connection to the chain node parallel to starting the tss_server so that
// we already can expose the `/info` http route
entropy_tss::launch::check_node_prerequisites(
&app_state.configuration.endpoint,
&app_state.account_id().to_ss58check(),
)
.await;
app_state.make_ready();
});
}

let addr = SocketAddr::from_str(&args.threshold_url).expect("failed to parse threshold url.");
let listener = tokio::net::TcpListener::bind(&addr)
.await
.expect("Unable to bind to given server address.");
Expand Down
2 changes: 2 additions & 0 deletions crates/threshold-signature-server/src/node_info/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub async fn hashes() -> Json<Vec<HashingAlgorithm>> {
/// Public signing and encryption keys associated with a TS server
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct TssPublicKeys {
pub connected_to_chain: bool,
pub tss_account: AccountId32,
pub x25519_public_key: X25519PublicKey,
}
Expand All @@ -43,6 +44,7 @@ pub struct TssPublicKeys {
#[tracing::instrument(skip_all)]
pub async fn info(State(app_state): State<AppState>) -> Result<Json<TssPublicKeys>, GetInfoError> {
Ok(Json(TssPublicKeys {
connected_to_chain: app_state.is_ready(),
x25519_public_key: app_state.x25519_public_key(),
tss_account: app_state.subxt_account_id(),
}))
Expand Down
4 changes: 4 additions & 0 deletions crates/threshold-signature-server/src/signing_client/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ pub async fn proactive_refresh(
State(app_state): State<AppState>,
encoded_data: Bytes,
) -> Result<StatusCode, ProtocolErr> {
if !app_state.is_ready() {
return Err(ProtocolErr::NotReady);
}

let ocw_data = OcwMessageProactiveRefresh::decode(&mut encoded_data.as_ref())?;
let api = get_api(&app_state.configuration.endpoint).await?;
let rpc = get_rpc(&app_state.configuration.endpoint).await?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ pub enum ProtocolErr {
Listener(#[from] entropy_protocol::errors::ListenerErr),
#[error("Failed to derive BIP-32 account: {0}")]
Bip32DerivationError(#[from] bip32::Error),
#[error("Node has started fresh and not yet successfully set up")]
NotReady,
}

impl IntoResponse for ProtocolErr {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ pub async fn open_protocol_connections(

/// Handle an incoming websocket connection
pub async fn handle_socket(socket: WebSocket, app_state: AppState) -> Result<(), WsError> {
if !app_state.is_ready() {
return Err(WsError::NotReady);
}

let (mut encrypted_connection, serialized_signed_message) =
noise_handshake_responder(socket, &app_state.x25519_secret)
.await
Expand Down
11 changes: 11 additions & 0 deletions crates/threshold-signature-server/src/user/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ pub async fn relay_tx(
State(app_state): State<AppState>,
Json(encrypted_msg): Json<EncryptedSignedMessage>,
) -> Result<(StatusCode, Body), UserErr> {
if !app_state.is_ready() {
return Err(UserErr::NotReady);
}
let api = get_api(&app_state.configuration.endpoint).await?;
let rpc = get_rpc(&app_state.configuration.endpoint).await?;

Expand Down Expand Up @@ -217,6 +220,10 @@ pub async fn sign_tx(
State(app_state): State<AppState>,
Json(encrypted_msg): Json<EncryptedSignedMessage>,
) -> Result<(StatusCode, Body), UserErr> {
if !app_state.is_ready() {
return Err(UserErr::NotReady);
}

let api = get_api(&app_state.configuration.endpoint).await?;
let rpc = get_rpc(&app_state.configuration.endpoint).await?;

Expand Down Expand Up @@ -378,6 +385,10 @@ pub async fn generate_network_key(
State(app_state): State<AppState>,
encoded_data: Bytes,
) -> Result<StatusCode, UserErr> {
if !app_state.is_ready() {
return Err(UserErr::NotReady);
}

let data = OcwMessageDkg::decode(&mut encoded_data.as_ref())?;
tracing::Span::current().record("block_number", data.block_number);

Expand Down
2 changes: 2 additions & 0 deletions crates/threshold-signature-server/src/user/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,8 @@ pub enum UserErr {
TooFewSigners,
#[error("Non signer sent from relayer")]
IncorrectSigner,
#[error("Node has started fresh and not yet successfully set up")]
NotReady,
}

impl From<hkdf::InvalidLength> for UserErr {
Expand Down
8 changes: 8 additions & 0 deletions crates/threshold-signature-server/src/validator/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ pub async fn new_reshare(
State(app_state): State<AppState>,
encoded_data: Bytes,
) -> Result<StatusCode, ValidatorErr> {
if !app_state.is_ready() {
return Err(ValidatorErr::NotReady);
}

let data = OcwMessageReshare::decode(&mut encoded_data.as_ref())?;

let api = get_api(&app_state.configuration.endpoint).await?;
Expand Down Expand Up @@ -204,6 +208,10 @@ async fn do_reshare(
pub async fn rotate_network_key(
State(app_state): State<AppState>,
) -> Result<StatusCode, ValidatorErr> {
if !app_state.is_ready() {
return Err(ValidatorErr::NotReady);
}

// validate from chain
let api = get_api(&app_state.configuration.endpoint).await?;
let rpc = get_rpc(&app_state.configuration.endpoint).await?;
Expand Down
2 changes: 2 additions & 0 deletions crates/threshold-signature-server/src/validator/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ pub enum ValidatorErr {
NotImplemented,
#[error("Input must be 32 bytes: {0}")]
TryFromSlice(#[from] TryFromSliceError),
#[error("Node has started fresh and not yet successfully set up")]
NotReady,
}

impl IntoResponse for ValidatorErr {
Expand Down

0 comments on commit 1c36ae0

Please sign in to comment.