Skip to content

Commit

Permalink
Tests for post service GRPC client
Browse files Browse the repository at this point in the history
  • Loading branch information
poszu committed Sep 25, 2023
1 parent 478bf35 commit ecbb9a0
Show file tree
Hide file tree
Showing 10 changed files with 450 additions and 163 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ name = "service"
version = "0.1.0"
edition = "2021"

[[bin]]
name = "test-server"
path = "src/test_server.rs"
[lib]
name = "post_service"
path = "src/lib.rs"

[dependencies]
post-rs = { path = "../" }
Expand All @@ -17,13 +17,14 @@ tokio = { version = "1.0", features = [
"sync",
"time",
] }
tokio-stream = "0.1"
tokio-stream = { version = "0.1", features = ["net"] }
async-stream = "0.3.5"
log = "0.4.20"
eyre = "0.6.8"
env_logger = "0.10.0"
clap = { version = "4.4.4", features = ["derive"] }
hex = "0.4.3"
mockall = "0.11.4"

[build-dependencies]
tonic-build = "0.10.0"
110 changes: 110 additions & 0 deletions service/src/bin/test_server.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use std::fs::read_to_string;
use std::time::Duration;

use clap::Parser;
use eyre::Context;
use tokio::sync::oneshot;
use tokio::time::sleep;
use tonic::transport::Server;
use tonic::transport::{Certificate, Identity, ServerTlsConfig};

use post_service::test_server::spacemesh_v1::post_service_server::PostServiceServer;
use post_service::test_server::spacemesh_v1::{
node_request, service_response, GenProofRequest, GenProofStatus, NodeRequest,
};
use post_service::test_server::{TestNodeRequest, TestPostService};

/// Post Service test server
#[derive(Parser, Debug)]
#[command(version, about)]
struct Cli {
#[command(flatten, next_help_heading = "TLS configuration")]
tls: Option<post_service::tls_config::Tls>,
}

#[tokio::main]
async fn main() -> eyre::Result<()> {
let args = Cli::parse();

let env = env_logger::Env::default().filter_or("RUST_LOG", "info");
env_logger::init_from_env(env);

let server = Server::builder();
let mut server = if let Some(tls) = args.tls {
log::info!(
"configuring TLS: CA cert: {}, cert: {}, key: {}",
tls.ca_cert.display(),
tls.cert.display(),
tls.key.display(),
);
let ca_cert = read_to_string(tls.ca_cert)?;
let cert = read_to_string(tls.cert)?;
let key = read_to_string(tls.key)?;

let tls = ServerTlsConfig::new()
.identity(Identity::from_pem(cert, key))
.client_ca_root(Certificate::from_pem(ca_cert));

server.tls_config(tls).wrap_err("setting up mTLS")?
} else {
log::info!("not configuring TLS");
server
};

let mut test_node = TestPostService::new();
let mut reg = test_node.register_for_connections();

let router = server.add_service(PostServiceServer::new(test_node));

let _handle = tokio::spawn(router.serve("[::1]:50051".parse()?));

loop {
// wait for the connection to be established
let tx = reg.recv().await?;

loop {
let (resp_tx, resp_rx) = oneshot::channel();
if let Err(e) = tx
.send(TestNodeRequest {
request: NodeRequest {
kind: Some(node_request::Kind::GenProof(GenProofRequest {
challenge: vec![0xCA; 32],
})),
},
response: resp_tx,
})
.await
{
log::error!("post service disconnected: {e:?}");
break;
}

let resp = resp_rx.await?;
match resp.kind {
Some(service_response::Kind::GenProof(resp)) => {
log::debug!("Got GenProof response: {resp:?}");
match resp.status() {
GenProofStatus::Ok => {
if let Some(proof) = resp.proof {
log::info!("POST proof generation finished, proof: {:?}", proof);
// break;
}
log::info!("POST proof generation in progress");
}
GenProofStatus::Unspecified => {
log::error!("unspecified status");
}
GenProofStatus::Error => {
log::error!("POST proof generation error");
break;
}
}
}
_ => {
log::error!("Got unexpected response: {:?}", resp);
}
}
sleep(Duration::from_secs(5)).await;
}
}
}
18 changes: 12 additions & 6 deletions service/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,23 @@ pub mod spacemesh_v1 {
tonic::include_proto!("spacemesh.v1");
}

pub(crate) struct ServiceClient {
pub struct ServiceClient<S: PostService> {
endpoint: Endpoint,
reconnect_interval: Duration,
service: crate::service::PostService,
service: S,
}

impl ServiceClient {
pub(crate) fn new(
#[mockall::automock]
pub trait PostService {
fn gen_proof(&mut self, challenge: Vec<u8>) -> eyre::Result<ProofGenState>;
}

impl<S: PostService> ServiceClient<S> {
pub fn new(
address: String,
reconnect_interval: Duration,
cert: Option<(Certificate, Identity)>,
service: crate::service::PostService,
service: S,
) -> eyre::Result<Self> {
let endpoint = Channel::builder(address.parse()?);
let endpoint = match cert {
Expand All @@ -55,9 +60,10 @@ impl ServiceClient {
})
}

pub(crate) async fn run(mut self) -> eyre::Result<()> {
pub async fn run(mut self) -> eyre::Result<()> {
loop {
let client = loop {
log::debug!("connecting to the node on {}", self.endpoint.uri());
match PostServiceClient::connect(self.endpoint.clone()).await {
Ok(client) => break client,
Err(e) => {
Expand Down
4 changes: 4 additions & 0 deletions service/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pub mod client;
pub mod service;
pub mod test_server;
pub mod tls_config;
28 changes: 5 additions & 23 deletions service/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
mod client;
mod service;
mod tls_config;

use std::{fs::read_to_string, path::PathBuf, time::Duration};

use clap::{Args, Parser, ValueEnum};
use eyre::Context;
use post::pow::randomx::RandomXFlag;
use tonic::transport::{Certificate, Identity};

use post::pow::randomx::RandomXFlag;
use post_service::{client, tls_config::Tls};

/// Post Service
#[derive(Parser, Debug)]
#[command(version, about)]
Expand All @@ -30,7 +28,7 @@ struct Cli {
post_settings: PostSettings,

#[command(flatten, next_help_heading = "TLS configuration")]
tls: Option<tls_config::Tls>,
tls: Option<Tls>,
}

#[derive(Args, Debug)]
Expand Down Expand Up @@ -71,22 +69,6 @@ struct ScryptParams {
p: usize,
}

/// TLS configuration
///
/// Either all fields must be specified or none
#[derive(Args, Debug, Clone)]
#[group(required = false)]
pub(crate) struct Tls {
/// server CA certificate
#[arg(long, required = false)]
ca_cert: PathBuf,
/// client certificate
#[arg(long, required = false)]
client_cert: PathBuf,
/// client key
#[arg(long, required = false)]
client_key: PathBuf,
}
#[derive(Args, Debug)]
/// POST proof generation settings
struct PostSettings {
Expand Down Expand Up @@ -155,7 +137,7 @@ async fn main() -> eyre::Result<()> {
let env = env_logger::Env::default().filter_or("RUST_LOG", "info");
env_logger::init_from_env(env);

let service = service::PostService::new(
let service = post_service::service::PostService::new(
args.dir,
post::config::Config {
k1: args.post_config.k1,
Expand Down
10 changes: 6 additions & 4 deletions service/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::path::PathBuf;
use eyre::Context;
use post::{metadata::ProofMetadata, pow::randomx::RandomXFlag, prove::Proof};

pub(crate) enum ProofGenState {
pub enum ProofGenState {
InProgress,
Finished {
proof: Proof<'static>,
Expand All @@ -20,7 +20,7 @@ struct ProofGenProcess {
}

#[derive(Debug)]
pub(crate) struct PostService {
pub struct PostService {
id: [u8; 32],
datadir: PathBuf,
cfg: post::config::Config,
Expand All @@ -31,7 +31,7 @@ pub(crate) struct PostService {
}

impl PostService {
pub(crate) fn new(
pub fn new(
datadir: PathBuf,
cfg: post::config::Config,
nonces: usize,
Expand All @@ -51,8 +51,10 @@ impl PostService {
pow_flags,
})
}
}

pub(crate) fn gen_proof(&mut self, challenge: Vec<u8>) -> eyre::Result<ProofGenState> {
impl crate::client::PostService for PostService {
fn gen_proof(&mut self, challenge: Vec<u8>) -> eyre::Result<ProofGenState> {
if let Some(process) = &mut self.proof_generation {
eyre::ensure!(
process.challenge == challenge,
Expand Down
Loading

0 comments on commit ecbb9a0

Please sign in to comment.