-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathlib.rs
More file actions
1226 lines (1080 loc) · 37.1 KB
/
Copy pathlib.rs
File metadata and controls
1226 lines (1080 loc) · 37.1 KB
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
pub mod cache;
pub mod config;
pub mod error;
pub mod handlers;
pub mod hash_validator;
pub mod metrics;
pub mod rate_limit;
pub mod retry;
pub mod routes;
pub mod stellar;
pub mod types;
use axum::{
extract::{Path, State},
http::{HeaderName, Request, StatusCode},
response::{IntoResponse, Response},
routing::{get, post},
Json, Router,
};
use chrono::{NaiveDate, Utc};
use futures::future::join_all;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer};
use tower_http::trace::TraceLayer;
use tracing::{info, warn};
use cache::CacheBackend;
use hash_validator::{HashValidator, ValidationError as HashValidationError};
use metrics::MetricsRegistry;
use stellar::{derive_account_id, StellarClient, TransactionRecord};
/// Header used to correlate a single logical operation across the NestJS
/// backend and this verifier service (see BE-136). Must match the header
/// name used by the backend.
pub const REQUEST_ID_HEADER: &str = "x-request-id";
// Application state
#[derive(Clone)]
pub struct AppState {
pub stellar: Arc<StellarClient>,
pub cache: Arc<CacheBackend>,
pub metrics: Arc<MetricsRegistry>,
pub stellar_secret_key: String,
}
// Request/Response types
#[derive(Debug, Deserialize)]
pub struct VerifyRequest {
pub document_hash: String,
pub transaction_id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct VerifyResponse {
pub verified: bool,
pub transaction_id: Option<String>,
pub timestamp: Option<i64>,
pub cached: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub revoked: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub revoked_at: Option<i64>,
}
/// Request type for submitting a document hash to Stellar blockchain
#[derive(Debug, Deserialize)]
pub struct SubmitRequest {
pub document_hash: String,
pub document_id: String,
pub submitter: String,
}
/// Response type for document hash submission
#[derive(Debug, Serialize, Deserialize)]
pub struct SubmitResponse {
pub success: bool,
pub transaction_id: Option<String>,
pub anchored_at: Option<i64>,
pub error: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct RevokeRequest {
pub document_hash: String,
pub reason: String,
pub revoked_by: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RevokeResponse {
pub transaction_id: String,
pub revoked_at: i64,
pub revoked: bool,
}
#[derive(Debug, Serialize)]
pub struct HealthResponse {
pub status: String,
pub stellar_connected: bool,
pub redis_connected: bool,
pub circuit_state: String,
pub circuit_failures: u32,
}
/// Response type for document verification history
#[derive(Debug, Serialize)]
pub struct HistoryResponse {
pub document_hash: String,
pub transactions: Vec<TransactionRecord>,
pub count: usize,
pub cached: bool,
}
#[derive(Debug, Serialize)]
pub struct ValidationErrorResponse {
pub error: String,
}
#[derive(Debug, Deserialize)]
pub struct BatchVerifyRequest {
pub hashes: Vec<String>,
}
#[derive(Debug, Serialize)]
pub struct BatchVerifyResponse {
pub results: Vec<BatchVerifyItem>,
pub total: usize,
pub verified_count: usize,
pub failed_count: usize,
}
#[derive(Debug, Serialize)]
pub struct BatchVerifyItem {
pub hash: String,
pub verified: bool,
pub transaction_id: Option<String>,
pub timestamp: Option<i64>,
pub error: Option<String>,
}
#[derive(Debug, Deserialize, Clone)]
pub struct TransferRequest {
pub document_hash: String,
pub from_owner: String,
pub to_owner: String,
pub transfer_date: String,
pub transfer_reference: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TransferRecord {
pub document_hash: String,
pub from_owner: String,
pub to_owner: String,
pub transfer_date: String,
pub transfer_reference: String,
pub transfer_hash: String,
pub memo: String,
pub anchored_at: String,
}
#[derive(Debug, Serialize)]
pub struct TransferResponse {
pub transfer_hash: String,
pub memo: String,
}
fn map_validation_error(err: HashValidationError) -> (StatusCode, ValidationErrorResponse) {
let message = match err {
HashValidationError::EmptyHash => "hash must not be empty".to_string(),
HashValidationError::WrongLength { expected, actual } => format!(
"hash has wrong length: expected {} characters, got {}",
expected, actual
),
HashValidationError::InvalidCharacter {
position,
character,
} => format!(
"hash contains invalid character '{}' at position {}",
character, position
),
};
(
StatusCode::BAD_REQUEST,
ValidationErrorResponse { error: message },
)
}
pub fn app(state: AppState) -> Router {
let request_id_header = HeaderName::from_static(REQUEST_ID_HEADER);
let span_header = request_id_header.clone();
Router::new()
.route("/health", get(health_check))
.route("/metrics", get(metrics_handler))
.route("/verify", post(verify_document))
.route("/verify/batch", post(batch_verify_documents))
.route("/verify/:hash", get(verify_document_by_hash))
.route("/verify/:hash/history", get(verify_document_history))
.route("/submit", post(submit_document))
.route("/revoke", post(revoke_document))
.route("/transfer", post(record_transfer))
.layer(
ServiceBuilder::new()
// Honour an inbound X-Request-Id (propagated from the NestJS
// backend, per BE-136); generate one only if it's absent.
.layer(SetRequestIdLayer::new(
request_id_header.clone(),
MakeRequestUuid,
))
.layer(
TraceLayer::new_for_http().make_span_with(move |request: &Request<_>| {
let request_id = request
.headers()
.get(&span_header)
.and_then(|v| v.to_str().ok())
.unwrap_or("unknown");
tracing::info_span!(
"http_request",
method = %request.method(),
path = %request.uri().path(),
request_id = %request_id,
)
}),
)
// Echo the request id back on the response so callers (and
// the backend) can confirm which id was used for this op.
.layer(PropagateRequestIdLayer::new(request_id_header)),
)
.with_state(state)
}
// Health check endpoint
pub async fn health_check(State(state): State<AppState>) -> impl IntoResponse {
let stellar_ok = state.stellar.check_connection().await;
let redis_ok = state.cache.check_connection().await;
let status = if stellar_ok && redis_ok {
"healthy"
} else {
"degraded"
};
Json(HealthResponse {
status: status.to_string(),
stellar_connected: stellar_ok,
redis_connected: redis_ok,
circuit_state: state.stellar.circuit_state_label().to_string(),
circuit_failures: state.stellar.circuit_failures(),
})
}
// Metrics endpoint
pub async fn metrics_handler(State(state): State<AppState>) -> impl IntoResponse {
(
[(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("text/plain; version=0.0.4"),
)],
state.metrics.render(),
)
}
/// Compute deterministic transfer hash from core fields.
///
/// SHA-256(document_hash + from_owner + to_owner + transfer_date)
pub fn compute_transfer_hash(req: &TransferRequest) -> String {
let mut hasher = Sha256::new();
hasher.update(req.document_hash.as_bytes());
hasher.update(req.from_owner.as_bytes());
hasher.update(req.to_owner.as_bytes());
hasher.update(req.transfer_date.as_bytes());
let digest = hasher.finalize();
hex::encode(digest)
}
/// Validate that the provided date is a valid ISO 8601 calendar date (YYYY-MM-DD).
fn is_valid_iso8601_date(date: &str) -> bool {
NaiveDate::parse_from_str(date, "%Y-%m-%d").is_ok()
}
/// Build a Stellar memo string for a transfer hash, respecting the 28-byte
/// text memo limit and using the required TRANSFER: prefix.
fn build_transfer_memo(transfer_hash: &str) -> String {
const PREFIX: &str = "TRANSFER:";
const MAX_MEMO_LEN: usize = 28;
let remaining = MAX_MEMO_LEN.saturating_sub(PREFIX.len());
let truncated = if transfer_hash.len() > remaining {
&transfer_hash[..remaining]
} else {
transfer_hash
};
format!("{}{}", PREFIX, truncated)
}
/// POST /transfer — anchor an ownership transfer on Stellar and persist history in Redis.
pub async fn record_transfer(
State(state): State<AppState>,
Json(req): Json<TransferRequest>,
) -> Result<Json<TransferResponse>, StatusCode> {
if !is_valid_iso8601_date(&req.transfer_date) {
return Err(StatusCode::BAD_REQUEST);
}
let transfer_hash = compute_transfer_hash(&req);
let memo = build_transfer_memo(&transfer_hash);
let anchor_account_id = derive_account_id(&state.stellar_secret_key).map_err(|e| {
warn!("Failed to derive anchor account id: {}", e);
state.metrics.increment_error_count();
StatusCode::INTERNAL_SERVER_ERROR
})?;
if let Err(e) = state
.stellar
.anchor_transfer(
&transfer_hash,
&anchor_account_id,
&state.stellar_secret_key,
)
.await
{
warn!("Failed to anchor transfer on Stellar: {}", e);
state.metrics.increment_error_count();
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
let record = TransferRecord {
document_hash: req.document_hash.clone(),
from_owner: req.from_owner.clone(),
to_owner: req.to_owner.clone(),
transfer_date: req.transfer_date.clone(),
transfer_reference: req.transfer_reference.clone(),
transfer_hash: transfer_hash.clone(),
memo: memo.clone(),
anchored_at: Utc::now().to_rfc3339(),
};
let key = format!("transfer:{}", record.document_hash);
let mut history: Vec<TransferRecord> = match state.cache.get(&key).await {
Ok(Some(existing)) => existing,
Ok(None) => Vec::new(),
Err(e) => {
warn!("Failed to read transfer history from cache: {}", e);
state.metrics.increment_error_count();
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
};
history.push(record);
// Set a long but finite TTL (10 years) to keep an auditable history
const TEN_YEARS_SECONDS: u64 = 60 * 60 * 24 * 365 * 10;
if let Err(e) = state.cache.set(&key, &history, TEN_YEARS_SECONDS).await {
warn!("Failed to persist transfer history: {}", e);
state.metrics.increment_error_count();
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
Ok(Json(TransferResponse {
transfer_hash,
memo,
}))
}
/// GET /transfer/:document_hash — retrieve transfer history for a document.
pub async fn get_transfer_history(
State(state): State<AppState>,
Path(document_hash): Path<String>,
) -> Result<Json<Vec<TransferRecord>>, StatusCode> {
let key = format!("transfer:{}", document_hash);
match state.cache.get::<Vec<TransferRecord>>(&key).await {
Ok(Some(history)) => Ok(Json(history)),
Ok(None) => Ok(Json(Vec::new())),
Err(e) => {
warn!("Failed to fetch transfer history from cache: {}", e);
state.metrics.increment_error_count();
Err(StatusCode::INTERNAL_SERVER_ERROR)
}
}
}
// Verify document by POST
pub async fn verify_document(
State(state): State<AppState>,
Json(req): Json<VerifyRequest>,
) -> Response {
let normalized_hash = HashValidator::normalize(&req.document_hash);
if let Err(err) = HashValidator::validate_sha256(&normalized_hash) {
let (status, body) = map_validation_error(err);
return (status, Json(body)).into_response();
}
info!("Verifying document hash: {}", normalized_hash);
state.metrics.increment_request_count();
// Check cache first
if let Ok(Some(cached)) = state.cache.get::<VerifyResponse>(&normalized_hash).await {
info!("Cache hit for hash: {}", normalized_hash);
state.metrics.increment_cache_hits();
return Json(cached).into_response();
}
state.metrics.increment_cache_misses();
let anchor_account_id = match derive_account_id(&state.stellar_secret_key) {
Ok(id) => id,
Err(e) => {
warn!("Failed to derive anchor account id: {}", e);
state.metrics.increment_error_count();
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
};
// Query Stellar blockchain
let result = match state
.stellar
.verify_hash(&normalized_hash, &anchor_account_id)
.await
{
Ok(verification) => verification,
Err(e) => {
warn!("Stellar query failed: {}", e);
state.metrics.increment_error_count();
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
};
let response = VerifyResponse {
verified: result.anchored,
transaction_id: result.transaction_id,
timestamp: result.timestamp,
cached: false,
revoked: None,
revoked_at: None,
};
Json(response).into_response()
}
// Verify document by GET with hash in path
pub async fn verify_document_by_hash(
State(state): State<AppState>,
Path(hash): Path<String>,
) -> Response {
let req = VerifyRequest {
document_hash: hash,
transaction_id: None,
};
verify_document(State(state), Json(req)).await
}
// Verify document history by hash
pub async fn verify_document_history(
State(state): State<AppState>,
Path(hash): Path<String>,
) -> Response {
let normalized_hash = HashValidator::normalize(&hash);
if let Err(err) = HashValidator::validate_sha256(&normalized_hash) {
let (status, body) = map_validation_error(err);
return (status, Json(body)).into_response();
}
let cache_key = format!("history:{}", normalized_hash);
let transactions: Vec<TransactionRecord> = match state.cache.get(&cache_key).await {
Ok(Some(records)) => records,
Ok(None) => Vec::new(),
Err(e) => {
warn!("Failed to fetch history from cache: {}", e);
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
};
let count = transactions.len();
let cached = !transactions.is_empty();
Json(HistoryResponse {
document_hash: normalized_hash,
transactions,
count,
cached,
})
.into_response()
}
// Batch verify documents
pub async fn batch_verify_documents(
State(state): State<AppState>,
Json(req): Json<BatchVerifyRequest>,
) -> Response {
// Validate batch size
if req.hashes.is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(ValidationErrorResponse {
error: "hashes array cannot be empty".to_string(),
}),
)
.into_response();
}
if req.hashes.len() > 50 {
return (
StatusCode::BAD_REQUEST,
Json(ValidationErrorResponse {
error: "batch size exceeds maximum of 50 hashes".to_string(),
}),
)
.into_response();
}
info!("Batch verifying {} document hashes", req.hashes.len());
state.metrics.increment_request_count();
// Process all hashes concurrently
let verification_futures: Vec<_> = req
.hashes
.iter()
.map(|hash| {
let state = state.clone();
let hash = hash.clone();
async move { verify_single_hash(&state, hash).await }
})
.collect();
let results = join_all(verification_futures).await;
let verified_count = results.iter().filter(|item| item.verified).count();
let failed_count = results.len() - verified_count;
let response = BatchVerifyResponse {
results,
total: req.hashes.len(),
verified_count,
failed_count,
};
Json(response).into_response()
}
// Helper function to verify a single hash
async fn verify_single_hash(state: &AppState, hash: String) -> BatchVerifyItem {
let normalized_hash = HashValidator::normalize(&hash);
if let Err(err) = HashValidator::validate_sha256(&normalized_hash) {
let error_msg = match err {
HashValidationError::EmptyHash => "hash must not be empty".to_string(),
HashValidationError::WrongLength { expected, actual } => format!(
"hash has wrong length: expected {} characters, got {}",
expected, actual
),
HashValidationError::InvalidCharacter {
position,
character,
} => format!(
"hash contains invalid character '{}' at position {}",
character, position
),
};
return BatchVerifyItem {
hash,
verified: false,
transaction_id: None,
timestamp: None,
error: Some(error_msg),
};
}
// Check cache first
if let Ok(Some(cached)) = state.cache.get::<VerifyResponse>(&normalized_hash).await {
info!("Cache hit for hash: {}", normalized_hash);
state.metrics.increment_cache_hits();
return BatchVerifyItem {
hash,
verified: cached.verified,
transaction_id: cached.transaction_id,
timestamp: cached.timestamp,
error: None,
};
}
state.metrics.increment_cache_misses();
let anchor_account_id = match derive_account_id(&state.stellar_secret_key) {
Ok(id) => id,
Err(e) => {
warn!("Failed to derive anchor account id: {}", e);
state.metrics.increment_error_count();
return BatchVerifyItem {
hash,
verified: false,
transaction_id: None,
timestamp: None,
error: Some(format!("failed to derive anchor account id: {}", e)),
};
}
};
// Query Stellar blockchain
let result = match state
.stellar
.verify_hash(&normalized_hash, &anchor_account_id)
.await
{
Ok(verification) => verification,
Err(e) => {
warn!("Stellar query failed for hash {}: {}", normalized_hash, e);
state.metrics.increment_error_count();
return BatchVerifyItem {
hash,
verified: false,
transaction_id: None,
timestamp: None,
error: Some(format!("stellar query failed: {}", e)),
};
}
};
// Cache the result
let cache_response = VerifyResponse {
verified: result.anchored,
transaction_id: result.transaction_id.clone(),
timestamp: result.timestamp,
cached: false,
revoked: None,
revoked_at: None,
};
if let Err(e) = state
.cache
.set(&normalized_hash, &cache_response, 3600)
.await
{
warn!("Failed to cache result for hash {}: {}", normalized_hash, e);
}
BatchVerifyItem {
hash,
verified: result.anchored,
transaction_id: result.transaction_id,
timestamp: result.timestamp,
error: None,
}
}
/// POST /submit — anchor a document hash to Stellar using a ManageData operation.
///
/// Request body: `{ document_hash, document_id, submitter }`
///
/// On success returns `{ success: true, transaction_id, anchored_at }`.
/// Duplicate submissions return the cached result with `200 OK` (idempotent).
pub async fn submit_document(
State(state): State<AppState>,
Json(req): Json<SubmitRequest>,
) -> Response {
let normalized_hash = HashValidator::normalize(&req.document_hash);
if let Err(err) = HashValidator::validate_sha256(&normalized_hash) {
let (status, body) = map_validation_error(err);
return (status, Json(body)).into_response();
}
let cache_key = format!("stellar:verify:{}", normalized_hash);
// Idempotency check — return cached anchor result if it exists.
if let Ok(Some(cached)) = state.cache.get::<SubmitResponse>(&cache_key).await {
info!(
"Cache hit for submit: returning existing anchor for {}",
normalized_hash
);
return Json(cached).into_response();
}
info!(
"Anchoring document hash {} submitted by {}",
normalized_hash, req.submitter
);
state.metrics.increment_request_count();
match state
.stellar
.anchor_hash(&normalized_hash, &req.submitter, &state.stellar_secret_key)
.await
{
Ok(result) => {
let response = SubmitResponse {
success: true,
transaction_id: Some(result.tx_hash.clone()),
anchored_at: Some(result.anchored_at),
error: None,
};
// Cache the result so duplicate submissions get a fast 200.
const ANCHOR_CACHE_TTL: u64 = 60 * 60 * 24 * 365; // 1 year
if let Err(e) = state
.cache
.set(&cache_key, &response, ANCHOR_CACHE_TTL)
.await
{
warn!(
"Failed to cache anchor result for {}: {}",
normalized_hash, e
);
}
info!(
"Document hash {} anchored in ledger {} (tx: {})",
normalized_hash, result.ledger, result.tx_hash
);
Json(response).into_response()
}
Err(e) => {
warn!("Stellar anchor failed for {}: {}", normalized_hash, e);
state.metrics.increment_error_count();
(
StatusCode::BAD_GATEWAY,
Json(SubmitResponse {
success: false,
transaction_id: None,
anchored_at: None,
error: Some(e.to_string()),
}),
)
.into_response()
}
}
}
/// POST /revoke — record a document revocation on Stellar.
///
/// Writes a `ManageData` entry with key `"revoked_" + hash[:56]` and
/// value `{ revokedAt, reason }` as bytes. The original `doc_` entry is
/// preserved so audit history remains intact.
///
/// After a successful on-chain revocation the Redis cache entry for
/// `stellar:verify:{hash}` is updated so that subsequent `GET /verify/:hash`
/// calls return `{ verified: true, revoked: true, revokedAt }`.
///
/// Returns `404` if the hash has no prior anchor record.
pub async fn revoke_document(
State(state): State<AppState>,
Json(req): Json<RevokeRequest>,
) -> Response {
let normalized_hash = HashValidator::normalize(&req.document_hash);
if let Err(err) = HashValidator::validate_sha256(&normalized_hash) {
let (status, body) = map_validation_error(err);
return (status, Json(body)).into_response();
}
let anchor_key = format!("stellar:verify:{}", normalized_hash);
// Ensure the document was previously anchored before revoking.
let existing: Option<SubmitResponse> = state
.cache
.get::<SubmitResponse>(&anchor_key)
.await
.unwrap_or(None);
if existing.is_none() {
return (
StatusCode::NOT_FOUND,
Json(ValidationErrorResponse {
error: "document hash has no prior anchor record; cannot revoke".to_string(),
}),
)
.into_response();
}
info!(
"Revoking document hash {} (revoked_by: {})",
normalized_hash, req.revoked_by
);
state.metrics.increment_request_count();
let revoked_at = Utc::now().timestamp();
// Build the revocation payload stored as ManageData value.
let revocation_value = serde_json::json!({
"revokedAt": Utc::now().to_rfc3339(),
"reason": req.reason,
"revokedBy": req.revoked_by,
})
.to_string();
// Use stellar.rs anchor_hash logic directly — we build a new ManageData tx
// with the revocation key.
match state
.stellar
.anchor_revocation(
&normalized_hash,
&revocation_value,
&req.revoked_by,
&state.stellar_secret_key,
)
.await
{
Ok(result) => {
// Update the cached verify entry to reflect revocation.
let updated_verify = VerifyResponse {
verified: true,
transaction_id: existing.and_then(|r| r.transaction_id),
timestamp: Some(revoked_at),
cached: false,
revoked: Some(true),
revoked_at: Some(revoked_at),
};
const REVOKE_CACHE_TTL: u64 = 60 * 60 * 24 * 365;
if let Err(e) = state
.cache
.set(&anchor_key, &updated_verify, REVOKE_CACHE_TTL)
.await
{
warn!("Failed to update cache after revocation: {}", e);
}
info!(
"Document {} revoked in ledger {} (tx: {})",
normalized_hash, result.ledger, result.tx_hash
);
Json(RevokeResponse {
transaction_id: result.tx_hash,
revoked_at,
revoked: true,
})
.into_response()
}
Err(e) => {
warn!("Revocation failed for {}: {}", normalized_hash, e);
state.metrics.increment_error_count();
(
StatusCode::BAD_GATEWAY,
Json(ValidationErrorResponse {
error: format!("Stellar revocation failed: {}", e),
}),
)
.into_response()
}
}
}
pub async fn transfer_document(Json(req): Json<TransferRequest>) -> impl IntoResponse {
let normalized_hash = HashValidator::normalize(&req.document_hash);
if let Err(err) = HashValidator::validate_sha256(&normalized_hash) {
let (status, body) = map_validation_error(err);
return (status, Json(body));
}
// Basic date validation: expect YYYY-MM-DD
if chrono::NaiveDate::parse_from_str(&req.transfer_date, "%Y-%m-%d").is_err() {
return (
StatusCode::BAD_REQUEST,
Json(ValidationErrorResponse {
error: "invalid date format, expected YYYY-MM-DD".to_string(),
}),
);
}
// Endpoint behavior not yet implemented; for now respond with BAD_REQUEST.
(
StatusCode::BAD_REQUEST,
Json(ValidationErrorResponse {
error: "transfer endpoint not yet implemented".to_string(),
}),
)
}
/// Calculates Levenshtein distance between two strings
pub fn levenshtein_distance(s1: &str, s2: &str) -> usize {
let len1 = s1.len();
let len2 = s2.len();
let mut matrix = vec![vec![0; len2 + 1]; len1 + 1];
for (i, row) in matrix.iter_mut().enumerate() {
row[0] = i;
}
for (j, cell) in matrix[0].iter_mut().enumerate() {
*cell = j;
}
for (i, c1) in s1.chars().enumerate() {
for (j, c2) in s2.chars().enumerate() {
let cost = if c1 == c2 { 0 } else { 1 };
matrix[i + 1][j + 1] = std::cmp::min(
std::cmp::min(matrix[i][j + 1] + 1, matrix[i + 1][j] + 1),
matrix[i][j] + cost,
);
}
}
matrix[len1][len2]
}
/// Normalizes Levenshtein distance to similarity score (0-1)
pub fn levenshtein_similarity(s1: &str, s2: &str) -> f64 {
let distance = levenshtein_distance(s1, s2) as f64;
let max_len = s1.len().max(s2.len()) as f64;
if max_len == 0.0 {
return 1.0;
}
1.0 - (distance / max_len)
}
/// Tokenizes text and calculates term frequencies
fn tokenize(text: &str) -> HashMap<String, usize> {
let mut frequencies = HashMap::new();
let lowercased = text.to_lowercase();
let words: Vec<&str> = lowercased
.split(|c: char| !c.is_alphanumeric())
.filter(|w| !w.is_empty())
.collect();
for word in words {
*frequencies.entry(word.to_string()).or_insert(0) += 1;
}
frequencies
}
/// Calculates cosine similarity between two documents
pub fn cosine_similarity(doc1: &str, doc2: &str) -> f64 {
let freq1 = tokenize(doc1);
let freq2 = tokenize(doc2);
if freq1.is_empty() || freq2.is_empty() {
return 0.0;
}
let mut dot_product = 0.0;
for (word, count1) in &freq1 {
if let Some(&count2) = freq2.get(word) {
dot_product += (*count1 as f64) * (count2 as f64);
}
}
let magnitude1: f64 = freq1
.values()
.map(|c| (*c as f64).powi(2))
.sum::<f64>()
.sqrt();
let magnitude2: f64 = freq2
.values()
.map(|c| (*c as f64).powi(2))
.sum::<f64>()
.sqrt();
if magnitude1 == 0.0 || magnitude2 == 0.0 {
return 0.0;
}
dot_product / (magnitude1 * magnitude2)
}
/// Document similarity result
#[derive(Debug, Clone)]
pub struct SimilarityResult {
pub doc1: String,
pub doc2: String,
pub cosine: f64,
pub levenshtein: f64,
pub combined: f64,
}
/// Compares two documents and returns similarity scores
pub fn compare_documents(doc1: &str, doc2: &str) -> SimilarityResult {
let cosine = cosine_similarity(doc1, doc2);
let levenshtein = levenshtein_similarity(doc1, doc2);
let combined = (cosine + levenshtein) / 2.0;
SimilarityResult {
doc1: doc1.to_string(),
doc2: doc2.to_string(),
cosine,
levenshtein,
combined,
}
}
/// Batch comparison of documents against a reference
pub fn batch_compare(reference: &str, documents: &[&str]) -> Vec<SimilarityResult> {
documents
.iter()
.map(|doc| compare_documents(reference, doc))
.collect()
}
/// Finds duplicate documents above threshold
pub fn find_duplicates(documents: &[&str], threshold: f64) -> Vec<(usize, usize, f64)> {