Skip to content

Commit

Permalink
extractor to handle error responses
Browse files Browse the repository at this point in the history
  • Loading branch information
elnosh committed Mar 26, 2024
1 parent 0614e18 commit f0fb430
Show file tree
Hide file tree
Showing 7 changed files with 272 additions and 98 deletions.
13 changes: 13 additions & 0 deletions Cargo.lock

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

30 changes: 0 additions & 30 deletions mutiny-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -704,36 +704,6 @@ pub struct MutinyWalletConfig {
skip_hodl_invoices: bool,
}

impl MutinyWalletConfig {
pub fn new(
xprivkey: ExtendedPrivKey,
network: Network,
esplora: Option<String>,
rgs: Option<String>,
lsp: Option<String>,
) -> MutinyWalletConfig {
MutinyWalletConfig {
xprivkey,
#[cfg(target_arch = "wasm32")]
websocket_proxy_addr: None,
network,
user_esplora_url: esplora,
user_rgs_url: rgs,
lsp_url: lsp,
lsp_token: None,
lsp_connection_string: None,
auth_client: None,
subscription_url: None,
scorer_url: None,
primal_url: None,
do_not_connect_peers: false,
skip_device_lock: false,
safe_mode: false,
skip_hodl_invoices: true,
}
}
}

pub struct MutinyWalletBuilder<S: MutinyStorage> {
xprivkey: ExtendedPrivKey,
nostr_key_source: NostrKeySource,
Expand Down
4 changes: 2 additions & 2 deletions mutiny-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ mutiny-core = { path = "../mutiny-core" }

anyhow = "1.0.70"
async-trait = "0.1.68"
axum = "0.7.4"
axum = { version = "0.7.4" , features = ["default", "macros"]}
bitcoin = { version = "0.30.2" }
clap = { version = "4.1.14", features = ["derive"] }
lightning = { version = "0.0.121", default-features = false, features = ["max_level_trace", "grind_signatures", "std"] }
Expand All @@ -23,4 +23,4 @@ futures-util = { version = "0.3", default-features = false }
sled = "0.34.7"
tokio = { version = "1.36.0", features = ["full"] }
reqwest = { version = "0.11", features = ["json"] }
serde = { version = "1.0.196", features = ["derive"] }
serde = { version = "1.0.196", features = ["derive"] }
33 changes: 33 additions & 0 deletions mutiny-server/src/extractor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use async_trait::async_trait;
use axum::extract::{rejection::FormRejection, FromRequest, Request};
use axum::http::StatusCode;
use axum::Json;
use serde_json::{json, Value};

pub struct Form<T>(pub T);

#[async_trait]
impl<S, T> FromRequest<S> for Form<T>
where
axum::Form<T>: FromRequest<S, Rejection = FormRejection>,
S: Send + Sync,
{
type Rejection = (StatusCode, Json<Value>);

async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let (parts, body) = req.into_parts();

let request = Request::from_parts(parts, body);

match axum::Form::<T>::from_request(request, state).await {
Ok(value) => Ok(Self(value.0)),
Err(rejection) => {
let err_payload = json!({
"error": rejection.body_text()
});

Err((StatusCode::BAD_REQUEST, Json(err_payload)))
}
}
}
}
55 changes: 33 additions & 22 deletions mutiny-server/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
#![allow(incomplete_features)]

mod config;
mod sled;
mod extractor;
mod routes;
mod sled;

use crate::config::Config;
use crate::sled::SledStorage;
Expand All @@ -13,7 +14,7 @@ use bitcoin::bip32::ExtendedPrivKey;
use clap::Parser;
use log::{debug, info};
use mutiny_core::storage::MutinyStorage;
use mutiny_core::{generate_seed, MutinyWalletBuilder, MutinyWalletConfig};
use mutiny_core::{generate_seed, MutinyWalletBuilder, MutinyWalletConfigBuilder};
use shutdown::Shutdown;
use std::time::Duration;

Expand Down Expand Up @@ -41,18 +42,22 @@ async fn main() -> anyhow::Result<()> {
let seed = mnemonic.to_seed("");
let xprivkey = ExtendedPrivKey::new_master(network, &seed).unwrap();

let wallet_config = MutinyWalletConfig::new(
xprivkey,
network,
config.esplora_url,
config.rgs_url,
config.lsp_url,
);
let mut config_builder = MutinyWalletConfigBuilder::new(xprivkey).with_network(network);
if let Some(url) = config.esplora_url {
config_builder.with_user_esplora_url(url);
}
if let Some(url) = config.rgs_url {
config_builder.with_user_rgs_url(url);
}
if let Some(url) = config.lsp_url {
config_builder.with_lsp_url(url);
}
let wallet_config = config_builder.build();

debug!("Initializing wallet...");
let wallet = MutinyWalletBuilder::new(xprivkey, storage).with_config(wallet_config).build().await?;

let listener = tokio::net::TcpListener::bind(format!("{}:{}", config.bind, config.port))
let wallet = MutinyWalletBuilder::new(xprivkey, storage)
.with_config(wallet_config)
.build()
.await?;

debug!("Wallet initialized!");
Expand All @@ -61,17 +66,23 @@ async fn main() -> anyhow::Result<()> {
mutiny_wallet: wallet.clone(),
};

let server_router = Router::new()
.route("/newaddress", get(routes::new_address))
.route("/sendtoaddress", post(routes::send_to_address))
.route("/openchannel", post(routes::open_channel))
.route("/invoice", post(routes::create_invoice))
.route("/payinvoice", post(routes::pay_invoice))
.route("/balance", get(routes::get_balance))
.fallback(fallback)
.layer(Extension(state.clone()));
tokio::spawn(async move {
let server_router = Router::new()
.route("/newaddress", get(routes::new_address))
.route("/sendtoaddress", post(routes::send_to_address))
.route("/openchannel", post(routes::open_channel))
.route("/createinvoice", post(routes::create_invoice))
.route("/payinvoice", post(routes::pay_invoice))
.route("/balance", get(routes::get_balance))
.fallback(fallback)
.layer(Extension(state.clone()));

let listener = tokio::net::TcpListener::bind(format!("{}:{}", config.bind, config.port))
.await
.expect("failed to parse bind/port");

axum::serve(listener, server_router).await.unwrap();
axum::serve(listener, server_router).await.unwrap();
});

// wait for shutdown hook
shutdown.recv().await;
Expand Down
Loading

0 comments on commit f0fb430

Please sign in to comment.