Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup #2

Merged
merged 2 commits into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/target
/target-nix
.env
fm_client_db
.cargo
Expand Down
3 changes: 3 additions & 0 deletions JUSTFILE
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
set dotenv-load := true

dev:
mprocs -c mprocs.yaml

mprocs:
./scripts/mprocs-nix.sh dev-fed mprocs-new.yaml

alias b := build
Expand Down
10 changes: 5 additions & 5 deletions flake.lock

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

25 changes: 15 additions & 10 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
description = "A fedimint client daemon for server side applications to hold, use, and manage Bitcoin";

inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-23.11";
nixpkgs = {
url = "github:nixos/nixpkgs/nixos-23.11";
};

flakebox = {
url = "github:rustshop/flakebox";
Expand All @@ -20,11 +22,13 @@
outputs = { self, nixpkgs, flakebox, flake-utils, fedimint }:
flake-utils.lib.eachDefaultSystem (system:
let
nixpkgs = fedimint.inputs.nixpkgs;
pkgs = import nixpkgs {
inherit system;
overlays = fedimint.overlays.fedimint;
};
lib = pkgs.lib;
fmLib = fedimint.lib.${system};
flakeboxLib = flakebox.lib.${system} { };
rustSrc = flakeboxLib.filterSubPaths {
root = builtins.path {
Expand Down Expand Up @@ -87,14 +91,15 @@
packages = {
default = outputs.fedimint-clientd;
};
devShells = flakeboxLib.mkShells (commonArgs // {
toolchain = toolchainNative;
nativeBuildInputs = commonArgs.nativeBuildInputs ++ [
pkgs.mprocs
fedimint.packages.${system}.devimint
fedimint.packages.${system}.gateway-pkgs
fedimint.packages.${system}.fedimint-pkgs
];
});
devShells = fmLib.devShells // {
default = fmLib.devShells.default.overrideAttrs (prev: {
nativeBuildInputs = [
pkgs.mprocs
fedimint.packages.${system}.devimint
fedimint.packages.${system}.gateway-pkgs
fedimint.packages.${system}.fedimint-pkgs
] ++ prev.nativeBuildInputs;
});
};
});
}
2 changes: 1 addition & 1 deletion mprocs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ procs:
user:
shell: zsh
stop: SIGKILL
fedimint-http:
fedimint-clientd:
shell: cargo run
stop: SIGTERM
ngrok:
Expand Down
58 changes: 24 additions & 34 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,11 @@ use state::AppState;
// use tower_http::cors::{Any, CorsLayer};
use tower_http::validate_request::ValidateRequestHeaderLayer;

#[derive(Clone, Debug, ValueEnum)]
#[derive(Clone, Debug, ValueEnum, PartialEq)]
enum Mode {
Fedimint,
Cashu,
Rest,
Ws,
Default,
Cashu,
}

#[derive(Subcommand)]
Expand All @@ -43,11 +42,11 @@ enum Commands {
struct Cli {
/// Federation invite code
#[clap(long, env = "FEDIMINT_CLIENTD_INVITE_CODE", required = false)]
federation_invite_code: String,
invite_code: String,

/// Path to FM database
#[clap(long, env = "FEDIMINT_CLIENTD_DB_PATH", required = true)]
fm_db_path: PathBuf,
db_path: PathBuf,

/// Password
#[clap(long, env = "FEDIMINT_CLIENTD_PASSWORD", required = true)]
Expand All @@ -57,8 +56,8 @@ struct Cli {
#[clap(long, env = "FEDIMINT_CLIENTD_ADDR", required = true)]
addr: String,

/// Mode of operation
#[clap(long, default_value = "default")]
/// Mode: ws, rest
#[clap(long, default_value = "rest")]
mode: Mode,
}

Expand All @@ -70,11 +69,16 @@ async fn main() -> Result<()> {
dotenv::dotenv().ok();

let cli: Cli = Cli::parse();
let mut state = AppState::new(cli.fm_db_path).await?;
match InviteCode::from_str(&cli.federation_invite_code) {

let mut state = AppState::new(cli.db_path).await?;

match InviteCode::from_str(&cli.invite_code) {
Ok(invite_code) => {
let federation_id = state.multimint.register_new(invite_code, true).await?;
info!("Created client for federation id: {:?}", federation_id);
if cli.mode == Mode::Cashu {
state.cashu_mint = Some(federation_id);
}
}
Err(e) => {
info!(
Expand All @@ -84,20 +88,23 @@ async fn main() -> Result<()> {
}
}

if state.multimint.all().await.is_empty() {
return Err(anyhow::anyhow!("No clients found, must have at least one client to start the server. Try providing a federation invite code with the `--invite-code` flag or setting the `FEDIMINT_CLIENTD_INVITE_CODE` environment variable."));
}

let app = match cli.mode {
Mode::Fedimint => Router::new()
.nest("/fedimint/v2", fedimint_v2_rest())
Mode::Rest => Router::new()
.nest("/v2", fedimint_v2_rest())
.with_state(state)
.layer(ValidateRequestHeaderLayer::bearer(&cli.password)),
Mode::Cashu => Router::new()
.nest("/cashu/v1", cashu_v1_rest())
Mode::Ws => Router::new()
.route("/ws", get(websocket_handler))
.with_state(state)
.layer(ValidateRequestHeaderLayer::bearer(&cli.password)),
Mode::Ws => Router::new()
.route("/fedimint/v2/ws", get(websocket_handler))
Mode::Cashu => Router::new()
.nest("/v1", cashu_v1_rest())
.with_state(state)
.layer(ValidateRequestHeaderLayer::bearer(&cli.password)),
Mode::Default => create_default_router(state, &cli.password).await?,
};

let cors = CorsLayer::new()
Expand Down Expand Up @@ -132,23 +139,6 @@ async fn main() -> Result<()> {
Ok(())
}

pub async fn create_default_router(state: AppState, password: &str) -> Result<Router> {
// TODO: Allow CORS? Probably not, since this should just interact with the
// local machine. let cors = CorsLayer::new()
// .allow_methods([Method::GET, Method::POST])
// .allow_origin(Any);

let app = Router::new()
.route("/fedimint/v2/ws", get(websocket_handler))
.nest("/fedimint/v2", fedimint_v2_rest())
.nest("/cashu/v1", cashu_v1_rest())
.with_state(state)
// .layer(cors)
.layer(ValidateRequestHeaderLayer::bearer(password));

Ok(app)
}

/// Implements Fedimint V0.2 API Route matching against CLI commands:
/// - `/fedimint/v2/admin/backup`: Upload the (encrypted) snapshot of mint notes
/// to federation.
Expand Down
11 changes: 1 addition & 10 deletions src/router/handlers/cashu/info.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::collections::BTreeMap;

use axum::extract::State;
use axum::http::StatusCode;
use axum::Json;
use serde::Serialize;

Expand Down Expand Up @@ -43,15 +42,7 @@ pub struct CashuNUT06InfoResponse {
pub async fn handle_info(
State(state): State<AppState>,
) -> Result<Json<CashuNUT06InfoResponse>, AppError> {
let client = match state.multimint.get_default().await {
Some(client) => client,
None => {
return Err(AppError::new(
StatusCode::INTERNAL_SERVER_ERROR,
anyhow::anyhow!("No default client"),
))
}
};
let client = state.get_cashu_client().await?;

let config = client.get_config();
let mut nuts = BTreeMap::new();
Expand Down
2 changes: 1 addition & 1 deletion src/router/handlers/cashu/melt/method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub struct PostMeltQuoteMethodRequest {
pub request: String,
pub amount: Amount,
pub unit: Unit,
pub federation_id: Option<FederationId>,
pub federation_id: FederationId,
}

#[derive(Debug, Serialize)]
Expand Down
2 changes: 1 addition & 1 deletion src/router/handlers/cashu/mint/method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::state::AppState;
pub struct PostMintQuoteMethodRequest {
pub amount: Amount,
pub unit: Unit,
pub federation_id: Option<FederationId>,
pub federation_id: FederationId,
}

#[derive(Debug, Serialize)]
Expand Down
2 changes: 1 addition & 1 deletion src/router/handlers/cashu/swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::state::AppState;
#[derive(Debug, Deserialize)]
pub struct SwapRequest {
pub notes: OOBNotes,
pub federation_id: Option<FederationId>,
pub federation_id: FederationId,
}

#[derive(Debug, Serialize)]
Expand Down
2 changes: 1 addition & 1 deletion src/router/handlers/fedimint/admin/backup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::state::AppState;
#[serde(rename_all = "camelCase")]
pub struct BackupRequest {
pub metadata: BTreeMap<String, String>,
pub federation_id: Option<FederationId>,
pub federation_id: FederationId,
}

async fn _backup(client: ClientArc, req: BackupRequest) -> Result<(), AppError> {
Expand Down
4 changes: 2 additions & 2 deletions src/router/handlers/fedimint/admin/list_operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::state::AppState;
#[serde(rename_all = "camelCase")]
pub struct ListOperationsRequest {
pub limit: usize,
pub federation_id: Option<FederationId>,
pub federation_id: FederationId,
}

#[derive(Serialize)]
Expand Down Expand Up @@ -88,7 +88,7 @@ pub async fn handle_rest(
State(state): State<AppState>,
Json(req): Json<ListOperationsRequest>,
) -> Result<Json<Value>, AppError> {
let client = state.get_client(None).await?;
let client = state.get_client(req.federation_id).await?;
let operations = _list_operations(client, req).await?;
Ok(Json(operations))
}
2 changes: 1 addition & 1 deletion src/router/handlers/fedimint/admin/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub enum ModuleSelector {
pub struct ModuleRequest {
pub module: ModuleSelector,
pub args: Vec<String>,
pub federation_id: Option<FederationId>,
pub federation_id: FederationId,
}

async fn _module(_client: ClientArc, _req: ModuleRequest) -> Result<(), AppError> {
Expand Down
16 changes: 8 additions & 8 deletions src/router/handlers/fedimint/admin/restore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,18 @@ async fn _restore(_client: ClientArc, _v: Value) -> Result<(), AppError> {
))
}

pub async fn handle_ws(state: AppState, v: Value) -> Result<Value, AppError> {
let client = state.get_client(None).await?;
_restore(client, v).await?;
Ok(json!(()))
pub async fn handle_ws(_state: AppState, _v: Value) -> Result<Value, AppError> {
// let client = state.get_client(v).await?;
// _restore(client, v).await?;
Ok(json!(null))
}

#[axum_macros::debug_handler]
pub async fn handle_rest(
State(state): State<AppState>,
Json(req): Json<Value>,
State(_state): State<AppState>,
Json(_req): Json<Value>,
) -> Result<Json<()>, AppError> {
let client = state.get_client(None).await?;
_restore(client, req).await?;
// let client = state.get_client(None).await?;
// _restore(client, req).await?;
Ok(Json(()))
}
2 changes: 1 addition & 1 deletion src/router/handlers/fedimint/ln/await_invoice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::state::AppState;
#[serde(rename_all = "camelCase")]
pub struct AwaitInvoiceRequest {
pub operation_id: OperationId,
pub federation_id: Option<FederationId>,
pub federation_id: FederationId,
}

async fn _await_invoice(
Expand Down
2 changes: 1 addition & 1 deletion src/router/handlers/fedimint/ln/await_pay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::state::AppState;
#[serde(rename_all = "camelCase")]
pub struct AwaitLnPayRequest {
pub operation_id: OperationId,
pub federation_id: Option<FederationId>,
pub federation_id: FederationId,
}

async fn _await_pay(client: ClientArc, req: AwaitLnPayRequest) -> Result<LnPayResponse, AppError> {
Expand Down
2 changes: 1 addition & 1 deletion src/router/handlers/fedimint/ln/invoice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub struct LnInvoiceRequest {
pub amount_msat: Amount,
pub description: String,
pub expiry_time: Option<u64>,
pub federation_id: Option<FederationId>,
pub federation_id: FederationId,
}

#[derive(Debug, Serialize)]
Expand Down
2 changes: 1 addition & 1 deletion src/router/handlers/fedimint/ln/list_gateways.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::state::AppState;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListGatewaysRequest {
pub federation_id: Option<FederationId>,
pub federation_id: FederationId,
}

async fn _list_gateways(client: ClientArc) -> Result<Value, AppError> {
Expand Down
6 changes: 3 additions & 3 deletions src/router/handlers/fedimint/ln/pay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub struct LnPayRequest {
pub amount_msat: Option<Amount>,
pub finish_in_background: bool,
pub lnurl_comment: Option<String>,
pub federeation_id: Option<FederationId>,
pub federation_id: FederationId,
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -68,7 +68,7 @@ async fn _pay(client: ClientArc, req: LnPayRequest) -> Result<LnPayResponse, App
pub async fn handle_ws(state: AppState, v: Value) -> Result<Value, AppError> {
let v = serde_json::from_value::<LnPayRequest>(v)
.map_err(|e| AppError::new(StatusCode::BAD_REQUEST, anyhow!("Invalid request: {}", e)))?;
let client = state.get_client(v.federeation_id).await?;
let client = state.get_client(v.federation_id).await?;
let pay = _pay(client, v).await?;
let pay_json = json!(pay);
Ok(pay_json)
Expand All @@ -79,7 +79,7 @@ pub async fn handle_rest(
State(state): State<AppState>,
Json(req): Json<LnPayRequest>,
) -> Result<Json<LnPayResponse>, AppError> {
let client = state.get_client(req.federeation_id).await?;
let client = state.get_client(req.federation_id).await?;
let pay = _pay(client, req).await?;
Ok(Json(pay))
}
Loading
Loading