hacker-challenge/src/persistence.rs
jakubDoka 09a84a15f3 rewrite (#2)
running clippy fix
separating homepage to a file
adding summary of network security
removing the rewrite structure
removing catch unwind
adding sealing to persistence
redirectng to the upstream
fixing some startup endgecases

Co-authored-by: Jakub Doka <jakub.doka2@gmail.com>
Reviewed-on: SGX/hacker-challenge-sgx#2
2024-11-08 14:33:42 +00:00

43 lines
1.4 KiB
Rust

use serde::{Deserialize, Serialize};
use solana_sdk::{pubkey::Pubkey, signature::keypair::Keypair};
use std::str::FromStr;
#[derive(Serialize, Deserialize)]
pub struct Data {
random: String,
keypair: String,
token: String,
}
impl Data {
pub async fn init_from(keypair: &Keypair, token: &Pubkey) -> Self {
use rand::{distributions::Alphanumeric, Rng};
let random_string: String =
rand::thread_rng().sample_iter(&Alphanumeric).take(128).map(char::from).collect();
Self {
random: random_string,
keypair: keypair.to_base58_string(),
token: token.to_string(),
}
}
pub async fn write(self, path: &str) -> Result<(), Box<dyn std::error::Error>> {
let serialized = serde_json::to_string(&self)?;
let sealed = detee_sgx::SealingConfig::new()?.seal_data(serialized.into_bytes())?;
tokio::fs::write(path, sealed).await.map_err(Into::into)
}
pub async fn read(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
let sealed = tokio::fs::read(path).await?;
let serialized = detee_sgx::SealingConfig::new()?.un_seal_data(sealed)?;
Ok(serde_json::from_str(&String::from_utf8(serialized)?)?)
}
pub fn parse(self) -> (Keypair, Pubkey) {
let keypair = Keypair::from_base58_string(&self.keypair);
let pubkey = Pubkey::from_str(&self.token).unwrap();
(keypair, pubkey)
}
}