bsv_wallet_cli/server/
mod.rs1pub mod handlers;
2pub mod types;
3
4use anyhow::Result;
5use axum::extract::{DefaultBodyLimit, Request};
6use axum::http::{HeaderMap, StatusCode};
7use axum::middleware::{self, Next};
8use axum::response::{IntoResponse, Response};
9use axum::routing::{get, post};
10use axum::{Json, Router};
11use bsv_wallet_toolbox::{Services, StorageSqlx, Wallet};
12use serde_json::json;
13use std::net::SocketAddr;
14use std::sync::Arc;
15use tower_http::cors::CorsLayer;
16use tower_http::trace::TraceLayer;
17
18use handlers::WalletState;
19
20pub type SpendingLock = Arc<tokio::sync::Mutex<()>>;
27
28#[derive(Clone)]
30#[allow(dead_code)]
31pub struct TlsConfig {
32 pub cert_path: String,
33 pub key_path: String,
34}
35
36#[derive(Clone, Default)]
38pub struct ServerConfig {
39 pub auth_token: Option<String>,
42 pub tls: Option<TlsConfig>,
44}
45
46async fn auth_middleware(headers: HeaderMap, request: Request, next: Next) -> Response {
48 let token = request
50 .extensions()
51 .get::<ServerConfig>()
52 .and_then(|c| c.auth_token.clone());
53
54 if let Some(expected) = token {
55 let provided = headers
56 .get("authorization")
57 .and_then(|v| v.to_str().ok())
58 .and_then(|v| v.strip_prefix("Bearer "));
59
60 match provided {
61 Some(t) if t == expected => {}
62 _ => {
63 return (
64 StatusCode::UNAUTHORIZED,
65 Json(json!({"code": "UNAUTHORIZED", "message": "Invalid or missing bearer token"})),
66 )
67 .into_response();
68 }
69 }
70 }
71
72 next.run(request).await
73}
74
75pub fn make_router(wallet: WalletState, config: ServerConfig) -> Router {
77 let cors = CorsLayer::very_permissive();
78 let cfg = config.clone();
79 let spending_lock: SpendingLock = Arc::new(tokio::sync::Mutex::new(()));
80
81 Router::new()
82 .route("/isAuthenticated", get(handlers::is_authenticated))
84 .route("/getPublicKey", post(handlers::get_public_key))
85 .route("/createSignature", post(handlers::create_signature))
86 .route("/createAction", post(handlers::create_action))
87 .route("/internalizeAction", post(handlers::internalize_action))
88 .route("/getHeight", get(handlers::get_height))
90 .route("/getNetwork", get(handlers::get_network))
91 .route("/getVersion", get(handlers::get_version))
92 .route(
93 "/waitForAuthentication",
94 get(handlers::wait_for_authentication),
95 )
96 .route("/getHeaderForHeight", post(handlers::get_header_for_height))
98 .route("/verifySignature", post(handlers::verify_signature))
100 .route("/encrypt", post(handlers::encrypt))
101 .route("/decrypt", post(handlers::decrypt))
102 .route("/createHmac", post(handlers::create_hmac))
103 .route("/verifyHmac", post(handlers::verify_hmac))
104 .route("/signAction", post(handlers::sign_action))
106 .route("/abortAction", post(handlers::abort_action))
107 .route("/listActions", post(handlers::list_actions))
108 .route("/listOutputs", post(handlers::list_outputs))
109 .route("/relinquishOutput", post(handlers::relinquish_output))
110 .route("/acquireCertificate", post(handlers::acquire_certificate))
112 .route("/listCertificates", post(handlers::list_certificates))
113 .route("/proveCertificate", post(handlers::prove_certificate))
114 .route(
115 "/relinquishCertificate",
116 post(handlers::relinquish_certificate),
117 )
118 .route(
120 "/discoverByIdentityKey",
121 post(handlers::discover_by_identity_key),
122 )
123 .route(
124 "/discoverByAttributes",
125 post(handlers::discover_by_attributes),
126 )
127 .route(
128 "/revealCounterpartyKeyLinkage",
129 post(handlers::reveal_counterparty_key_linkage),
130 )
131 .route(
132 "/revealSpecificKeyLinkage",
133 post(handlers::reveal_specific_key_linkage),
134 )
135 .layer(cors)
137 .layer(middleware::from_fn(auth_middleware))
138 .layer(axum::Extension(cfg))
139 .layer(axum::Extension(spending_lock))
140 .layer(TraceLayer::new_for_http())
141 .layer(DefaultBodyLimit::max(50 * 1024 * 1024))
142 .with_state(wallet)
143}
144
145pub async fn run(wallet: WalletState, port: u16, config: ServerConfig) -> Result<()> {
146 let tls = config.tls.clone();
147 let app = make_router(wallet, config);
148 let addr = SocketAddr::from(([127, 0, 0, 1], port));
149
150 #[cfg(feature = "tls")]
151 if let Some(tls_cfg) = tls {
152 use axum_server::tls_rustls::RustlsConfig;
153 let rustls = RustlsConfig::from_pem_file(&tls_cfg.cert_path, &tls_cfg.key_path).await?;
154 tracing::info!("HTTPS server listening on {addr}");
155 eprintln!("HTTPS server listening on {addr}");
156 axum_server::bind_rustls(addr, rustls)
157 .serve(app.into_make_service())
158 .await?;
159 return Ok(());
160 }
161
162 #[cfg(not(feature = "tls"))]
163 if tls.is_some() {
164 anyhow::bail!("TLS requested but binary was built without `--features tls`");
165 }
166
167 tracing::info!("HTTP server listening on {addr}");
168 eprintln!("HTTP server listening on {addr}");
169
170 let listener = tokio::net::TcpListener::bind(addr).await?;
171 axum::serve(listener, app)
172 .with_graceful_shutdown(shutdown_signal())
173 .await?;
174
175 Ok(())
176}
177
178pub fn make_wallet_state(wallet: Wallet<StorageSqlx, Services>) -> WalletState {
179 Arc::new(wallet)
180}
181
182#[allow(dead_code)] pub fn make_wallet_state_from_arc(wallet: Arc<Wallet<StorageSqlx, Services>>) -> WalletState {
191 wallet
192}
193
194async fn shutdown_signal() {
195 tokio::signal::ctrl_c()
196 .await
197 .expect("failed to listen for ctrl-c");
198 eprintln!("\nShutting down...");
199}