Skip to main content

bsv_wallet_cli/server/
mod.rs

1pub 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
20/// Lock that serializes spending operations (createAction).
21/// Non-spending endpoints (encrypt, getPublicKey, listOutputs, etc.) are unaffected.
22///
23/// Why: With limited UTXOs, concurrent createAction calls race on SQLite's write lock
24/// and the loser gets SQLITE_BUSY_SNAPSHOT instead of waiting for the winner's change
25/// output. This lock queues them so each spending request sees the previous one's change.
26pub type SpendingLock = Arc<tokio::sync::Mutex<()>>;
27
28/// TLS configuration (cert + key paths).
29#[derive(Clone)]
30#[allow(dead_code)]
31pub struct TlsConfig {
32    pub cert_path: String,
33    pub key_path: String,
34}
35
36/// Server configuration (auth, TLS, etc.)
37#[derive(Clone, Default)]
38pub struct ServerConfig {
39    /// Optional bearer token. When set, all requests must include
40    /// `Authorization: Bearer <token>`. When None, auth is disabled.
41    pub auth_token: Option<String>,
42    /// Optional TLS config. Requires `--features tls` at build time.
43    pub tls: Option<TlsConfig>,
44}
45
46/// Auth middleware — checks Bearer token if configured.
47async fn auth_middleware(headers: HeaderMap, request: Request, next: Next) -> Response {
48    // Extract config from request extensions
49    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
75/// Build the axum Router with all 28 WalletInterface endpoints.
76pub 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        // Existing 5 endpoints
83        // Status endpoints accept BOTH GET and POST: @bsv/sdk's HTTPWalletJSON substrate
84        // POSTs every method (incl. these), while curl/CLI clients GET them. Supporting
85        // both makes the server wire-compatible with browser WalletClient connections.
86        .route(
87            "/isAuthenticated",
88            get(handlers::is_authenticated).post(handlers::is_authenticated),
89        )
90        .route("/getPublicKey", post(handlers::get_public_key))
91        .route("/createSignature", post(handlers::create_signature))
92        .route("/createAction", post(handlers::create_action))
93        .route("/internalizeAction", post(handlers::internalize_action))
94        // Batch 1: Status (GET + POST for HTTPWalletJSON compat)
95        .route(
96            "/getHeight",
97            get(handlers::get_height).post(handlers::get_height),
98        )
99        .route(
100            "/getNetwork",
101            get(handlers::get_network).post(handlers::get_network),
102        )
103        .route(
104            "/getVersion",
105            get(handlers::get_version).post(handlers::get_version),
106        )
107        .route(
108            "/waitForAuthentication",
109            get(handlers::wait_for_authentication).post(handlers::wait_for_authentication),
110        )
111        // Batch 2: Header
112        .route("/getHeaderForHeight", post(handlers::get_header_for_height))
113        // Batch 3: Crypto
114        .route("/verifySignature", post(handlers::verify_signature))
115        .route("/encrypt", post(handlers::encrypt))
116        .route("/decrypt", post(handlers::decrypt))
117        .route("/createHmac", post(handlers::create_hmac))
118        .route("/verifyHmac", post(handlers::verify_hmac))
119        // Batch 4: Transaction workflow
120        .route("/signAction", post(handlers::sign_action))
121        .route("/abortAction", post(handlers::abort_action))
122        .route("/listActions", post(handlers::list_actions))
123        .route("/listOutputs", post(handlers::list_outputs))
124        .route("/relinquishOutput", post(handlers::relinquish_output))
125        // Batch 5: Certificates
126        .route("/acquireCertificate", post(handlers::acquire_certificate))
127        .route("/listCertificates", post(handlers::list_certificates))
128        .route("/proveCertificate", post(handlers::prove_certificate))
129        .route(
130            "/relinquishCertificate",
131            post(handlers::relinquish_certificate),
132        )
133        // Batch 6: Discovery + Key linkage
134        .route(
135            "/discoverByIdentityKey",
136            post(handlers::discover_by_identity_key),
137        )
138        .route(
139            "/discoverByAttributes",
140            post(handlers::discover_by_attributes),
141        )
142        .route(
143            "/revealCounterpartyKeyLinkage",
144            post(handlers::reveal_counterparty_key_linkage),
145        )
146        .route(
147            "/revealSpecificKeyLinkage",
148            post(handlers::reveal_specific_key_linkage),
149        )
150        // Layer ordering: CORS (outermost) → auth → trace → body limit
151        .layer(cors)
152        .layer(middleware::from_fn(auth_middleware))
153        .layer(axum::Extension(cfg))
154        .layer(axum::Extension(spending_lock))
155        .layer(TraceLayer::new_for_http())
156        .layer(DefaultBodyLimit::max(50 * 1024 * 1024))
157        .with_state(wallet)
158}
159
160pub async fn run(wallet: WalletState, port: u16, config: ServerConfig) -> Result<()> {
161    let tls = config.tls.clone();
162    let app = make_router(wallet, config);
163    let addr = SocketAddr::from(([127, 0, 0, 1], port));
164
165    #[cfg(feature = "tls")]
166    if let Some(tls_cfg) = tls {
167        use axum_server::tls_rustls::RustlsConfig;
168        let rustls = RustlsConfig::from_pem_file(&tls_cfg.cert_path, &tls_cfg.key_path).await?;
169        tracing::info!("HTTPS server listening on {addr}");
170        eprintln!("HTTPS server listening on {addr}");
171        axum_server::bind_rustls(addr, rustls)
172            .serve(app.into_make_service())
173            .await?;
174        return Ok(());
175    }
176
177    #[cfg(not(feature = "tls"))]
178    if tls.is_some() {
179        anyhow::bail!("TLS requested but binary was built without `--features tls`");
180    }
181
182    tracing::info!("HTTP server listening on {addr}");
183    eprintln!("HTTP server listening on {addr}");
184
185    let listener = tokio::net::TcpListener::bind(addr).await?;
186    axum::serve(listener, app)
187        .with_graceful_shutdown(shutdown_signal())
188        .await?;
189
190    Ok(())
191}
192
193pub fn make_wallet_state(wallet: Wallet<StorageSqlx, Services>) -> WalletState {
194    Arc::new(wallet)
195}
196
197/// Build a `WalletState` from an existing `Arc<Wallet>`.
198///
199/// Use this when the caller is already holding an `Arc<Wallet>` and wants the
200/// HTTP server to share the *same* wallet instance — same identity key, same
201/// balance, same UTXO set. Avoids opening a second `Wallet` handle against
202/// the same SQLite DB (which would work via busy_timeout but adds write
203/// contention and a second instance of any in-memory caches).
204#[allow(dead_code)] // public API for external callers; not used inside this binary
205pub fn make_wallet_state_from_arc(wallet: Arc<Wallet<StorageSqlx, Services>>) -> WalletState {
206    wallet
207}
208
209async fn shutdown_signal() {
210    tokio::signal::ctrl_c()
211        .await
212        .expect("failed to listen for ctrl-c");
213    eprintln!("\nShutting down...");
214}