scope-bca 0.5.6

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
//! Address book management API handlers.

use crate::AppState;
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use scope_cli::cli::address_book::{AddressBook, WatchedAddress};
use serde::Deserialize;
use std::sync::Arc;

/// GET /api/address-book/list — List address book entries.
pub async fn handle_list(State(state): State<Arc<AppState>>) -> impl IntoResponse {
    let data_dir = state.config.data_dir();
    match AddressBook::load(&data_dir) {
        Ok(address_book) => Json(serde_json::json!({
            "addresses": address_book.addresses,
        }))
        .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

/// Request body for adding an address book entry.
#[derive(Debug, Deserialize)]
pub struct AddAddressBookRequest {
    /// Blockchain address.
    pub address: String,
    /// Chain (default: "ethereum").
    #[serde(default = "default_chain")]
    pub chain: String,
    /// Optional label.
    pub label: Option<String>,
    /// Optional tags.
    #[serde(default)]
    pub tags: Vec<String>,
}

fn default_chain() -> String {
    "ethereum".to_string()
}

/// POST /api/address-book/add — Add an address to the address book.
pub async fn handle_add(
    State(state): State<Arc<AppState>>,
    Json(req): Json<AddAddressBookRequest>,
) -> impl IntoResponse {
    let data_dir = state.config.data_dir();
    let mut address_book = match AddressBook::load(&data_dir) {
        Ok(ab) => ab,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "error": e.to_string() })),
            )
                .into_response();
        }
    };

    let watched = WatchedAddress {
        address: req.address.clone(),
        label: req.label,
        chain: req.chain,
        tags: req.tags,
        added_at: chrono::Utc::now().timestamp() as u64,
    };

    match address_book.add_address(watched) {
        Ok(_) => {
            let data_dir_buf = data_dir.to_path_buf();
            if let Err(e) = address_book.save(&data_dir_buf) {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(serde_json::json!({ "error": e.to_string() })),
                )
                    .into_response();
            }
            Json(serde_json::json!({
                "status": "added",
                "address": req.address,
                "addresses": address_book.addresses,
            }))
            .into_response()
        }
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

/// Request body for removing an address book entry.
#[derive(Debug, Deserialize)]
pub struct RemoveAddressBookRequest {
    /// Blockchain address to remove.
    pub address: String,
}

/// POST /api/address-book/remove — Remove an address from the address book.
pub async fn handle_remove(
    State(state): State<Arc<AppState>>,
    Json(req): Json<RemoveAddressBookRequest>,
) -> impl IntoResponse {
    let data_dir = state.config.data_dir();
    let mut address_book = match AddressBook::load(&data_dir) {
        Ok(ab) => ab,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "error": e.to_string() })),
            )
                .into_response();
        }
    };

    match address_book.remove_address(&req.address) {
        Ok(true) => {
            let data_dir_buf = data_dir.to_path_buf();
            if let Err(e) = address_book.save(&data_dir_buf) {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(serde_json::json!({ "error": e.to_string() })),
                )
                    .into_response();
            }
            Json(serde_json::json!({
                "status": "removed",
                "address": req.address,
                "addresses": address_book.addresses,
            }))
            .into_response()
        }
        Ok(false) => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({ "error": format!("Address '{}' not found in address book", req.address) })),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

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

    #[test]
    fn test_deserialize_full() {
        let json = serde_json::json!({
            "address": "0x1234567890123456789012345678901234567890",
            "chain": "polygon",
            "label": "My Wallet",
            "tags": ["defi", "nft"]
        });
        let req: AddAddressBookRequest = serde_json::from_value(json).unwrap();
        assert_eq!(req.address, "0x1234567890123456789012345678901234567890");
        assert_eq!(req.chain, "polygon");
        assert_eq!(req.label, Some("My Wallet".to_string()));
        assert_eq!(req.tags.len(), 2);
        assert_eq!(req.tags[0], "defi");
        assert_eq!(req.tags[1], "nft");
    }

    #[test]
    fn test_deserialize_minimal() {
        let json = serde_json::json!({
            "address": "0x1234567890123456789012345678901234567890"
        });
        let req: AddAddressBookRequest = serde_json::from_value(json).unwrap();
        assert_eq!(req.address, "0x1234567890123456789012345678901234567890");
        assert_eq!(req.chain, "ethereum");
        assert_eq!(req.label, None);
        assert_eq!(req.tags.len(), 0);
    }

    #[test]
    fn test_default_chain() {
        assert_eq!(default_chain(), "ethereum");
    }

    #[test]
    fn test_with_tags() {
        let json = serde_json::json!({
            "address": "0x1234567890123456789012345678901234567890",
            "tags": ["tag1", "tag2", "tag3"]
        });
        let req: AddAddressBookRequest = serde_json::from_value(json).unwrap();
        assert_eq!(req.tags.len(), 3);
        assert_eq!(req.tags[0], "tag1");
        assert_eq!(req.tags[1], "tag2");
        assert_eq!(req.tags[2], "tag3");
    }

    #[test]
    fn test_with_label() {
        let json = serde_json::json!({
            "address": "0x1234567890123456789012345678901234567890",
            "label": "Test Label"
        });
        let req: AddAddressBookRequest = serde_json::from_value(json).unwrap();
        assert_eq!(req.label, Some("Test Label".to_string()));
    }

    #[tokio::test]
    async fn test_handle_address_book_list_direct() {
        use crate::AppState;
        use axum::extract::State;
        use axum::response::IntoResponse;
        use scope::chains::DefaultClientFactory;
        use scope::config::Config;

        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 = std::sync::Arc::new(AppState { config, factory });
        let response = handle_list(State(state)).await.into_response();
        let status = response.status();
        assert!(status.is_success() || status.is_server_error());
    }

    #[tokio::test]
    async fn test_handle_address_book_add_direct() {
        use crate::AppState;
        use axum::extract::State;
        use axum::response::IntoResponse;
        use scope::chains::DefaultClientFactory;
        use scope::config::Config;

        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 = std::sync::Arc::new(AppState { config, factory });
        let req = AddAddressBookRequest {
            address: "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2".to_string(),
            chain: "ethereum".to_string(),
            label: Some("Test".to_string()),
            tags: vec!["test".to_string()],
        };
        let response = handle_add(State(state), axum::Json(req))
            .await
            .into_response();
        let status = response.status();
        assert!(status.is_success() || status.is_client_error() || status.is_server_error());
    }

    #[test]
    fn test_deserialize_remove_request() {
        let json = serde_json::json!({
            "address": "0x1234567890123456789012345678901234567890"
        });
        let req: RemoveAddressBookRequest = serde_json::from_value(json).unwrap();
        assert_eq!(req.address, "0x1234567890123456789012345678901234567890");
    }

    #[tokio::test]
    async fn test_handle_address_book_remove_direct() {
        use crate::AppState;
        use axum::extract::State;
        use axum::response::IntoResponse;
        use scope::chains::DefaultClientFactory;
        use scope::config::Config;

        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 = std::sync::Arc::new(AppState { config, factory });
        let req = RemoveAddressBookRequest {
            address: "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2".to_string(),
        };
        let response = handle_remove(State(state), axum::Json(req))
            .await
            .into_response();
        let status = response.status();
        // 200 (removed), 404 (not found), or 500 (load/save error)
        assert!(
            status.is_success()
                || status == axum::http::StatusCode::NOT_FOUND
                || status.is_server_error()
        );
    }

    #[tokio::test]
    async fn test_handle_address_book_remove_nonexistent() {
        use crate::AppState;
        use axum::extract::State;
        use axum::response::IntoResponse;
        use scope::chains::DefaultClientFactory;
        use scope::config::Config;

        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 = std::sync::Arc::new(AppState { config, factory });
        let req = RemoveAddressBookRequest {
            address: "0x000000000000000000000000000000000000dead".to_string(),
        };
        let response = handle_remove(State(state), axum::Json(req))
            .await
            .into_response();
        // Should return 404 (not found) or 500 (load error)
        assert!(
            response.status() == axum::http::StatusCode::NOT_FOUND
                || response.status().is_server_error()
                || response.status().is_success()
        );
    }

    #[tokio::test]
    async fn test_handle_address_book_list_json_structure() {
        use axum::body;
        use axum::extract::State;
        use scope::chains::DefaultClientFactory;
        use scope::config::Config;

        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 = std::sync::Arc::new(AppState { config, factory });
        let response = handle_list(State(state)).await.into_response();
        if response.status().is_success() {
            let body_bytes = body::to_bytes(response.into_body(), 1_000_000)
                .await
                .unwrap();
            let json: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();
            assert!(json.get("addresses").is_some());
        }
    }

    #[tokio::test]
    async fn test_handle_address_book_add_duplicate_returns_bad_request() {
        use crate::AppState;
        use axum::extract::State;
        use axum::http::StatusCode;
        use axum::response::IntoResponse;
        use scope::chains::DefaultClientFactory;
        use scope::config::Config;

        let tmp_dir = tempfile::tempdir().unwrap();
        let data_dir = tmp_dir.path().to_path_buf();
        let mut config = Config::default();
        config.address_book.data_dir = Some(data_dir.clone());

        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 = std::sync::Arc::new(AppState { config, factory });

        let addr = "0x742d35Cc6634C0532925a3b844Bc9e7595f1b3c2".to_string();
        let req1 = AddAddressBookRequest {
            address: addr.clone(),
            chain: "ethereum".to_string(),
            label: Some("First".to_string()),
            tags: vec![],
        };
        let r1 = handle_add(State(state.clone()), axum::Json(req1))
            .await
            .into_response();
        if !r1.status().is_success() {
            return;
        }

        let req2 = AddAddressBookRequest {
            address: addr,
            chain: "ethereum".to_string(),
            label: Some("Duplicate".to_string()),
            tags: vec![],
        };
        let r2 = handle_add(State(state), axum::Json(req2))
            .await
            .into_response();
        assert_eq!(r2.status(), StatusCode::BAD_REQUEST);
        let body = axum::body::to_bytes(r2.into_body(), 1_000_000)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert!(
            json["error"]
                .as_str()
                .unwrap()
                .to_lowercase()
                .contains("already")
        );
    }

    #[tokio::test]
    async fn test_handle_address_book_list_corrupt_file_returns_500() {
        use crate::AppState;
        use axum::extract::State;
        use axum::http::StatusCode;
        use scope::chains::DefaultClientFactory;
        use scope::config::Config;

        let tmp_dir = tempfile::tempdir().unwrap();
        let yaml_path = tmp_dir.path().join("address_book.yaml");
        std::fs::write(&yaml_path, "{{{ invalid yaml").unwrap();

        let mut config = Config::default();
        config.address_book.data_dir = Some(tmp_dir.path().to_path_buf());
        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 = std::sync::Arc::new(AppState { config, factory });
        let response = handle_list(State(state)).await.into_response();
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }
}