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
23pub type SpendingLock = Arc<tokio::sync::Mutex<()>>;
30
31#[derive(Clone)]
33#[allow(dead_code)]
34pub struct TlsConfig {
35 pub cert_path: String,
36 pub key_path: String,
37}
38
39#[derive(Clone)]
41pub struct ServerConfig {
42 pub auth_token: Option<String>,
45 pub tls: Option<TlsConfig>,
47 pub chain: Chain,
50 pub bind_addr: std::net::IpAddr,
54 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
72pub 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
81pub 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
102pub 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
109async fn auth_middleware(headers: HeaderMap, request: Request, next: Next) -> Response {
111 if request.uri().path() == "/arc-callback" {
115 return next.run(request).await;
116 }
117
118 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
145pub 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 let verifier = crate::broadcast_verify::BroadcastVerifier::from_env(config.chain);
154
155 Router::new()
156 .route(
161 "/isAuthenticated",
162 get(handlers::is_authenticated).post(handlers::is_authenticated),
163 )
164 .route("/getPublicKey", post(handlers::get_public_key))
165 .route("/permission-audit", get(permission_audit))
169 .route("/permission-audit/reset", post(permission_audit_reset))
170 .route("/createSignature", post(handlers::create_signature))
171 .route(
175 "/createAction",
176 post(handlers::create_action).layer(DefaultBodyLimit::disable()),
177 )
178 .route(
179 "/internalizeAction",
180 post(handlers::internalize_action).layer(DefaultBodyLimit::disable()),
181 )
182 .route(
184 "/getHeight",
185 get(handlers::get_height).post(handlers::get_height),
186 )
187 .route(
188 "/getNetwork",
189 get(handlers::get_network).post(handlers::get_network),
190 )
191 .route(
192 "/getVersion",
193 get(handlers::get_version).post(handlers::get_version),
194 )
195 .route(
196 "/waitForAuthentication",
197 get(handlers::wait_for_authentication).post(handlers::wait_for_authentication),
198 )
199 .route("/getHeaderForHeight", post(handlers::get_header_for_height))
201 .route("/verifySignature", post(handlers::verify_signature))
203 .route("/encrypt", post(handlers::encrypt))
204 .route("/decrypt", post(handlers::decrypt))
205 .route("/createHmac", post(handlers::create_hmac))
206 .route("/verifyHmac", post(handlers::verify_hmac))
207 .route("/signAction", post(handlers::sign_action))
209 .route("/abortAction", post(handlers::abort_action))
210 .route("/listActions", post(handlers::list_actions))
211 .route("/listOutputs", post(handlers::list_outputs))
212 .route("/relinquishOutput", post(handlers::relinquish_output))
213 .route("/acquireCertificate", post(handlers::acquire_certificate))
215 .route("/listCertificates", post(handlers::list_certificates))
216 .route("/proveCertificate", post(handlers::prove_certificate))
217 .route(
218 "/relinquishCertificate",
219 post(handlers::relinquish_certificate),
220 )
221 .route(
223 "/discoverByIdentityKey",
224 post(handlers::discover_by_identity_key),
225 )
226 .route(
227 "/discoverByAttributes",
228 post(handlers::discover_by_attributes),
229 )
230 .route(
231 "/revealCounterpartyKeyLinkage",
232 post(handlers::reveal_counterparty_key_linkage),
233 )
234 .route(
235 "/revealSpecificKeyLinkage",
236 post(handlers::reveal_specific_key_linkage),
237 )
238 .route("/arc-callback", post(arc_callback))
241 .layer(cors)
245 .layer(middleware::from_fn(lenient_json_body))
246 .layer(middleware::from_fn(auth_middleware))
247 .layer(axum::Extension(cfg))
248 .layer(axum::Extension(spending_lock))
249 .layer(axum::Extension(verifier))
250 .layer(TraceLayer::new_for_http())
251 .layer(DefaultBodyLimit::max(BODY_CAP))
252 .with_state(wallet)
253}
254
255async fn arc_callback(
263 axum::extract::State(wallet): axum::extract::State<WalletState>,
264 request: Request,
265) -> Response {
266 let expected = request
267 .extensions()
268 .get::<ServerConfig>()
269 .and_then(|c| c.callback_token.clone());
270 let Some(expected) = expected else {
271 return (
272 StatusCode::NOT_FOUND,
273 Json(json!({"code": "CALLBACK_DISABLED", "message": "no callback token configured"})),
274 )
275 .into_response();
276 };
277
278 let headers = request.headers().clone();
279 let provided = headers
280 .get("authorization")
281 .and_then(|v| v.to_str().ok())
282 .and_then(|v| v.strip_prefix("Bearer "))
283 .map(str::to_string)
284 .or_else(|| {
285 headers
286 .get("x-callbacktoken")
287 .and_then(|v| v.to_str().ok())
288 .map(str::to_string)
289 });
290
291 if provided.as_deref() != Some(expected.as_str()) {
292 tracing::warn!(
296 has_authorization = headers.contains_key("authorization"),
297 has_x_callbacktoken = headers.contains_key("x-callbacktoken"),
298 "arc-callback: rejected POST with invalid/missing callback token"
299 );
300 return (
301 StatusCode::UNAUTHORIZED,
302 Json(json!({"code": "UNAUTHORIZED", "message": "invalid or missing callback token"})),
303 )
304 .into_response();
305 }
306
307 let bytes = match axum::body::to_bytes(request.into_body(), 1_000_000).await {
308 Ok(b) => b,
309 Err(_) => {
310 return (
311 StatusCode::PAYLOAD_TOO_LARGE,
312 Json(json!({"code": "TOO_LARGE", "message": "payload too large"})),
313 )
314 .into_response();
315 }
316 };
317 let payload: serde_json::Value = match serde_json::from_slice(&bytes) {
318 Ok(v) => v,
319 Err(e) => {
320 return (
321 StatusCode::BAD_REQUEST,
322 Json(json!({"code": "BAD_JSON", "message": e.to_string()})),
323 )
324 .into_response();
325 }
326 };
327
328 match crate::arc_ingest::ingest_arc_payload(wallet.storage(), &payload).await {
329 Ok(action) => (
330 StatusCode::OK,
331 Json(json!({"ok": true, "action": format!("{:?}", action)})),
332 )
333 .into_response(),
334 Err(e) => (
335 StatusCode::BAD_REQUEST,
336 Json(json!({"code": "BAD_PAYLOAD", "message": e.to_string()})),
337 )
338 .into_response(),
339 }
340}
341
342pub fn sanitize_lone_surrogates(input: &[u8]) -> std::borrow::Cow<'_, [u8]> {
350 if !input.windows(2).any(|w| w == b"\\u") {
351 return std::borrow::Cow::Borrowed(input);
352 }
353 let hex4 = |b: &[u8]| -> Option<u32> {
354 if b.len() < 4 {
355 return None;
356 }
357 std::str::from_utf8(&b[..4])
358 .ok()
359 .and_then(|h| u32::from_str_radix(h, 16).ok())
360 };
361 let mut out = Vec::with_capacity(input.len());
362 let mut i = 0;
363 let mut changed = false;
364 while i < input.len() {
365 if input[i] == b'\\' && i + 1 < input.len() && input[i + 1] == b'u' {
366 if let Some(cu) = hex4(&input[i + 2..]) {
367 let is_lead = (0xD800..=0xDBFF).contains(&cu);
368 let is_trail = (0xDC00..=0xDFFF).contains(&cu);
369 if is_lead {
370 let next = &input[i + 6..];
371 let paired = next.len() >= 6
372 && next[0] == b'\\'
373 && next[1] == b'u'
374 && hex4(&next[2..]).is_some_and(|t| (0xDC00..=0xDFFF).contains(&t));
375 if paired {
376 out.extend_from_slice(&input[i..i + 12]);
377 i += 12;
378 continue;
379 }
380 out.extend_from_slice(b"\\ufffd");
381 changed = true;
382 i += 6;
383 continue;
384 }
385 if is_trail {
386 out.extend_from_slice(b"\\ufffd");
387 changed = true;
388 i += 6;
389 continue;
390 }
391 out.extend_from_slice(&input[i..i + 6]);
392 i += 6;
393 continue;
394 }
395 }
396 out.push(input[i]);
397 i += 1;
398 }
399 if changed {
400 std::borrow::Cow::Owned(out)
401 } else {
402 std::borrow::Cow::Borrowed(input)
403 }
404}
405
406const BEEF_DOORS: [&str; 2] = ["/createAction", "/internalizeAction"];
413
414const BODY_CAP: usize = 50 * 1024 * 1024;
416
417async fn lenient_json_body(request: Request, next: Next) -> Response {
420 let is_json = request
421 .headers()
422 .get(axum::http::header::CONTENT_TYPE)
423 .and_then(|v| v.to_str().ok())
424 .is_some_and(|ct| ct.to_ascii_lowercase().contains("json"));
425 if !is_json {
426 return next.run(request).await;
427 }
428 let (parts, body) = request.into_parts();
429 let cap = if BEEF_DOORS.contains(&parts.uri.path()) {
430 usize::MAX
431 } else {
432 BODY_CAP
433 };
434 let bytes = match axum::body::to_bytes(body, cap).await {
435 Ok(b) => b,
436 Err(_) => {
437 return (
438 StatusCode::PAYLOAD_TOO_LARGE,
439 Json(json!({"code": "TOO_LARGE", "message": "payload too large"})),
440 )
441 .into_response();
442 }
443 };
444 let body = match sanitize_lone_surrogates(&bytes) {
445 std::borrow::Cow::Borrowed(_) => axum::body::Body::from(bytes),
446 std::borrow::Cow::Owned(fixed) => {
447 tracing::warn!(
448 path = %parts.uri.path(),
449 "json body carried a lone UTF-16 surrogate escape; substituted U+FFFD"
450 );
451 axum::body::Body::from(fixed)
452 }
453 };
454 next.run(Request::from_parts(parts, body)).await
455}
456
457pub async fn run(wallet: WalletState, port: u16, config: ServerConfig) -> Result<()> {
458 let tls = config.tls.clone();
459 let bind_addr = config.bind_addr;
460 let app = make_router(wallet, config);
461 let addr = SocketAddr::from((bind_addr, port));
462
463 #[cfg(feature = "tls")]
464 if let Some(tls_cfg) = tls {
465 use axum_server::tls_rustls::RustlsConfig;
466 let rustls = RustlsConfig::from_pem_file(&tls_cfg.cert_path, &tls_cfg.key_path).await?;
467 tracing::info!("HTTPS server listening on {addr}");
468 eprintln!("HTTPS server listening on {addr}");
469 axum_server::bind_rustls(addr, rustls)
470 .serve(app.into_make_service())
471 .await?;
472 return Ok(());
473 }
474
475 #[cfg(not(feature = "tls"))]
476 if tls.is_some() {
477 anyhow::bail!("TLS requested but binary was built without `--features tls`");
478 }
479
480 tracing::info!("HTTP server listening on {addr}");
481 eprintln!("HTTP server listening on {addr}");
482
483 let listener = tokio::net::TcpListener::bind(addr).await?;
484 axum::serve(listener, app)
485 .with_graceful_shutdown(shutdown_signal())
486 .await?;
487
488 Ok(())
489}
490
491pub fn make_wallet_state(wallet: Wallet<StorageSqlx, Services>) -> WalletState {
492 Arc::new(wallet)
493}
494
495#[allow(dead_code)] pub fn make_wallet_state_from_arc(wallet: Arc<Wallet<StorageSqlx, Services>>) -> WalletState {
504 wallet
505}
506
507async fn shutdown_signal() {
508 tokio::signal::ctrl_c()
509 .await
510 .expect("failed to listen for ctrl-c");
511 eprintln!("\nShutting down...");
512}
513
514async fn permission_audit() -> Json<serde_json::Value> {
516 let entries = audit::snapshot();
517 Json(json!({ "count": entries.len(), "entries": entries }))
518}
519
520async fn permission_audit_reset() -> Json<serde_json::Value> {
522 audit::reset();
523 Json(json!({ "ok": true }))
524}
525
526#[cfg(test)]
527mod lenient_json_tests {
528 use super::sanitize_lone_surrogates;
529
530 #[test]
531 fn lone_lead_and_lone_trail_become_fffd_and_pairs_survive() {
532 let lead = br#"{"keyID":"ab \ud83d cd"}"#;
533 assert_eq!(
534 &*sanitize_lone_surrogates(lead),
535 br#"{"keyID":"ab \ufffd cd"}"#
536 );
537 let trail = br#"{"keyID":"\udc00"}"#;
538 assert_eq!(&*sanitize_lone_surrogates(trail), br#"{"keyID":"\ufffd"}"#);
539 let pair = br#"{"keyID":"\ud83d\ude00"}"#;
540 assert!(matches!(
541 sanitize_lone_surrogates(pair),
542 std::borrow::Cow::Borrowed(_)
543 ));
544 let plain = br#"{"keyID":"plain \\u0041"}"#;
545 assert!(matches!(
546 sanitize_lone_surrogates(plain),
547 std::borrow::Cow::Borrowed(_)
548 ));
549 let fixed = sanitize_lone_surrogates(lead);
550 let v: serde_json::Value = serde_json::from_slice(&fixed).unwrap();
551 assert_eq!(v["keyID"], "ab \u{fffd} cd");
552 }
553}
554
555#[cfg(test)]
556mod bind_guard_tests {
557 use super::refuse_open_bind;
558 use std::net::IpAddr;
559
560 fn ip(s: &str) -> IpAddr {
561 s.parse().unwrap()
562 }
563
564 #[test]
565 fn beyond_loopback_needs_a_token_or_the_flag() {
566 for open in ["0.0.0.0", "::", "192.168.1.10", "10.0.0.1"] {
567 let err = refuse_open_bind(ip(open), None, false).unwrap_err();
568 assert!(
569 err.to_string().contains("--allow-no-token"),
570 "{open}: {err}"
571 );
572 assert!(
573 refuse_open_bind(ip(open), Some(""), false).is_err(),
574 "{open}"
575 );
576 assert!(
577 refuse_open_bind(ip(open), Some("t"), false).is_ok(),
578 "{open}"
579 );
580 assert!(refuse_open_bind(ip(open), None, true).is_ok(), "{open}");
581 }
582 }
583
584 #[test]
585 fn loopback_is_unchanged() {
586 for lo in ["127.0.0.1", "127.0.0.2", "::1", "::ffff:127.0.0.1"] {
587 assert!(refuse_open_bind(ip(lo), None, false).is_ok(), "{lo}");
588 }
589 }
590}