Skip to main content

bsv_wallet_cli/server/
mod.rs

1pub mod audit;
2pub mod broadcast_follow_up;
3pub mod handlers;
4pub mod post_word;
5pub mod types;
6
7use anyhow::Result;
8use axum::extract::{DefaultBodyLimit, Request};
9use axum::http::{HeaderMap, StatusCode};
10use axum::middleware::{self, Next};
11use axum::response::{IntoResponse, Response};
12use axum::routing::{get, post};
13use axum::{Json, Router};
14use bsv_wallet_toolbox::{Chain, Services, StorageSqlx, Wallet};
15use serde_json::json;
16use std::net::SocketAddr;
17use std::sync::Arc;
18use tower_http::cors::CorsLayer;
19use tower_http::trace::TraceLayer;
20
21use handlers::WalletState;
22
23/// Lock that serializes spending operations (createAction).
24/// Non-spending endpoints (encrypt, getPublicKey, listOutputs, etc.) are unaffected.
25///
26/// Why: With limited UTXOs, concurrent createAction calls race on SQLite's write lock
27/// and the loser gets SQLITE_BUSY_SNAPSHOT instead of waiting for the winner's change
28/// output. This lock queues them so each spending request sees the previous one's change.
29pub type SpendingLock = Arc<tokio::sync::Mutex<()>>;
30
31/// TLS configuration (cert + key paths).
32#[derive(Clone)]
33#[allow(dead_code)]
34pub struct TlsConfig {
35    pub cert_path: String,
36    pub key_path: String,
37}
38
39/// Server configuration (auth, TLS, etc.)
40#[derive(Clone)]
41pub struct ServerConfig {
42    /// Optional bearer token. When set, all requests must include
43    /// `Authorization: Bearer <token>`. When None, auth is disabled.
44    pub auth_token: Option<String>,
45    /// Optional TLS config. Requires `--features tls` at build time.
46    pub tls: Option<TlsConfig>,
47    /// Network the served wallet is on. Drives post-broadcast verification
48    /// (which ARC / WoC endpoints to probe). Defaults to `Main`.
49    pub chain: Chain,
50    /// Address to bind (default `127.0.0.1`). Set `BIND_ADDR=0.0.0.0` for the
51    /// tunnel/public-webhook case (`POST /arc-callback` behind cloudflared /
52    /// tailscale funnel / direct TLS).
53    pub bind_addr: std::net::IpAddr,
54    /// Per-wallet ARC/Arcade callback token. When set, `POST /arc-callback`
55    /// is enabled, authenticated by THIS token (`Authorization: Bearer` or
56    /// `X-CallbackToken`) and EXEMPT from the wallet bearer auth above.
57    pub callback_token: Option<String>,
58}
59
60impl Default for ServerConfig {
61    fn default() -> Self {
62        Self {
63            auth_token: None,
64            tls: None,
65            chain: Chain::Main,
66            bind_addr: std::net::IpAddr::from([127, 0, 0, 1]),
67            callback_token: None,
68        }
69    }
70}
71
72/// The address to bind: `BIND_ADDR` when it parses, else `127.0.0.1`. Read
73/// by every served command and by the bind guard, so the two agree.
74pub fn bind_addr_from_env() -> std::net::IpAddr {
75    std::env::var("BIND_ADDR")
76        .ok()
77        .and_then(|v| v.parse().ok())
78        .unwrap_or_else(|| std::net::IpAddr::from([127, 0, 0, 1]))
79}
80
81/// The bind guard (0.7.1). With no bearer token a served wallet answers any
82/// caller that can reach it, and its two BEEF doors take a body of any size
83/// (0.7.0), so an address beyond loopback needs a token or the operator's
84/// explicit `allow_no_token`. An empty token counts as none. Loopback is
85/// unchanged. Run at startup, before the wallet is opened or a socket bound.
86pub fn refuse_open_bind(
87    bind_addr: std::net::IpAddr,
88    auth_token: Option<&str>,
89    allow_no_token: bool,
90) -> Result<()> {
91    let has_token = auth_token.is_some_and(|t| !t.is_empty());
92    if has_token || allow_no_token || bind_addr.to_canonical().is_loopback() {
93        return Ok(());
94    }
95    anyhow::bail!(
96        "refusing to bind {bind_addr}: no bearer token is configured, and a wallet served \
97         beyond loopback without one answers anyone who can reach it. Set AUTH_TOKEN, or pass \
98         --allow-no-token to bind it open deliberately."
99    )
100}
101
102/// [`refuse_open_bind`] on the environment the served commands read
103/// (`BIND_ADDR`, `AUTH_TOKEN`).
104pub fn refuse_open_bind_from_env(allow_no_token: bool) -> Result<()> {
105    let token = std::env::var("AUTH_TOKEN").ok();
106    refuse_open_bind(bind_addr_from_env(), token.as_deref(), allow_no_token)
107}
108
109/// Auth middleware — checks Bearer token if configured.
110async fn auth_middleware(headers: HeaderMap, request: Request, next: Next) -> Response {
111    // /arc-callback is EXEMPT from wallet bearer auth: it is authenticated by
112    // the per-wallet callback token inside its own handler (ARC/Arcade call it
113    // with `Authorization: Bearer <callback-token>`, not the wallet token).
114    if request.uri().path() == "/arc-callback" {
115        return next.run(request).await;
116    }
117
118    // Extract config from request extensions
119    let token = request
120        .extensions()
121        .get::<ServerConfig>()
122        .and_then(|c| c.auth_token.clone());
123
124    if let Some(expected) = token {
125        let provided = headers
126            .get("authorization")
127            .and_then(|v| v.to_str().ok())
128            .and_then(|v| v.strip_prefix("Bearer "));
129
130        match provided {
131            Some(t) if t == expected => {}
132            _ => {
133                return (
134                    StatusCode::UNAUTHORIZED,
135                    Json(json!({"code": "UNAUTHORIZED", "message": "Invalid or missing bearer token"})),
136                )
137                    .into_response();
138            }
139        }
140    }
141
142    next.run(request).await
143}
144
145/// Build the axum Router with all 28 WalletInterface endpoints.
146pub fn make_router(wallet: WalletState, config: ServerConfig) -> Router {
147    let cors = CorsLayer::very_permissive();
148    let cfg = config.clone();
149    let spending_lock: SpendingLock = Arc::new(tokio::sync::Mutex::new(()));
150    // Post-broadcast verifier — lets `/createAction` fail loudly when ARC
151    // silently dropped an immediate broadcast (e.g. 465 fee-too-low on a deep
152    // unconfirmed BEEF) instead of returning a phantom txid.
153    let verifier = crate::broadcast_verify::BroadcastVerifier::from_env(config.chain);
154
155    Router::new()
156        // Existing 5 endpoints
157        // Status endpoints accept BOTH GET and POST: @bsv/sdk's HTTPWalletJSON substrate
158        // POSTs every method (incl. these), while curl/CLI clients GET them. Supporting
159        // both makes the server wire-compatible with browser WalletClient connections.
160        .route(
161            "/isAuthenticated",
162            get(handlers::is_authenticated).post(handlers::is_authenticated),
163        )
164        .route("/getPublicKey", post(handlers::get_public_key))
165        // PERMISSION AUDIT (not BRC-100): what a wallet with a human behind it
166        // would have prompted for. See `audit.rs` — this daemon grants everything
167        // silently, which is what makes it headless AND blind.
168        .route("/permission-audit", get(permission_audit))
169        .route("/permission-audit/reset", post(permission_audit_reset))
170        // CHAIN FEED (not BRC-100): the daemon's chain-event feed status,
171        // its stored cursor and, when it stopped, the fault it stopped on.
172        .route("/chain-feed", get(chain_feed_status))
173        .route("/createSignature", post(handlers::create_signature))
174        // The two doors that carry a caller's BEEF (`inputBEEF`, `tx`): no
175        // body cap, a valid BEEF is never refused for its size (see
176        // `BEEF_DOORS`).
177        .route(
178            "/createAction",
179            post(handlers::create_action).layer(DefaultBodyLimit::disable()),
180        )
181        .route(
182            "/internalizeAction",
183            post(handlers::internalize_action).layer(DefaultBodyLimit::disable()),
184        )
185        // Batch 1: Status (GET + POST for HTTPWalletJSON compat)
186        .route(
187            "/getHeight",
188            get(handlers::get_height).post(handlers::get_height),
189        )
190        .route(
191            "/getNetwork",
192            get(handlers::get_network).post(handlers::get_network),
193        )
194        .route(
195            "/getVersion",
196            get(handlers::get_version).post(handlers::get_version),
197        )
198        .route(
199            "/waitForAuthentication",
200            get(handlers::wait_for_authentication).post(handlers::wait_for_authentication),
201        )
202        // Batch 2: Header
203        .route("/getHeaderForHeight", post(handlers::get_header_for_height))
204        // Batch 3: Crypto
205        .route("/verifySignature", post(handlers::verify_signature))
206        .route("/encrypt", post(handlers::encrypt))
207        .route("/decrypt", post(handlers::decrypt))
208        .route("/createHmac", post(handlers::create_hmac))
209        .route("/verifyHmac", post(handlers::verify_hmac))
210        // Batch 4: Transaction workflow
211        .route("/signAction", post(handlers::sign_action))
212        .route("/abortAction", post(handlers::abort_action))
213        .route("/listActions", post(handlers::list_actions))
214        .route("/listOutputs", post(handlers::list_outputs))
215        .route("/relinquishOutput", post(handlers::relinquish_output))
216        // Batch 5: Certificates
217        .route("/acquireCertificate", post(handlers::acquire_certificate))
218        .route("/listCertificates", post(handlers::list_certificates))
219        .route("/proveCertificate", post(handlers::prove_certificate))
220        .route(
221            "/relinquishCertificate",
222            post(handlers::relinquish_certificate),
223        )
224        // Batch 6: Discovery + Key linkage
225        .route(
226            "/discoverByIdentityKey",
227            post(handlers::discover_by_identity_key),
228        )
229        .route(
230            "/discoverByAttributes",
231            post(handlers::discover_by_attributes),
232        )
233        .route(
234            "/revealCounterpartyKeyLinkage",
235            post(handlers::reveal_counterparty_key_linkage),
236        )
237        .route(
238            "/revealSpecificKeyLinkage",
239            post(handlers::reveal_specific_key_linkage),
240        )
241        // ARC/Arcade proof-delivery webhook (callback-token auth, exempt from
242        // wallet bearer auth — see auth_middleware).
243        .route("/arc-callback", post(arc_callback))
244        // The last layer added runs first: body limit, trace, the
245        // extensions, then auth BEFORE the body is read (an uncapped BEEF
246        // door is open only to the wallet's own caller), then the body.
247        .layer(cors)
248        .layer(middleware::from_fn(lenient_json_body))
249        .layer(middleware::from_fn(auth_middleware))
250        .layer(axum::Extension(cfg))
251        .layer(axum::Extension(spending_lock))
252        .layer(axum::Extension(verifier))
253        .layer(TraceLayer::new_for_http())
254        .layer(DefaultBodyLimit::max(BODY_CAP))
255        .with_state(wallet)
256}
257
258/// `POST /arc-callback` — ARC/Arcade status webhook receiving push status
259/// updates and (on MINED) the merkle path, straight into wallet storage.
260///
261/// Authenticated by the per-wallet callback token: ARC-convention
262/// `Authorization: Bearer <callback-token>` or an `X-CallbackToken` header
263/// (both accepted — broadcaster implementations vary). Returns 404 when no
264/// callback token is configured (route effectively disabled).
265async fn arc_callback(
266    axum::extract::State(wallet): axum::extract::State<WalletState>,
267    request: Request,
268) -> Response {
269    let expected = request
270        .extensions()
271        .get::<ServerConfig>()
272        .and_then(|c| c.callback_token.clone());
273    let Some(expected) = expected else {
274        return (
275            StatusCode::NOT_FOUND,
276            Json(json!({"code": "CALLBACK_DISABLED", "message": "no callback token configured"})),
277        )
278            .into_response();
279    };
280
281    let headers = request.headers().clone();
282    let provided = headers
283        .get("authorization")
284        .and_then(|v| v.to_str().ok())
285        .and_then(|v| v.strip_prefix("Bearer "))
286        .map(str::to_string)
287        .or_else(|| {
288            headers
289                .get("x-callbacktoken")
290                .and_then(|v| v.to_str().ok())
291                .map(str::to_string)
292        });
293
294    if provided.as_deref() != Some(expected.as_str()) {
295        // Arcade authenticates its webhook POSTs as `Authorization: Bearer
296        // <X-CallbackToken>` — a 401 here means a token mismatch and Arcade
297        // will burn its (~10) retries, then permanently drop the submission.
298        tracing::warn!(
299            has_authorization = headers.contains_key("authorization"),
300            has_x_callbacktoken = headers.contains_key("x-callbacktoken"),
301            "arc-callback: rejected POST with invalid/missing callback token"
302        );
303        return (
304            StatusCode::UNAUTHORIZED,
305            Json(json!({"code": "UNAUTHORIZED", "message": "invalid or missing callback token"})),
306        )
307            .into_response();
308    }
309
310    let bytes = match axum::body::to_bytes(request.into_body(), 1_000_000).await {
311        Ok(b) => b,
312        Err(_) => {
313            return (
314                StatusCode::PAYLOAD_TOO_LARGE,
315                Json(json!({"code": "TOO_LARGE", "message": "payload too large"})),
316            )
317                .into_response();
318        }
319    };
320    let payload: serde_json::Value = match serde_json::from_slice(&bytes) {
321        Ok(v) => v,
322        Err(e) => {
323            return (
324                StatusCode::BAD_REQUEST,
325                Json(json!({"code": "BAD_JSON", "message": e.to_string()})),
326            )
327                .into_response();
328        }
329    };
330
331    match crate::arc_ingest::ingest_arc_payload(wallet.storage(), &payload).await {
332        Ok(action) => (
333            StatusCode::OK,
334            Json(json!({"ok": true, "action": format!("{:?}", action)})),
335        )
336            .into_response(),
337        Err(e) => (
338            StatusCode::BAD_REQUEST,
339            Json(json!({"code": "BAD_PAYLOAD", "message": e.to_string()})),
340        )
341            .into_response(),
342    }
343}
344
345/// Browser wallets accept JSON whose strings carry lone UTF-16 surrogate escapes
346/// (`"\ud83d"` without its pair); serde does not, so a page whose keyID or data
347/// happened to contain one got `400 Failed to parse the request body as JSON:
348/// keyID: lone leading surrogate` from this wallet while MetaNet Desktop served
349/// the same call (beta soak, 2026-09-02, two logins lost). A browser's encoder
350/// turns such a code unit into U+FFFD when it hashes the string, so the same
351/// substitution here yields the same bytes the JS wallet would derive from.
352pub fn sanitize_lone_surrogates(input: &[u8]) -> std::borrow::Cow<'_, [u8]> {
353    if !input.windows(2).any(|w| w == b"\\u") {
354        return std::borrow::Cow::Borrowed(input);
355    }
356    let hex4 = |b: &[u8]| -> Option<u32> {
357        if b.len() < 4 {
358            return None;
359        }
360        std::str::from_utf8(&b[..4])
361            .ok()
362            .and_then(|h| u32::from_str_radix(h, 16).ok())
363    };
364    let mut out = Vec::with_capacity(input.len());
365    let mut i = 0;
366    let mut changed = false;
367    while i < input.len() {
368        if input[i] == b'\\' && i + 1 < input.len() && input[i + 1] == b'u' {
369            if let Some(cu) = hex4(&input[i + 2..]) {
370                let is_lead = (0xD800..=0xDBFF).contains(&cu);
371                let is_trail = (0xDC00..=0xDFFF).contains(&cu);
372                if is_lead {
373                    let next = &input[i + 6..];
374                    let paired = next.len() >= 6
375                        && next[0] == b'\\'
376                        && next[1] == b'u'
377                        && hex4(&next[2..]).is_some_and(|t| (0xDC00..=0xDFFF).contains(&t));
378                    if paired {
379                        out.extend_from_slice(&input[i..i + 12]);
380                        i += 12;
381                        continue;
382                    }
383                    out.extend_from_slice(b"\\ufffd");
384                    changed = true;
385                    i += 6;
386                    continue;
387                }
388                if is_trail {
389                    out.extend_from_slice(b"\\ufffd");
390                    changed = true;
391                    i += 6;
392                    continue;
393                }
394                out.extend_from_slice(&input[i..i + 6]);
395                i += 6;
396                continue;
397            }
398        }
399        out.push(input[i]);
400        i += 1;
401    }
402    if changed {
403        std::borrow::Cow::Owned(out)
404    } else {
405        std::borrow::Cow::Borrowed(input)
406    }
407}
408
409/// The routes whose JSON body carries a caller's BEEF. Their body is read
410/// whole with no cap: the BRC-100 JSON wire carries the BEEF as one array, so
411/// the body is held in memory (linear in the BEEF, about four bytes of body
412/// per byte of BEEF) and the BEEF is then judged by the toolbox's streaming
413/// reader for invalid bytes only. Every other route keeps
414/// [`BODY_CAP`].
415const BEEF_DOORS: [&str; 2] = ["/createAction", "/internalizeAction"];
416
417/// The body cap of the routes that carry no BEEF.
418const BODY_CAP: usize = 50 * 1024 * 1024;
419
420/// Rewrite lone surrogate escapes in JSON request bodies before the `Json`
421/// extractors see them (see [`sanitize_lone_surrogates`]).
422async fn lenient_json_body(request: Request, next: Next) -> Response {
423    let is_json = request
424        .headers()
425        .get(axum::http::header::CONTENT_TYPE)
426        .and_then(|v| v.to_str().ok())
427        .is_some_and(|ct| ct.to_ascii_lowercase().contains("json"));
428    if !is_json {
429        return next.run(request).await;
430    }
431    let (parts, body) = request.into_parts();
432    let cap = if BEEF_DOORS.contains(&parts.uri.path()) {
433        usize::MAX
434    } else {
435        BODY_CAP
436    };
437    let bytes = match axum::body::to_bytes(body, cap).await {
438        Ok(b) => b,
439        Err(_) => {
440            return (
441                StatusCode::PAYLOAD_TOO_LARGE,
442                Json(json!({"code": "TOO_LARGE", "message": "payload too large"})),
443            )
444                .into_response();
445        }
446    };
447    let body = match sanitize_lone_surrogates(&bytes) {
448        std::borrow::Cow::Borrowed(_) => axum::body::Body::from(bytes),
449        std::borrow::Cow::Owned(fixed) => {
450            tracing::warn!(
451                path = %parts.uri.path(),
452                "json body carried a lone UTF-16 surrogate escape; substituted U+FFFD"
453            );
454            axum::body::Body::from(fixed)
455        }
456    };
457    next.run(Request::from_parts(parts, body)).await
458}
459
460pub async fn run(wallet: WalletState, port: u16, config: ServerConfig) -> Result<()> {
461    let tls = config.tls.clone();
462    let bind_addr = config.bind_addr;
463    let app = make_router(wallet, config);
464    let addr = SocketAddr::from((bind_addr, port));
465
466    #[cfg(feature = "tls")]
467    if let Some(tls_cfg) = tls {
468        use axum_server::tls_rustls::RustlsConfig;
469        let rustls = RustlsConfig::from_pem_file(&tls_cfg.cert_path, &tls_cfg.key_path).await?;
470        tracing::info!("HTTPS server listening on {addr}");
471        eprintln!("HTTPS server listening on {addr}");
472        axum_server::bind_rustls(addr, rustls)
473            .serve(app.into_make_service())
474            .await?;
475        return Ok(());
476    }
477
478    #[cfg(not(feature = "tls"))]
479    if tls.is_some() {
480        anyhow::bail!("TLS requested but binary was built without `--features tls`");
481    }
482
483    tracing::info!("HTTP server listening on {addr}");
484    eprintln!("HTTP server listening on {addr}");
485
486    let listener = tokio::net::TcpListener::bind(addr).await?;
487    axum::serve(listener, app)
488        .with_graceful_shutdown(shutdown_signal())
489        .await?;
490
491    Ok(())
492}
493
494pub fn make_wallet_state(wallet: Wallet<StorageSqlx, Services>) -> WalletState {
495    Arc::new(wallet)
496}
497
498/// Build a `WalletState` from an existing `Arc<Wallet>`.
499///
500/// Use this when the caller is already holding an `Arc<Wallet>` and wants the
501/// HTTP server to share the *same* wallet instance — same identity key, same
502/// balance, same UTXO set. Avoids opening a second `Wallet` handle against
503/// the same SQLite DB (which would work via busy_timeout but adds write
504/// contention and a second instance of any in-memory caches).
505#[allow(dead_code)] // public API for external callers; not used inside this binary
506pub fn make_wallet_state_from_arc(wallet: Arc<Wallet<StorageSqlx, Services>>) -> WalletState {
507    wallet
508}
509
510async fn shutdown_signal() {
511    tokio::signal::ctrl_c()
512        .await
513        .expect("failed to listen for ctrl-c");
514    eprintln!("\nShutting down...");
515}
516
517/// GET /permission-audit — every permissioned request since start or reset.
518async fn permission_audit() -> Json<serde_json::Value> {
519    let entries = audit::snapshot();
520    Json(json!({ "count": entries.len(), "entries": entries }))
521}
522
523/// GET /chain-feed — the feed's stored status and cursor (`chain_feed`).
524/// `{"status": null}` where no feed ran (`serve`, or `CHAINTRACKS_URL=off`).
525async fn chain_feed_status(
526    axum::extract::State(wallet): axum::extract::State<WalletState>,
527) -> Response {
528    let storage = wallet.storage();
529    let status = crate::chain_feed::read_status(storage).await;
530    let cursor = crate::tracker_host::feed_cursor(storage).await;
531    match (status, cursor) {
532        (Ok(status), Ok(cursor)) => {
533            Json(json!({ "status": status, "cursor": cursor.to_string() })).into_response()
534        }
535        (Err(e), _) | (_, Err(e)) => (
536            StatusCode::INTERNAL_SERVER_ERROR,
537            Json(json!({ "code": "ERR_CHAIN_FEED", "message": e.to_string() })),
538        )
539            .into_response(),
540    }
541}
542
543/// POST /permission-audit/reset — call immediately before the flow you measure.
544async fn permission_audit_reset() -> Json<serde_json::Value> {
545    audit::reset();
546    Json(json!({ "ok": true }))
547}
548
549#[cfg(test)]
550mod lenient_json_tests {
551    use super::sanitize_lone_surrogates;
552
553    #[test]
554    fn lone_lead_and_lone_trail_become_fffd_and_pairs_survive() {
555        let lead = br#"{"keyID":"ab \ud83d cd"}"#;
556        assert_eq!(
557            &*sanitize_lone_surrogates(lead),
558            br#"{"keyID":"ab \ufffd cd"}"#
559        );
560        let trail = br#"{"keyID":"\udc00"}"#;
561        assert_eq!(&*sanitize_lone_surrogates(trail), br#"{"keyID":"\ufffd"}"#);
562        let pair = br#"{"keyID":"\ud83d\ude00"}"#;
563        assert!(matches!(
564            sanitize_lone_surrogates(pair),
565            std::borrow::Cow::Borrowed(_)
566        ));
567        let plain = br#"{"keyID":"plain \\u0041"}"#;
568        assert!(matches!(
569            sanitize_lone_surrogates(plain),
570            std::borrow::Cow::Borrowed(_)
571        ));
572        let fixed = sanitize_lone_surrogates(lead);
573        let v: serde_json::Value = serde_json::from_slice(&fixed).unwrap();
574        assert_eq!(v["keyID"], "ab \u{fffd} cd");
575    }
576}
577
578#[cfg(test)]
579mod bind_guard_tests {
580    use super::refuse_open_bind;
581    use std::net::IpAddr;
582
583    fn ip(s: &str) -> IpAddr {
584        s.parse().unwrap()
585    }
586
587    #[test]
588    fn beyond_loopback_needs_a_token_or_the_flag() {
589        for open in ["0.0.0.0", "::", "192.168.1.10", "10.0.0.1"] {
590            let err = refuse_open_bind(ip(open), None, false).unwrap_err();
591            assert!(
592                err.to_string().contains("--allow-no-token"),
593                "{open}: {err}"
594            );
595            assert!(
596                refuse_open_bind(ip(open), Some(""), false).is_err(),
597                "{open}"
598            );
599            assert!(
600                refuse_open_bind(ip(open), Some("t"), false).is_ok(),
601                "{open}"
602            );
603            assert!(refuse_open_bind(ip(open), None, true).is_ok(), "{open}");
604        }
605    }
606
607    #[test]
608    fn loopback_is_unchanged() {
609        for lo in ["127.0.0.1", "127.0.0.2", "::1", "::ffff:127.0.0.1"] {
610            assert!(refuse_open_bind(ip(lo), None, false).is_ok(), "{lo}");
611        }
612    }
613}