Skip to content

Commit

Permalink
Rm persisted TSS keys
Browse files Browse the repository at this point in the history
  • Loading branch information
ameba23 committed Dec 13, 2024
1 parent 8a8cb52 commit 542849e
Show file tree
Hide file tree
Showing 6 changed files with 66 additions and 90 deletions.
6 changes: 4 additions & 2 deletions crates/threshold-signature-server/src/attestation/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ pub async fn attest(
State(app_state): State<AppState>,
input: Bytes,
) -> Result<StatusCode, AttestationErr> {
let (signer, x25519_secret) = get_signer_and_x25519_secret(&app_state.kv_store).await?;
let signer = app_state.signer;
let x25519_secret = app_state.x25519_secret;
let attestation_requests = OcwMessageAttestationRequest::decode(&mut input.as_ref())?;

let api = get_api(&app_state.configuration.endpoint).await?;
Expand Down Expand Up @@ -94,7 +95,8 @@ pub async fn get_attest(
State(app_state): State<AppState>,
Query(context_querystring): Query<QuoteContextQuery>,
) -> Result<(StatusCode, Vec<u8>), AttestationErr> {
let (signer, x25519_secret) = get_signer_and_x25519_secret(&app_state.kv_store).await?;
let signer = app_state.signer;
let x25519_secret = app_state.x25519_secret;
let api = get_api(&app_state.configuration.endpoint).await?;
let rpc = get_rpc(&app_state.configuration.endpoint).await?;

Expand Down
104 changes: 37 additions & 67 deletions crates/threshold-signature-server/src/helpers/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,73 +236,43 @@ pub fn development_mnemonic(validator_name: &Option<ValidatorName>) -> bip39::Mn
.expect("Unable to parse given mnemonic.")
}

pub async fn setup_mnemonic(kv: &KvManager, mnemonic: bip39::Mnemonic) {
if has_mnemonic(kv).await {
tracing::warn!("Deleting account related keys from KVDB.");

kv.kv()
.delete(FORBIDDEN_KEY_MNEMONIC)
.await
.expect("Error deleting existing mnemonic from KVDB.");
kv.kv()
.delete(FORBIDDEN_KEY_SHARED_SECRET)
.await
.expect("Error deleting shared secret from KVDB.");
kv.kv()
.delete(FORBIDDEN_KEY_DIFFIE_HELLMAN_PUBLIC)
.await
.expect("Error deleting X25519 public key from KVDB.");
}

tracing::info!("Writing new mnemonic to KVDB.");

// Write our new mnemonic to the KVDB.
let reservation = kv
.kv()
.reserve_key(FORBIDDEN_KEY_MNEMONIC.to_string())
.await
.expect("Issue reserving mnemonic");
kv.kv()
.put(reservation, mnemonic.to_string().as_bytes().to_vec())
.await
.expect("failed to update mnemonic");

let (pair, static_secret) =
get_signer_and_x25519_secret(kv).await.expect("Cannot derive keypairs");
let x25519_public_key = x25519_dalek::PublicKey::from(&static_secret).to_bytes();

// Write the shared secret in the KVDB
let shared_secret_reservation = kv
.kv()
.reserve_key(FORBIDDEN_KEY_SHARED_SECRET.to_string())
.await
.expect("Issue reserving ss key");
kv.kv()
.put(shared_secret_reservation, static_secret.to_bytes().to_vec())
.await
.expect("failed to update secret share");

// Write the Diffie-Hellman key in the KVDB
let diffie_hellman_reservation = kv
.kv()
.reserve_key(FORBIDDEN_KEY_DIFFIE_HELLMAN_PUBLIC.to_string())
.await
.expect("Issue reserving DH key");

kv.kv()
.put(diffie_hellman_reservation, x25519_public_key.to_vec())
.await
.expect("failed to update dh");

// Now we write the TSS AccountID and X25519 public key to files for convenience reasons.
let formatted_dh_public = format!("{x25519_public_key:?}").replace('"', "");
fs::write(".entropy/public_key", formatted_dh_public).expect("Failed to write public key file");

let id = AccountId32::new(pair.signer().public().0);
fs::write(".entropy/account_id", format!("{id}")).expect("Failed to write account_id file");

tracing::debug!("Starting process with account ID: `{id}`");
}
// pub async fn setup_mnemonic(mnemonic: bip39::Mnemonic) -> (sr25519::Pair, StaticSecret) {
// let (pair, static_secret) =
// get_signer_and_x25519_secret(kv).await.expect("Cannot derive keypairs");
// let x25519_public_key = x25519_dalek::PublicKey::from(&static_secret).to_bytes();
//
// // Write the shared secret in the KVDB
// let shared_secret_reservation = kv
// .kv()
// .reserve_key(FORBIDDEN_KEY_SHARED_SECRET.to_string())
// .await
// .expect("Issue reserving ss key");
// kv.kv()
// .put(shared_secret_reservation, static_secret.to_bytes().to_vec())
// .await
// .expect("failed to update secret share");
//
// // Write the Diffie-Hellman key in the KVDB
// let diffie_hellman_reservation = kv
// .kv()
// .reserve_key(FORBIDDEN_KEY_DIFFIE_HELLMAN_PUBLIC.to_string())
// .await
// .expect("Issue reserving DH key");
//
// kv.kv()
// .put(diffie_hellman_reservation, x25519_public_key.to_vec())
// .await
// .expect("failed to update dh");
//
// // Now we write the TSS AccountID and X25519 public key to files for convenience reasons.
// let formatted_dh_public = format!("{x25519_public_key:?}").replace('"', "");
// fs::write(".entropy/public_key", formatted_dh_public).expect("Failed to write public key file");
//
// let id = AccountId32::new(pair.signer().public().0);
// fs::write(".entropy/account_id", format!("{id}")).expect("Failed to write account_id file");
//
// tracing::debug!("Starting process with account ID: `{id}`");
// }

pub async fn threshold_account_id(kv: &KvManager) -> String {
let mnemonic = kv.kv().get(FORBIDDEN_KEY_MNEMONIC).await.expect("Issue getting mnemonic");
Expand Down
5 changes: 2 additions & 3 deletions crates/threshold-signature-server/src/helpers/signing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,8 @@ 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 (pair_signer, x25519_secret_key) = get_signer_and_x25519_secret(kv_manager)
.await
.map_err(|e| ProtocolErr::UserError(e.to_string()))?;
let pair_signer = &app_state.signer;
let x25519_secret_key = &app_state.x25519_secret;
let signer = pair_signer.signer();

let account_id = AccountId32(signer.public().0);
Expand Down
6 changes: 3 additions & 3 deletions crates/threshold-signature-server/src/helpers/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ pub async fn get_signer(

/// Get the PairSigner as above, and also the x25519 encryption keypair for
/// this threshold server
pub async fn get_signer_and_x25519_secret(
kv: &KvManager,
pub fn get_signer_and_x25519_secret(
mnemonic: &str,
) -> Result<(PairSigner<EntropyConfig, sr25519::Pair>, StaticSecret), UserErr> {
let hkdf = get_hkdf(kv).await?;
let hkdf = get_hkdf_from_mnemonic(mnemonic)?;
let pair_signer = get_signer_from_hkdf(&hkdf)?;
let static_secret = get_x25519_secret_from_hkdf(&hkdf)?;
Ok((pair_signer, static_secret))
Expand Down
24 changes: 19 additions & 5 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::{sr25519, Pair};
use subxt::tx::PairSigner;
use tower_http::{
cors::{Any, CorsLayer},
trace::{self, TraceLayer},
Expand All @@ -191,8 +192,9 @@ pub use crate::helpers::{
};
use crate::{
attestation::api::{attest, get_attest},
chain_api::EntropyConfig,
health::api::healthz,
launch::Configuration,
launch::{development_mnemonic, Configuration, ValidatorName},
node_info::api::{hashes, info, version as get_version},
r#unsafe::api::{delete, put, remove_keys, unsafe_get},
signing_client::{api::*, ListenerState},
Expand All @@ -203,18 +205,30 @@ use crate::{
#[derive(Clone)]
pub struct AppState {
listener_state: ListenerState,
pair: sr25519::Pair,
signer: PairSigner<EntropyConfig, sr25519::Pair>,
x25519_secret: StaticSecret,
x25519_public_key: [u8; 32],
pub configuration: Configuration,
pub kv_store: KvManager,
}

impl AppState {
pub fn new(configuration: Configuration, kv_store: KvManager) -> Self {
let (pair, _seed) = sr25519::Pair::generate();
let x25519_secret = StaticSecret::random_from_rng(&mut OsRng);
pub fn new(
configuration: Configuration,
kv_store: KvManager,
validator_name: &ValidatorName,
) -> Self {
let (pair, x25519_secret) = if cfg!(test) || validator_name.is_some() {
get_signer_and_x25519_secret(development_mnemonic(&validator_name))
} else {
let (pair, _seed) = sr25519::Pair::generate();
let x25519_secret = StaticSecret::random_from_rng(&mut OsRng);
(pair, x25519_secret)
};

let signer = PairSigner::<EntropyConfig, sr25519::Pair>::new(pair);
let x25519_public_key = x25519_dalek::PublicKey::from(&x25519_secret).to_bytes();

Self {
pair,
x25519_secret,
Expand Down
11 changes: 1 addition & 10 deletions crates/threshold-signature-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,7 @@ async fn main() {

let kv_store = load_kv_store(&validator_name, args.password_file).await;

let app_state = AppState::new(configuration.clone(), kv_store.clone());

if cfg!(test) || validator_name.is_some() {
setup_mnemonic(&kv_store, development_mnemonic(&validator_name)).await
} else if !has_mnemonic(&kv_store).await {
let mut rng = rand::thread_rng();
let mnemonic = bip39::Mnemonic::generate_in_with(&mut rng, bip39::Language::English, 24)
.expect("Failed to generate mnemonic");
setup_mnemonic(&kv_store, mnemonic).await
}
let app_state = AppState::new(configuration.clone(), kv_store.clone(), &validator_name);

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

Expand Down

0 comments on commit 542849e

Please sign in to comment.