scope-bca 0.8.5

Scope Blockchain Analysis - A production-grade tool for blockchain data analysis, address management, and transaction investigation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
//! # Web Server Module
//!
//! Provides a locally hosted HTTP server with REST API endpoints and a
//! single-page web UI that mirrors all CLI functionality. The server uses
//! the same `Config` and `DefaultClientFactory` as the CLI, ensuring
//! identical behavior.
//!
//! ## Usage
//!
//! ```bash
//! # Start in foreground (default port 8080)
//! scope web
//!
//! # Custom port and bind address
//! scope web --port 3000 --bind 0.0.0.0
//!
//! # Run as background daemon
//! scope web --daemon
//!
//! # Stop a running daemon
//! scope web --stop
//! ```

pub mod api;
pub mod auth;
pub mod monitor;

use axum::Router;
use axum::response::IntoResponse;
use scope::chains::{ChainClientFactory, DefaultClientFactory};
use scope::config::Config;
use scope_cli::cli::output::Output;
use scope_cli::note;
use std::net::SocketAddr;
use std::sync::Arc;
use tower_http::cors::{Any, CorsLayer};

/// Shared application state passed to all handlers via Axum extractors.
pub struct AppState {
    /// Application configuration (same as CLI).
    pub config: Config,
    /// Client factory for creating chain and DEX clients. A trait object, so
    /// handler tests can run on a mock factory without network.
    pub factory: Box<dyn ChainClientFactory>,
}

impl AppState {
    /// State with `config` and the `factory` that builds chain clients.
    pub fn new(config: Config, factory: impl ChainClientFactory + 'static) -> Self {
        Self {
            config,
            factory: Box::new(factory),
        }
    }
}

/// Builds the Axum router with all API routes and static file serving.
pub fn build_router(state: Arc<AppState>) -> Router {
    let cors = CorsLayer::new()
        .allow_origin(Any)
        .allow_methods(Any)
        .allow_headers(Any);

    let auth_token = state.config.web.auth_token.clone();
    let api_routes = api::routes(state.clone()).layer(axum::middleware::from_fn(
        move |req: axum::http::Request<axum::body::Body>, next: axum::middleware::Next| {
            let token = auth_token.clone();
            async move { auth::auth_middleware(req, next, token).await }
        },
    ));

    Router::new()
        .nest("/api", api_routes)
        .route("/ws/monitor", axum::routing::get(monitor::ws_handler))
        .fallback(axum::routing::get(serve_ui))
        .layer(cors)
        .with_state(state)
}

/// Serves the embedded single-page web UI.
async fn serve_ui(uri: axum::http::Uri) -> impl axum::response::IntoResponse {
    let path = uri.path().trim_start_matches('/');

    // Serve specific static assets
    match path {
        "" | "index.html" => {
            axum::response::Html(include_str!("static/index.html")).into_response()
        }
        "app.js" => (
            [(axum::http::header::CONTENT_TYPE, "application/javascript")],
            include_str!("static/app.js"),
        )
            .into_response(),
        "style.css" => (
            [(axum::http::header::CONTENT_TYPE, "text/css")],
            include_str!("static/style.css"),
        )
            .into_response(),
        "favicon.svg" => (
            [(axum::http::header::CONTENT_TYPE, "image/svg+xml")],
            include_str!("static/favicon.svg"),
        )
            .into_response(),
        "favicon.ico" => {
            // Redirect .ico requests to the SVG favicon
            axum::response::Redirect::permanent("/favicon.svg").into_response()
        }
        // SPA fallback: serve index.html for client-side routing
        _ => axum::response::Html(include_str!("static/index.html")).into_response(),
    }
}

/// Starts the web server on the given address.
///
/// This is the main entry point called from the CLI `web` command handler.
pub async fn start_server(addr: SocketAddr, config: Config, out: &Output) -> anyhow::Result<()> {
    let built = scope::http::build(&config)?;
    for notice in &built.notices {
        tracing::warn!("{notice}");
    }
    let http = built.client;
    let factory = DefaultClientFactory {
        chains_config: config.chains.clone(),
        http,
    };
    let state = Arc::new(AppState::new(config, factory));
    let app = build_router(state);

    tracing::info!("Scope web server listening on http://{}", addr);
    note!(out, "Scope web server listening on http://{}", addr);

    let listener = tokio::net::TcpListener::bind(addr).await?;
    axum::serve(listener, app).await?;

    Ok(())
}

// ============================================================================
// Daemon management
// ============================================================================

/// The folder of the daemon's PID and log files.
pub fn daemon_dir() -> std::path::PathBuf {
    scope::paths::state_dir()
}

/// Returns the path to the PID file for the daemon.
pub fn pid_file_path() -> std::path::PathBuf {
    daemon_dir().join("scope-web.pid")
}

/// Returns the path to the log file for the daemon.
pub fn log_file_path() -> std::path::PathBuf {
    daemon_dir().join("scope-web.log")
}

/// Where versions before `~/.scope-bca` (0.7.0 and older) kept the PID
/// file. The migration does not copy it: a daemon those versions started
/// is still found here (#106).
pub fn legacy_pid_file_path() -> Option<std::path::PathBuf> {
    scope::paths::user_home().map(|h| h.join(".config/scope/data/scope-web.pid"))
}

/// The PID file to stop: the current one, else an older version's.
fn pid_file_to_stop(
    current: std::path::PathBuf,
    legacy: Option<std::path::PathBuf>,
) -> Option<std::path::PathBuf> {
    std::iter::once(current).chain(legacy).find(|p| p.exists())
}

/// Stops a running daemon by reading its PID file and sending SIGTERM.
/// Tells the user what happened, as notes on `out`.
///
/// # Errors
///
/// The PID file cannot be read or holds no PID.
pub fn stop_daemon(out: &Output) -> scope::error::Result<()> {
    let Some(pid_path) = pid_file_to_stop(pid_file_path(), legacy_pid_file_path()) else {
        note!(
            out,
            "No daemon PID file found at {}",
            pid_file_path().display()
        );
        note!(out, "Is the daemon running?");
        return Ok(());
    };

    let pid_str = std::fs::read_to_string(&pid_path).map_err(|e| {
        scope::error::ScopeError::io_context(e, format!("cannot read {}", pid_path.display()))
    })?;
    let pid: u32 = pid_str.trim().parse().map_err(|e| {
        scope::error::ScopeError::Other(format!("Invalid PID in {}: {}", pid_path.display(), e))
    })?;

    note!(out, "Stopping Scope web daemon (PID {})...", pid);

    #[cfg(unix)]
    {
        // Send SIGTERM to the daemon process
        let result = unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) };
        if result == 0 {
            note!(out, "Daemon stopped.");
        } else {
            note!(
                out,
                "Failed to stop daemon (process may have already exited)."
            );
        }
    }

    #[cfg(not(unix))]
    {
        note!(out, "Daemon stop is only supported on Unix systems.");
        note!(out, "Please manually terminate PID {}.", pid);
    }

    // Remove PID file
    let _ = std::fs::remove_file(&pid_path);
    Ok(())
}

/// Starts the server as a background daemon (Unix only).
///
/// Spawns the current executable as a detached child process with
/// stdout/stderr redirected to a log file, then writes the PID.
///
/// # Errors
///
/// The data directory, log file, PID file or child process cannot be made.
#[cfg(unix)]
pub fn start_daemon(addr: SocketAddr, config: Config, out: &Output) -> scope::error::Result<()> {
    use std::io::Write;

    let _ = config; // Config reloaded from disk in child

    std::fs::create_dir_all(daemon_dir())?;

    let pid_path = pid_file_path();
    let log_path = log_file_path();

    note!(out, "Starting Scope web daemon...");
    note!(out, "URL:  http://{}", addr);
    note!(out, "PID:  {}", pid_path.display());
    note!(out, "Log:  {}", log_path.display());

    // Redirect stdout/stderr to log file
    let log_file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&log_path)?;
    let log_file_err = log_file.try_clone()?;

    let current_exe = std::env::current_exe()?;
    let child = std::process::Command::new(current_exe)
        .args([
            "web",
            "--port",
            &addr.port().to_string(),
            "--bind",
            &addr.ip().to_string(),
        ])
        .env("SCOPE_WEB_DAEMON_CHILD", "1")
        .stdout(log_file)
        .stderr(log_file_err)
        .stdin(std::process::Stdio::null())
        .spawn()?;

    let pid = child.id();

    // Write PID file
    let mut f = std::fs::File::create(&pid_path)?;
    write!(f, "{}", pid)?;

    note!(out, "Daemon started with PID {}", pid);
    note!(out, "Stop with: scope web --stop");

    Ok(())
}

/// Fallback for non-Unix: run in foreground.
#[cfg(not(unix))]
pub fn start_daemon(addr: SocketAddr, config: Config, out: &Output) -> scope::error::Result<()> {
    note!(out, "Daemon mode is only supported on Unix systems.");
    note!(out, "Starting in foreground instead...");
    let rt = tokio::runtime::Runtime::new()?;
    rt.block_on(start_server(addr, config, out))
        .map_err(|e| scope::error::ScopeError::Other(e.to_string()))
}

/// Returns true if running as a daemon child process.
pub fn is_daemon_child() -> bool {
    std::env::var("SCOPE_WEB_DAEMON_CHILD").is_ok()
}

// ============================================================================
// Unit Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body;

    #[test]
    fn test_pid_file_path() {
        let path = pid_file_path();
        assert!(path.to_string_lossy().contains("scope-web.pid"));
    }

    #[test]
    fn test_log_file_path() {
        let path = log_file_path();
        assert!(path.to_string_lossy().contains("scope-web.log"));
    }

    #[test]
    fn test_build_router() {
        let config = Config::default();
        let http: std::sync::Arc<dyn scope::http::HttpClient> =
            std::sync::Arc::new(scope::http::NativeHttpClient::new().unwrap());
        let factory = DefaultClientFactory {
            chains_config: config.chains.clone(),
            http,
        };
        let state = Arc::new(AppState::new(config, factory));
        let _router = build_router(state);
    }

    #[test]
    fn test_the_daemon_creates_the_folder_its_files_go_in() {
        // Review M1: the PID and log files are in daemon_dir(), the folder
        // start_daemon creates, so a fresh home can start the daemon.
        assert_eq!(pid_file_path().parent(), Some(daemon_dir().as_path()));
        assert_eq!(log_file_path().parent(), Some(daemon_dir().as_path()));
        assert_eq!(daemon_dir(), scope::paths::state_dir());
    }

    #[test]
    fn test_is_daemon_child_default() {
        // Should be false in test context (env var not set)
        // Note: may be true if test runner sets it, so just ensure it doesn't panic
        let _ = is_daemon_child();
    }

    #[tokio::test]
    async fn test_serve_ui_index() {
        let response = serve_ui(axum::http::Uri::from_static("/"))
            .await
            .into_response();
        assert_eq!(response.status(), axum::http::StatusCode::OK);
        let body = body::to_bytes(response.into_body(), 1_000_000)
            .await
            .unwrap();
        let html = String::from_utf8(body.to_vec()).unwrap();
        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("Scope"));
    }

    /// H6: the market panel must not send a peg the user did not set, or the
    /// configured `market.health.peg_target` never applies on the web.
    #[test]
    fn test_ui_sends_peg_only_when_the_user_sets_it() {
        let js = include_str!("static/app.js");
        let html = include_str!("static/index.html");
        assert!(!js.contains("|| 1.0"), "app.js falls back to a fixed peg");
        assert!(
            !html.contains(r#"id="mkt-peg" value="#),
            "index.html fixes the peg field value"
        );
        assert!(
            js.contains("market.peg_target"),
            "peg field not filled from config"
        );
        assert!(js.contains("pegUserSet"), "peg not gated on a user edit");
    }

    /// M5: DEX venues come from `/api/venues`, not from lists in the UI.
    #[test]
    fn test_ui_hard_codes_no_dex_venue() {
        let js = include_str!("static/app.js");
        let html = include_str!("static/index.html");
        for text in ["Ethereum DEX", "Solana DEX"] {
            assert!(!js.contains(text), "app.js lists {text}");
            assert!(!html.contains(text), "index.html lists {text}");
        }
        assert!(
            js.contains("v.kind !== 'dex'"),
            "CEX-only selects must drop DEX venues"
        );
    }

    #[tokio::test]
    async fn test_serve_ui_index_html() {
        let response = serve_ui(axum::http::Uri::from_static("/index.html"))
            .await
            .into_response();
        assert_eq!(response.status(), axum::http::StatusCode::OK);
    }

    #[tokio::test]
    async fn test_serve_ui_app_js() {
        let response = serve_ui(axum::http::Uri::from_static("/app.js"))
            .await
            .into_response();
        assert_eq!(response.status(), axum::http::StatusCode::OK);
        let body = body::to_bytes(response.into_body(), 1_000_000)
            .await
            .unwrap();
        let js = String::from_utf8(body.to_vec()).unwrap();
        assert!(js.contains("function") || js.contains("const") || js.contains("var"));
    }

    #[tokio::test]
    async fn test_serve_ui_style_css() {
        let response = serve_ui(axum::http::Uri::from_static("/style.css"))
            .await
            .into_response();
        assert_eq!(response.status(), axum::http::StatusCode::OK);
        let body = body::to_bytes(response.into_body(), 1_000_000)
            .await
            .unwrap();
        let css = String::from_utf8(body.to_vec()).unwrap();
        assert!(css.contains(":root") || css.contains("body") || css.contains("nav"));
    }

    #[tokio::test]
    async fn test_serve_ui_spa_fallback() {
        // Unknown paths should return index.html (SPA routing)
        let response = serve_ui(axum::http::Uri::from_static("/some/random/path"))
            .await
            .into_response();
        assert_eq!(response.status(), axum::http::StatusCode::OK);
        let body = body::to_bytes(response.into_body(), 1_000_000)
            .await
            .unwrap();
        let html = String::from_utf8(body.to_vec()).unwrap();
        assert!(html.contains("<!DOCTYPE html>"));
    }

    #[tokio::test]
    async fn test_serve_ui_favicon_svg() {
        let response = serve_ui(axum::http::Uri::from_static("/favicon.svg"))
            .await
            .into_response();
        assert_eq!(response.status(), axum::http::StatusCode::OK);
        let headers = response.headers();
        let ct = headers.get(axum::http::header::CONTENT_TYPE).unwrap();
        assert_eq!(ct, "image/svg+xml");
    }

    #[tokio::test]
    async fn test_serve_ui_favicon_ico_redirect() {
        let response = serve_ui(axum::http::Uri::from_static("/favicon.ico"))
            .await
            .into_response();
        assert_eq!(
            response.status(),
            axum::http::StatusCode::PERMANENT_REDIRECT
        );
        let headers = response.headers();
        let loc = headers.get(axum::http::header::LOCATION).unwrap();
        assert_eq!(loc, "/favicon.svg");
    }

    #[tokio::test]
    async fn test_route_ws_monitor_handshake() {
        use axum::http::{Request, StatusCode};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        // GET /ws/monitor?token=USDC - WebSocket upgrade with required query params
        let req = Request::builder()
            .uri("/ws/monitor?token=USDC")
            .method("GET")
            .header("Connection", "Upgrade")
            .header("Upgrade", "websocket")
            .header("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
            .header("Sec-WebSocket-Version", "13")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        // With Upgrade headers: 101 Switching Protocols; without proper handshake: 426
        let status = response.status();
        assert!(
            status == StatusCode::SWITCHING_PROTOCOLS
                || status == StatusCode::UPGRADE_REQUIRED
                || status.is_success(),
            "Unexpected status: {}",
            status
        );
    }

    #[tokio::test]
    async fn test_route_ws_monitor_missing_token() {
        use axum::http::Request;
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let req = Request::builder()
            .uri("/ws/monitor")
            .method("GET")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        // Missing required token param -> 422 Unprocessable Entity
        assert!(response.status().is_client_error());
    }

    #[test]
    fn test_pid_file_path_in_data_dir() {
        let path = pid_file_path();
        assert!(path.ends_with("scope-web.pid"));
        assert!(path.parent().is_some());
    }

    #[test]
    fn test_stop_finds_the_current_pid_file_else_the_old_one() {
        // #106 1: a daemon that 0.7.0 started keeps its PID file in
        // ~/.config/scope/data.
        let d = tempfile::tempdir().unwrap();
        let current = d.path().join("state/scope-web.pid");
        let legacy = d.path().join(".config/scope/data/scope-web.pid");
        assert_eq!(
            pid_file_to_stop(current.clone(), Some(legacy.clone())),
            None
        );
        std::fs::create_dir_all(legacy.parent().unwrap()).unwrap();
        std::fs::write(&legacy, "1\n").unwrap();
        assert_eq!(
            pid_file_to_stop(current.clone(), Some(legacy.clone())),
            Some(legacy.clone())
        );
        std::fs::create_dir_all(current.parent().unwrap()).unwrap();
        std::fs::write(&current, "2\n").unwrap();
        assert_eq!(
            pid_file_to_stop(current.clone(), Some(legacy)),
            Some(current),
            "the current file wins"
        );
        assert!(
            legacy_pid_file_path()
                .unwrap()
                .ends_with(".config/scope/data/scope-web.pid")
        );
    }

    #[test]
    fn test_log_file_path_in_data_dir() {
        let path = log_file_path();
        assert!(path.ends_with("scope-web.log"));
        assert!(path.parent().is_some());
    }

    #[test]
    fn test_app_state_construction() {
        let config = Config::default();
        let http: std::sync::Arc<dyn scope::http::HttpClient> =
            std::sync::Arc::new(scope::http::NativeHttpClient::new().unwrap());
        let factory = DefaultClientFactory {
            chains_config: config.chains.clone(),
            http,
        };
        let state = AppState::new(config, factory);
        // Verify state fields are accessible
        let _ = state.config.chains.api_keys.len();
    }

    #[test]
    fn test_stop_daemon_no_pid_file() {
        // stop_daemon should handle missing PID file gracefully
        // We can't easily override the data dir, but verify the function exists
        // and the path helpers return valid paths
        let pid = pid_file_path();
        let log = log_file_path();
        assert_eq!(pid.parent(), log.parent());
    }

    /// One test for every PID file case: they share the PID file path (in
    /// the test home), so separate tests would race. No process is ever
    /// signalled: the only PID sent a signal is above every OS's PID limit.
    #[test]
    fn test_stop_daemon_reads_the_pid_file() {
        let pid_path = pid_file_path();
        std::fs::create_dir_all(daemon_dir()).unwrap();
        let _ = std::fs::remove_file(&pid_path);
        if let Some(legacy) = legacy_pid_file_path() {
            let _ = std::fs::remove_file(legacy);
        }

        // No PID file: nothing to stop, and it says so.
        let (out, cap) = Output::capture();
        stop_daemon(&out).unwrap();
        assert!(
            cap.err().contains("No daemon PID file found"),
            "{}",
            cap.err()
        );
        assert!(cap.err().contains("Is the daemon running?"));

        // Not a PID: an error that names the file, which stays.
        std::fs::write(&pid_path, "not-a-pid\n").unwrap();
        let (out, _) = Output::capture();
        let err = stop_daemon(&out).unwrap_err();
        assert!(err.to_string().contains("Invalid PID in"), "{err}");
        assert!(pid_path.exists());
        std::fs::remove_file(&pid_path).unwrap();

        // A PID file that cannot be read.
        std::fs::create_dir(&pid_path).unwrap();
        let (out, _) = Output::capture();
        let err = stop_daemon(&out).unwrap_err();
        assert!(err.to_string().contains("cannot read"), "{err}");
        std::fs::remove_dir(&pid_path).unwrap();

        // A PID no process can have (Linux allows at most 2^22, macOS
        // 99998): the stop is reported and the stale file removed.
        let pid = i32::MAX;
        std::fs::write(&pid_path, format!("{pid}\n")).unwrap();
        let (out, cap) = Output::capture();
        stop_daemon(&out).unwrap();
        let notes = cap.err();
        assert!(
            notes.contains(&format!("Stopping Scope web daemon (PID {pid})")),
            "{notes}"
        );
        #[cfg(unix)]
        assert!(notes.contains("Failed to stop daemon"), "{notes}");
        #[cfg(not(unix))]
        assert!(
            notes.contains(&format!("Please manually terminate PID {pid}")),
            "{notes}"
        );
        assert!(!pid_path.exists(), "the PID file is removed");
    }

    /// A free local port (bound, then released).
    fn free_addr() -> SocketAddr {
        std::net::TcpListener::bind("127.0.0.1:0")
            .unwrap()
            .local_addr()
            .unwrap()
    }

    #[tokio::test]
    async fn test_start_server_serves_the_ui_and_says_where() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let addr = free_addr();
        let (out, cap) = Output::capture();
        let server = start_server(addr, Config::default(), &out);
        let client = async {
            let mut stream = loop {
                match tokio::net::TcpStream::connect(addr).await {
                    Ok(s) => break s,
                    Err(_) => tokio::time::sleep(std::time::Duration::from_millis(20)).await,
                }
            };
            stream
                .write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
                .await
                .unwrap();
            let mut reply = String::new();
            stream.read_to_string(&mut reply).await.unwrap();
            reply
        };
        let reply = tokio::select! {
            r = server => panic!("the server stopped: {r:?}"),
            reply = tokio::time::timeout(std::time::Duration::from_secs(10), client) => {
                reply.expect("a reply within 10s")
            }
        };
        assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");
        assert!(reply.contains("<!DOCTYPE html>"));
        assert!(
            cap.err()
                .contains(&format!("Scope web server listening on http://{addr}")),
            "{}",
            cap.err()
        );
    }

    #[tokio::test]
    async fn test_start_server_fails_when_the_port_is_taken() {
        let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = taken.local_addr().unwrap();
        let (out, _) = Output::capture();
        let result = tokio::time::timeout(
            std::time::Duration::from_secs(10),
            start_server(addr, Config::default(), &out),
        )
        .await
        .expect("start_server returns");
        assert!(result.is_err(), "bound twice to {addr}");
    }

    // Helper to create the test app state
    fn test_state() -> Arc<AppState> {
        let config = Config::default();
        let http: std::sync::Arc<dyn scope::http::HttpClient> =
            std::sync::Arc::new(scope::http::NativeHttpClient::new().unwrap());
        let factory = DefaultClientFactory {
            chains_config: config.chains.clone(),
            http,
        };
        Arc::new(AppState::new(config, factory))
    }

    // ========================================================================
    // HTTP routing integration tests — exercise handler code paths
    // ========================================================================

    #[tokio::test]
    async fn test_route_get_config_status() {
        use axum::http::{Request, StatusCode};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let req = Request::builder()
            .uri("/api/config/status")
            .method("GET")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        let body = body::to_bytes(response.into_body(), 1_000_000)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert!(json.get("config_path").is_some());
        assert!(json.get("api_keys").is_some());
        assert!(json.get("version").is_some());
    }

    #[tokio::test]
    async fn test_route_post_config_save() {
        use axum::http::{Request, StatusCode, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let payload = serde_json::json!({
            "api_keys": {},
            "rpc_endpoints": {}
        });

        let req = Request::builder()
            .uri("/api/config")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        // May succeed or fail depending on file system, but should not panic
        let status = response.status();
        assert!(status == StatusCode::OK || status == StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn test_route_post_address() {
        use axum::http::{Request, StatusCode, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let payload = serde_json::json!({
            "address": "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
            "chain": "ethereum"
        });

        let req = Request::builder()
            .uri("/api/address")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        // Will likely fail due to no API key, but exercises the handler
        let status = response.status();
        assert!(
            status == StatusCode::OK
                || status == StatusCode::BAD_REQUEST
                || status == StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn test_route_post_tx() {
        use axum::http::{Request, StatusCode, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let payload = serde_json::json!({
            "hash": "0xabc123def456789012345678901234567890123456789012345678901234abcd",
            "chain": "ethereum"
        });

        let req = Request::builder()
            .uri("/api/tx")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        let status = response.status();
        assert!(
            status == StatusCode::OK
                || status == StatusCode::BAD_REQUEST
                || status == StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn test_route_post_crawl() {
        use axum::http::{Request, StatusCode, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let payload = serde_json::json!({
            "token": "USDC",
            "chain": "ethereum"
        });

        let req = Request::builder()
            .uri("/api/crawl")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        let status = response.status();
        assert!(
            status == StatusCode::OK
                || status == StatusCode::BAD_REQUEST
                || status == StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn test_route_get_discover() {
        use axum::http::{Request, StatusCode};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let req = Request::builder()
            .uri("/api/discover?source=profiles&limit=5")
            .method("GET")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        let status = response.status();
        assert!(status == StatusCode::OK || status == StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn test_route_post_insights() {
        use axum::http::{Request, StatusCode, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let payload = serde_json::json!({
            "target": "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2"
        });

        let req = Request::builder()
            .uri("/api/insights")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        let status = response.status();
        assert!(
            status == StatusCode::OK
                || status == StatusCode::BAD_REQUEST
                || status == StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn test_route_post_compliance_risk() {
        use axum::http::{Request, StatusCode, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let payload = serde_json::json!({
            "address": "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
            "chain": "ethereum",
            "detailed": true
        });

        let req = Request::builder()
            .uri("/api/compliance/risk")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        let status = response.status();
        assert!(
            status == StatusCode::OK
                || status == StatusCode::BAD_REQUEST
                || status == StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn test_route_post_export() {
        use axum::http::{Request, StatusCode, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let payload = serde_json::json!({
            "address": "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
            "chain": "ethereum",
            "format": "json"
        });

        let req = Request::builder()
            .uri("/api/export")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        let status = response.status();
        assert!(
            status == StatusCode::OK
                || status == StatusCode::BAD_REQUEST
                || status == StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn test_route_post_token_health() {
        use axum::http::{Request, StatusCode, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let payload = serde_json::json!({
            "token": "USDC",
            "chain": "ethereum",
            "with_market": false
        });

        let req = Request::builder()
            .uri("/api/token-health")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        let status = response.status();
        assert!(
            status == StatusCode::OK
                || status == StatusCode::BAD_REQUEST
                || status == StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn test_route_post_contract() {
        use axum::http::{Request, StatusCode, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let payload = serde_json::json!({
            "address": "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
            "chain": "ethereum"
        });

        let req = Request::builder()
            .uri("/api/contract")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        let status = response.status();
        assert!(
            status == StatusCode::OK
                || status == StatusCode::BAD_REQUEST
                || status == StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn test_route_post_market_summary() {
        use axum::http::{Request, StatusCode, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let payload = serde_json::json!({
            "pair": "USDC",
            "market_venue": "binance"
        });

        let req = Request::builder()
            .uri("/api/market/summary")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        let status = response.status();
        assert!(
            status == StatusCode::OK
                || status == StatusCode::BAD_REQUEST
                || status == StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn test_route_get_address_book_list() {
        use axum::http::{Request, StatusCode};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let req = Request::builder()
            .uri("/api/address-book/list")
            .method("GET")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        let status = response.status();
        assert!(status == StatusCode::OK || status == StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn test_route_post_address_book_add() {
        use axum::http::{Request, StatusCode, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let payload = serde_json::json!({
            "address": "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2",
            "chain": "ethereum",
            "label": "Test Wallet"
        });

        let req = Request::builder()
            .uri("/api/address-book/add")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        let status = response.status();
        assert!(
            status == StatusCode::OK
                || status == StatusCode::BAD_REQUEST
                || status == StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn test_route_invalid_json_body() {
        use axum::http::{Request, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let req = Request::builder()
            .uri("/api/address")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from("not json"))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        // Should return 4xx for bad JSON
        assert!(response.status().is_client_error());
    }

    #[tokio::test]
    async fn test_route_missing_required_field() {
        use axum::http::{Request, header};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        // Missing required "address" field
        let payload = serde_json::json!({ "chain": "ethereum" });

        let req = Request::builder()
            .uri("/api/address")
            .method("POST")
            .header(header::CONTENT_TYPE, "application/json")
            .body(axum::body::Body::from(payload.to_string()))
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        assert!(response.status().is_client_error());
    }

    #[tokio::test]
    async fn test_route_static_fallback() {
        use axum::http::{Request, StatusCode};
        use tower::ServiceExt;

        let state = test_state();
        let app = build_router(state);

        let req = Request::builder()
            .uri("/nonexistent-path")
            .method("GET")
            .body(axum::body::Body::empty())
            .unwrap();

        let response = app.oneshot(req).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }
}