Skip to content

Commit

Permalink
Basic server
Browse files Browse the repository at this point in the history
  • Loading branch information
Avi-D-coder committed Jan 18, 2024
1 parent 275b8eb commit 33f63eb
Show file tree
Hide file tree
Showing 8 changed files with 207 additions and 2 deletions.
5 changes: 5 additions & 0 deletions kairos-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ name = "kairos-server"
version.workspace = true
edition.workspace = true

[lib]

[[bin]]
name = "kairos-server"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
Expand Down
70 changes: 70 additions & 0 deletions kairos-server/src/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
use std::{
fmt,
ops::{Deref, DerefMut},
};

use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};



#[derive(Debug)]
pub struct AppErr {
error: anyhow::Error,
status: Option<StatusCode>,
}

impl AppErr {
pub fn set_status(err: impl Into<Self>, status: StatusCode) -> Self {
let mut err = err.into();
err.status = Some(status);
err
}
}

impl IntoResponse for AppErr {
fn into_response(self) -> Response {
(
self.status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
format!("{}", self.error),
)
.into_response()
}
}

impl Deref for AppErr {
type Target = anyhow::Error;
fn deref(&self) -> &Self::Target {
&self.error
}
}

impl DerefMut for AppErr {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.error
}
}

impl fmt::Display for AppErr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}: {}",
self.status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
self.error
)
}
}

impl std::error::Error for AppErr {}

impl From<anyhow::Error> for AppErr {
fn from(error: anyhow::Error) -> Self {
Self {
error,
status: None,
}
}
}
39 changes: 39 additions & 0 deletions kairos-server/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
pub mod errors;
pub mod routes;

use std::{
collections::{HashMap, HashSet},
sync::Arc,
};

use axum::{routing::post, Router};
use routes::{transfer::Transfer, *};
use tokio::sync::RwLock;

pub use errors::AppErr;

type PublicKey = String;

pub struct BatchState {
pub balances: HashMap<PublicKey, u64>,
pub batch_epoch: u64,
/// The set of transfers that will be batched in the next epoch.
pub batched_transfers: HashSet<Transfer>,
}
impl BatchState {
pub fn new() -> Arc<RwLock<Self>> {
Arc::new(RwLock::new(Self {
balances: HashMap::new(),
batch_epoch: 0,
batched_transfers: HashSet::new(),
}))
}
}

pub fn app_router(state: Arc<RwLock<BatchState>>) -> Router {
Router::new()
.route("/api/v1/mock/deposit", post(deposit))
.route("/api/v1/mock/withdraw", post(withdraw))
.route("/api/v1/transfer", post(transfer))
.with_state(state)
}
21 changes: 19 additions & 2 deletions kairos-server/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
fn main() {
println!("Hello, world!");
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
let axum_port: u16 = std::env::var("SERVER_PORT").map_or(8000, |x| {
x.parse().unwrap_or_else(|e| {
format!("Failed to parse SERVER_PORT: {}", e)
.parse()
.unwrap()
})
});

let app = kairos_server::app_router(kairos_server::BatchState::new());

let axum_addr = SocketAddr::from(([127, 0, 0, 1], axum_port));
tracing::info!("starting http server");
let listener = tokio::net::TcpListener::bind(axum_addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
20 changes: 20 additions & 0 deletions kairos-server/src/routes/deposit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use std::sync::Arc;

use axum::{extract::State, Json};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;

use crate::{AppErr, BatchState, PublicKey};

#[derive(Serialize, Deserialize)]
pub struct DepositRequest {
pub public_key: PublicKey,
pub amount: u64,
}

pub async fn deposit(
State(pool): State<Arc<RwLock<BatchState>>>,
Json(proof_request): Json<DepositRequest>,
) -> Result<(), AppErr> {
todo!("deposit")
}
7 changes: 7 additions & 0 deletions kairos-server/src/routes/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
pub mod deposit;
pub mod withdraw;
pub mod transfer;

pub use deposit::deposit;
pub use withdraw::withdraw;
pub use transfer::transfer;
27 changes: 27 additions & 0 deletions kairos-server/src/routes/transfer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use std::sync::Arc;

use axum::{extract::State, Json};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;

use crate::{AppErr, BatchState, PublicKey};

#[derive(Serialize, Deserialize)]
pub struct Transfer {
pub from: PublicKey,
pub to: PublicKey,
pub amount: u64,
}

#[derive(Serialize, Deserialize)]
pub struct TransferRequest {
transfer: Transfer,
signature: String,
}

pub async fn transfer(
State(pool): State<Arc<RwLock<BatchState>>>,
Json(proof_request): Json<TransferRequest>,
) -> Result<(), AppErr> {
todo!()
}
20 changes: 20 additions & 0 deletions kairos-server/src/routes/withdraw.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use std::sync::Arc;

use axum::{extract::State, Json};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;

use crate::{AppErr, BatchState, PublicKey};

#[derive(Serialize, Deserialize)]
pub struct WithdrawRequest {
pub public_key: PublicKey,
pub amount: u64,
}

pub async fn withdraw(
State(pool): State<Arc<RwLock<BatchState>>>,
Json(proof_request): Json<WithdrawRequest>,
) -> Result<(), AppErr> {
todo!()
}

0 comments on commit 33f63eb

Please sign in to comment.