|
| 1 | +use anyhow::{bail, Context, Result}; |
| 2 | +use serde::{Deserialize, Serialize}; |
| 3 | +use std::net::IpAddr; |
| 4 | +use tokio::{ |
| 5 | + io::{AsyncReadExt, AsyncWriteExt}, |
| 6 | + net::TcpStream, |
| 7 | +}; |
| 8 | + |
| 9 | +#[derive(Serialize, Deserialize)] |
| 10 | +struct QuoteRequest<'a> { |
| 11 | + quote: &'a [u8], |
| 12 | +} |
| 13 | + |
| 14 | +#[derive(Serialize, Deserialize, Debug)] |
| 15 | +pub struct QuoteResponse { |
| 16 | + pub encrypted_key: Vec<u8>, |
| 17 | + pub provider_quote: Vec<u8>, |
| 18 | +} |
| 19 | + |
| 20 | +pub async fn get_key(quote: Vec<u8>, address: IpAddr, port: u16) -> Result<QuoteResponse> { |
| 21 | + if quote.len() > 1024 * 1024 { |
| 22 | + bail!("Quote is too long"); |
| 23 | + } |
| 24 | + let mut tcp_stream = TcpStream::connect((address, port)) |
| 25 | + .await |
| 26 | + .context("Failed to connect to key provider")?; |
| 27 | + let payload = QuoteRequest { quote: "e }; |
| 28 | + let serialized = serde_json::to_vec(&payload)?; |
| 29 | + let length = serialized.len() as u32; |
| 30 | + tcp_stream |
| 31 | + .write_all(&length.to_be_bytes()) |
| 32 | + .await |
| 33 | + .context("Failed to write length")?; |
| 34 | + tcp_stream |
| 35 | + .write_all(&serialized) |
| 36 | + .await |
| 37 | + .context("Failed to write payload")?; |
| 38 | + |
| 39 | + let mut response_length = [0; 4]; |
| 40 | + tcp_stream |
| 41 | + .read_exact(&mut response_length) |
| 42 | + .await |
| 43 | + .context("Failed to read response length")?; |
| 44 | + let response_length = u32::from_be_bytes(response_length); |
| 45 | + let mut response = vec![0; response_length as usize]; |
| 46 | + tcp_stream |
| 47 | + .read_exact(&mut response) |
| 48 | + .await |
| 49 | + .context("Failed to read response")?; |
| 50 | + let response: QuoteResponse = |
| 51 | + serde_json::from_slice(&response).context("Failed to deserialize response")?; |
| 52 | + Ok(response) |
| 53 | +} |
0 commit comments