bsv-rs 0.3.5

BSV blockchain SDK for Rust - primitives, script, transactions, and more
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
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
//! HTTP integration tests for StorageUploader and StorageDownloader.
//!
//! These tests use `wiremock` to spin up a local mock HTTP server and verify that
//! the storage uploader sends correct requests and handles various HTTP responses.
//!
//! The StorageUploader is fully testable via wiremock because it accepts an injectable
//! base URL via `StorageUploaderConfig::new(url)`. The uploader's two-step upload
//! flow (POST /upload for presigned URL, then PUT to that URL) and the find/list/renew
//! endpoints all use the configured base URL.
//!
//! The StorageDownloader's `download()` method is harder to test end-to-end with wiremock
//! because it first resolves hosts via the overlay network's LookupResolver, then
//! downloads from discovered hosts. We test what we can: the configuration, URL
//! validation, and error paths. The actual HTTP download behavior is covered by
//! directing the download at a known host URL.
//!
//! Run with: `cargo test --features "full,http" --test storage_http_tests`

#![cfg(all(feature = "storage", feature = "http"))]

use bsv_rs::storage::{
    get_url_for_file, is_valid_url, StorageUploader, StorageUploaderConfig, UploadableFile,
};
use wiremock::matchers::{body_string_contains, header, method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

// =============================================================================
// StorageUploader Tests - publish_file (two-step upload flow)
// =============================================================================

/// Test successful file upload through the two-step flow:
/// 1. POST /upload with file size and retention -> returns presigned URL
/// 2. PUT to presigned URL with file content -> 200 success
/// The uploader then generates a UHRP URL from the file's SHA-256 hash.
#[tokio::test]
async fn test_uploader_publish_file_success() {
    let mock_server = MockServer::start().await;

    let file_data = b"Hello, World!";
    let file = UploadableFile::new(file_data.to_vec(), "text/plain");

    // Step 1: Mock the /upload endpoint that returns a presigned URL.
    // The presigned URL points back to the same mock server at /put-file.
    let presigned_url = format!("{}/put-file", mock_server.uri());
    Mock::given(method("POST"))
        .and(path("/upload"))
        .and(header("content-type", "application/json"))
        .and(body_string_contains("\"fileSize\":13"))
        .and(body_string_contains("\"retentionPeriod\":10080"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "uploadURL": presigned_url,
            "requiredHeaders": {},
            "amount": 100
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    // Step 2: Mock the presigned URL where the file is actually uploaded via PUT.
    Mock::given(method("PUT"))
        .and(path("/put-file"))
        .and(header("content-type", "text/plain"))
        .respond_with(ResponseTemplate::new(200).set_body_string("OK"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.publish_file(&file, None).await;
    assert!(result.is_ok(), "Expected success, got: {:?}", result);

    let upload_result = result.unwrap();
    assert!(
        upload_result.published,
        "File should be marked as published"
    );
    assert!(
        is_valid_url(&upload_result.uhrp_url),
        "Result should contain a valid UHRP URL, got: {}",
        upload_result.uhrp_url
    );

    // Verify the UHRP URL matches the file content
    let expected_url = get_url_for_file(file_data).unwrap();
    assert_eq!(
        upload_result.uhrp_url, expected_url,
        "UHRP URL should be derived from the file's SHA-256 hash"
    );
}

/// Test that the uploader uses the custom retention period when provided
/// instead of the default 7-day retention.
#[tokio::test]
async fn test_uploader_publish_file_with_custom_retention() {
    let mock_server = MockServer::start().await;

    let file = UploadableFile::new(b"test".to_vec(), "text/plain");
    let presigned_url = format!("{}/put-file", mock_server.uri());

    // Expect the custom retention period of 1440 minutes (1 day) in the request body.
    Mock::given(method("POST"))
        .and(path("/upload"))
        .and(body_string_contains("\"retentionPeriod\":1440"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "uploadURL": presigned_url,
            "requiredHeaders": {}
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    Mock::given(method("PUT"))
        .and(path("/put-file"))
        .respond_with(ResponseTemplate::new(200).set_body_string("OK"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.publish_file(&file, Some(1440)).await;
    assert!(
        result.is_ok(),
        "Expected success with custom retention, got: {:?}",
        result
    );
}

/// Test that required headers from the upload info response are included
/// in the PUT request to the presigned URL.
#[tokio::test]
async fn test_uploader_publish_file_with_required_headers() {
    let mock_server = MockServer::start().await;

    let file = UploadableFile::new(b"data".to_vec(), "application/octet-stream");
    let presigned_url = format!("{}/put-file", mock_server.uri());

    // Return required headers that must be forwarded to the PUT request.
    Mock::given(method("POST"))
        .and(path("/upload"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "uploadURL": presigned_url,
            "requiredHeaders": {
                "x-amz-acl": "public-read",
                "x-custom-header": "custom-value"
            }
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    // Verify the required headers are actually sent in the PUT request.
    Mock::given(method("PUT"))
        .and(path("/put-file"))
        .and(header("x-amz-acl", "public-read"))
        .and(header("x-custom-header", "custom-value"))
        .and(header("content-type", "application/octet-stream"))
        .respond_with(ResponseTemplate::new(200).set_body_string("OK"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.publish_file(&file, None).await;
    assert!(
        result.is_ok(),
        "Expected success with required headers, got: {:?}",
        result
    );
}

/// Test that a 400 Bad Request from the /upload endpoint is handled as an error.
#[tokio::test]
async fn test_uploader_publish_file_upload_info_400() {
    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/upload"))
        .respond_with(ResponseTemplate::new(400).set_body_string("Bad Request"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);
    let file = UploadableFile::new(b"test".to_vec(), "text/plain");

    let result = uploader.publish_file(&file, None).await;
    assert!(
        result.is_err(),
        "Expected failure for 400, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("HTTP 400"),
        "Error should mention HTTP 400, got: {}",
        err_msg
    );
}

/// Test that a 401 Unauthorized from the /upload endpoint is handled as an error.
#[tokio::test]
async fn test_uploader_publish_file_upload_info_401() {
    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/upload"))
        .respond_with(ResponseTemplate::new(401).set_body_string("Unauthorized"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);
    let file = UploadableFile::new(b"test".to_vec(), "text/plain");

    let result = uploader.publish_file(&file, None).await;
    assert!(
        result.is_err(),
        "Expected failure for 401, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("HTTP 401"),
        "Error should mention HTTP 401, got: {}",
        err_msg
    );
}

/// Test that a 413 Payload Too Large from the /upload endpoint is handled.
#[tokio::test]
async fn test_uploader_publish_file_upload_info_413() {
    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/upload"))
        .respond_with(ResponseTemplate::new(413).set_body_string("Payload Too Large"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);
    let file = UploadableFile::new(vec![0u8; 1024], "application/octet-stream");

    let result = uploader.publish_file(&file, None).await;
    assert!(
        result.is_err(),
        "Expected failure for 413, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("HTTP 413"),
        "Error should mention HTTP 413, got: {}",
        err_msg
    );
}

/// Test that a 500 Internal Server Error from the /upload endpoint is handled.
#[tokio::test]
async fn test_uploader_publish_file_upload_info_500() {
    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/upload"))
        .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);
    let file = UploadableFile::new(b"test".to_vec(), "text/plain");

    let result = uploader.publish_file(&file, None).await;
    assert!(
        result.is_err(),
        "Expected failure for 500, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("HTTP 500"),
        "Error should mention HTTP 500, got: {}",
        err_msg
    );
}

/// Test that if /upload returns an error status in the JSON body (not HTTP error),
/// the uploader handles it correctly.
#[tokio::test]
async fn test_uploader_publish_file_upload_info_error_status_in_json() {
    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/upload"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "error",
            "uploadURL": "",
            "requiredHeaders": {}
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);
    let file = UploadableFile::new(b"test".to_vec(), "text/plain");

    let result = uploader.publish_file(&file, None).await;
    assert!(
        result.is_err(),
        "Expected failure for error status in JSON, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("Upload route returned an error"),
        "Error should mention upload route error, got: {}",
        err_msg
    );
}

/// Test that a 500 error on the PUT (presigned URL upload) step is handled.
#[tokio::test]
async fn test_uploader_publish_file_put_step_500() {
    let mock_server = MockServer::start().await;

    let presigned_url = format!("{}/put-file", mock_server.uri());

    // Step 1 succeeds
    Mock::given(method("POST"))
        .and(path("/upload"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "uploadURL": presigned_url,
            "requiredHeaders": {}
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    // Step 2 fails with 500
    Mock::given(method("PUT"))
        .and(path("/put-file"))
        .respond_with(ResponseTemplate::new(500).set_body_string("Storage backend error"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);
    let file = UploadableFile::new(b"test".to_vec(), "text/plain");

    let result = uploader.publish_file(&file, None).await;
    assert!(
        result.is_err(),
        "Expected failure for PUT step 500, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("File upload failed"),
        "Error should mention file upload failure, got: {}",
        err_msg
    );
}

/// Test a small 1-byte file upload to verify the minimal case.
#[tokio::test]
async fn test_uploader_publish_file_small_file() {
    let mock_server = MockServer::start().await;

    let file_data = vec![42u8]; // Single byte
    let file = UploadableFile::new(file_data.clone(), "application/octet-stream");
    let presigned_url = format!("{}/put-file", mock_server.uri());

    // Expect fileSize: 1 in the request
    Mock::given(method("POST"))
        .and(path("/upload"))
        .and(body_string_contains("\"fileSize\":1"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "uploadURL": presigned_url,
            "requiredHeaders": {}
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    Mock::given(method("PUT"))
        .and(path("/put-file"))
        .respond_with(ResponseTemplate::new(200).set_body_string("OK"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.publish_file(&file, None).await;
    assert!(
        result.is_ok(),
        "Expected success for small file, got: {:?}",
        result
    );

    let upload_result = result.unwrap();
    let expected_url = get_url_for_file(&file_data).unwrap();
    assert_eq!(upload_result.uhrp_url, expected_url);
}

/// Test uploading an empty file (0 bytes) to verify edge case handling.
#[tokio::test]
async fn test_uploader_publish_file_empty_content() {
    let mock_server = MockServer::start().await;

    let file_data: Vec<u8> = vec![];
    let file = UploadableFile::new(file_data.clone(), "application/octet-stream");
    let presigned_url = format!("{}/put-file", mock_server.uri());

    Mock::given(method("POST"))
        .and(path("/upload"))
        .and(body_string_contains("\"fileSize\":0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "uploadURL": presigned_url,
            "requiredHeaders": {}
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    Mock::given(method("PUT"))
        .and(path("/put-file"))
        .respond_with(ResponseTemplate::new(200).set_body_string("OK"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.publish_file(&file, None).await;
    assert!(
        result.is_ok(),
        "Expected success for empty file, got: {:?}",
        result
    );

    // Verify the UHRP URL is the hash of empty content
    let upload_result = result.unwrap();
    let expected_url = get_url_for_file(&file_data).unwrap();
    assert_eq!(upload_result.uhrp_url, expected_url);
}

// =============================================================================
// StorageUploader Tests - find_file
// =============================================================================

/// Test successful find_file that returns file metadata.
#[tokio::test]
async fn test_uploader_find_file_success() {
    let mock_server = MockServer::start().await;

    // The find endpoint uses a query parameter for the UHRP URL.
    Mock::given(method("GET"))
        .and(path("/find"))
        .and(query_param("uhrpUrl", "uhrp://testurl123"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "data": {
                "name": "cdn/abc123",
                "size": "1024",
                "mimeType": "text/plain",
                "expiryTime": 1700000000
            }
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.find_file("uhrp://testurl123").await;
    assert!(result.is_ok(), "Expected success, got: {:?}", result);

    let file_data = result.unwrap();
    assert!(file_data.is_some(), "Expected file data to be present");

    let data = file_data.unwrap();
    assert_eq!(data.name, Some("cdn/abc123".to_string()));
    assert_eq!(data.size, "1024");
    assert_eq!(data.mime_type, "text/plain");
    assert_eq!(data.expiry_time, 1700000000);
}

/// Test find_file when the server returns an error status in the JSON response.
#[tokio::test]
async fn test_uploader_find_file_error_status_in_json() {
    let mock_server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/find"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "error",
            "code": "ERR_NOT_FOUND",
            "description": "File not found"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.find_file("uhrp://unknown-hash").await;
    assert!(result.is_err(), "Expected failure, got: {:?}", result);

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("ERR_NOT_FOUND"),
        "Error should contain error code, got: {}",
        err_msg
    );
    assert!(
        err_msg.contains("File not found"),
        "Error should contain description, got: {}",
        err_msg
    );
}

/// Test find_file when the HTTP response is a non-success status code.
#[tokio::test]
async fn test_uploader_find_file_http_error() {
    let mock_server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/find"))
        .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.find_file("uhrp://some-hash").await;
    assert!(
        result.is_err(),
        "Expected failure for HTTP 500, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("HTTP 500"),
        "Error should mention HTTP 500, got: {}",
        err_msg
    );
}

// =============================================================================
// StorageUploader Tests - list_uploads
// =============================================================================

/// Test successful list_uploads that returns an array of uploaded files.
#[tokio::test]
async fn test_uploader_list_uploads_success() {
    let mock_server = MockServer::start().await;

    let mock_uploads = serde_json::json!([
        { "uhrpUrl": "uhrp://hash1", "expiryTime": 111111 },
        { "uhrpUrl": "uhrp://hash2", "expiryTime": 222222 }
    ]);

    Mock::given(method("GET"))
        .and(path("/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "uploads": mock_uploads
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.list_uploads().await;
    assert!(result.is_ok(), "Expected success, got: {:?}", result);

    let uploads = result.unwrap();
    assert!(uploads.is_array(), "Expected an array of uploads");

    let arr = uploads.as_array().unwrap();
    assert_eq!(arr.len(), 2, "Expected 2 uploads");
    assert_eq!(arr[0]["uhrpUrl"], "uhrp://hash1");
    assert_eq!(arr[1]["expiryTime"], 222222);
}

/// Test list_uploads when the server returns an empty list.
#[tokio::test]
async fn test_uploader_list_uploads_empty() {
    let mock_server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.list_uploads().await;
    assert!(result.is_ok(), "Expected success, got: {:?}", result);

    let uploads = result.unwrap();
    // When "uploads" is absent from JSON, it defaults to empty array
    assert!(uploads.is_array(), "Expected an array");
    assert_eq!(
        uploads.as_array().unwrap().len(),
        0,
        "Expected empty array when no uploads field"
    );
}

/// Test list_uploads when the server returns an error status.
#[tokio::test]
async fn test_uploader_list_uploads_error_status() {
    let mock_server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "error",
            "code": "ERR_INTERNAL",
            "description": "Something broke"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.list_uploads().await;
    assert!(result.is_err(), "Expected failure, got: {:?}", result);

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("ERR_INTERNAL"),
        "Error should contain code, got: {}",
        err_msg
    );
    assert!(
        err_msg.contains("Something broke"),
        "Error should contain description, got: {}",
        err_msg
    );
}

/// Test list_uploads when the HTTP response is a server error.
#[tokio::test]
async fn test_uploader_list_uploads_http_500() {
    let mock_server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/list"))
        .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.list_uploads().await;
    assert!(
        result.is_err(),
        "Expected failure for HTTP 500, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("HTTP 500"),
        "Error should mention HTTP 500, got: {}",
        err_msg
    );
}

// =============================================================================
// StorageUploader Tests - renew_file
// =============================================================================

/// Test successful file renewal that returns new expiry information.
#[tokio::test]
async fn test_uploader_renew_file_success() {
    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/renew"))
        .and(header("content-type", "application/json"))
        .and(body_string_contains("\"uhrpUrl\""))
        .and(body_string_contains("\"additionalMinutes\":1440"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "prevExpiryTime": 1700000000,
            "newExpiryTime": 1700086400,
            "amount": 50
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.renew_file("uhrp://some-hash", 1440).await;
    assert!(result.is_ok(), "Expected success, got: {:?}", result);

    let renewal = result.unwrap();
    assert_eq!(renewal.status, "success");
    assert_eq!(renewal.previous_expiry, 1700000000);
    assert_eq!(renewal.new_expiry, 1700086400);
    assert_eq!(renewal.amount, 50);
    assert!(renewal.is_success());
}

/// Test renew_file when the server returns an error status in the JSON body.
#[tokio::test]
async fn test_uploader_renew_file_error_status_in_json() {
    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/renew"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "error",
            "code": "ERR_CANT_RENEW",
            "description": "Failed to renew"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.renew_file("uhrp://some-hash", 30).await;
    assert!(result.is_err(), "Expected failure, got: {:?}", result);

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("ERR_CANT_RENEW"),
        "Error should contain error code, got: {}",
        err_msg
    );
    assert!(
        err_msg.contains("Failed to renew"),
        "Error should contain description, got: {}",
        err_msg
    );
}

/// Test renew_file when the HTTP response is 404 Not Found.
#[tokio::test]
async fn test_uploader_renew_file_http_404() {
    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/renew"))
        .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.renew_file("uhrp://ghost", 10).await;
    assert!(
        result.is_err(),
        "Expected failure for 404, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("HTTP 404"),
        "Error should mention HTTP 404, got: {}",
        err_msg
    );
}

/// Test renew_file when the HTTP response is 500 Internal Server Error.
#[tokio::test]
async fn test_uploader_renew_file_http_500() {
    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/renew"))
        .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.renew_file("uhrp://some-hash", 60).await;
    assert!(
        result.is_err(),
        "Expected failure for 500, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("HTTP 500"),
        "Error should mention HTTP 500, got: {}",
        err_msg
    );
}

// =============================================================================
// StorageUploader Tests - Request Body Verification
// =============================================================================

/// Test that the /upload POST body contains the correct file size and retention period.
#[tokio::test]
async fn test_uploader_request_body_verification() {
    let mock_server = MockServer::start().await;

    let file_data = b"This is a test file with some content";
    let file = UploadableFile::new(file_data.to_vec(), "text/plain");
    let presigned_url = format!("{}/put-file", mock_server.uri());

    // Verify both fileSize and retentionPeriod appear in the body.
    // The file is 37 bytes, and the default retention is 10080 (7 days).
    Mock::given(method("POST"))
        .and(path("/upload"))
        .and(body_string_contains("\"fileSize\":37"))
        .and(body_string_contains("\"retentionPeriod\":10080"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "uploadURL": presigned_url,
            "requiredHeaders": {}
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    Mock::given(method("PUT"))
        .and(path("/put-file"))
        .respond_with(ResponseTemplate::new(200).set_body_string("OK"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.publish_file(&file, None).await;
    assert!(
        result.is_ok(),
        "Expected success for body verification, got: {:?}",
        result
    );
}

/// Test that the content-type header is correctly set on the PUT request.
#[tokio::test]
async fn test_uploader_content_type_header_verification() {
    let mock_server = MockServer::start().await;

    let file = UploadableFile::new(b"image data".to_vec(), "image/png");
    let presigned_url = format!("{}/put-file", mock_server.uri());

    Mock::given(method("POST"))
        .and(path("/upload"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "uploadURL": presigned_url,
            "requiredHeaders": {}
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    // Verify the content-type matches the file's MIME type.
    Mock::given(method("PUT"))
        .and(path("/put-file"))
        .and(header("content-type", "image/png"))
        .respond_with(ResponseTemplate::new(200).set_body_string("OK"))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.publish_file(&file, None).await;
    assert!(
        result.is_ok(),
        "Expected success for content-type verification, got: {:?}",
        result
    );
}

// =============================================================================
// StorageDownloader Tests - URL Validation and Error Paths
//
// NOTE: The StorageDownloader's download() method depends on the overlay
// network's LookupResolver to discover host URLs before downloading.
// Since we cannot easily inject a mock LookupResolver through the public API,
// we test the downloader's URL validation, error handling, and configuration.
// The actual HTTP download logic (try_download) is exercised through the
// uploader tests above, which also use reqwest internally.
// =============================================================================

use bsv_rs::storage::{StorageDownloader, StorageDownloaderConfig};

/// Test that the downloader rejects invalid UHRP URLs in the resolve() method.
#[tokio::test]
async fn test_downloader_resolve_rejects_invalid_url() {
    let downloader = StorageDownloader::default();

    let result = downloader.resolve("https://example.com").await;
    assert!(
        result.is_err(),
        "Expected error for invalid UHRP URL, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("Invalid UHRP URL"),
        "Error should mention invalid URL, got: {}",
        err_msg
    );
}

/// Test that the downloader rejects empty strings as UHRP URLs.
#[tokio::test]
async fn test_downloader_resolve_rejects_empty_url() {
    let downloader = StorageDownloader::default();

    let result = downloader.resolve("").await;
    assert!(
        result.is_err(),
        "Expected error for empty URL, got: {:?}",
        result
    );
}

/// Test that the downloader rejects non-UHRP URL formats.
#[tokio::test]
async fn test_downloader_resolve_rejects_http_url() {
    let downloader = StorageDownloader::default();

    let result = downloader.resolve("http://localhost:8080/file").await;
    assert!(
        result.is_err(),
        "Expected error for HTTP URL, got: {:?}",
        result
    );
}

/// Test that the downloader rejects invalid UHRP URLs in the download() method.
#[tokio::test]
async fn test_downloader_download_rejects_invalid_url() {
    let downloader = StorageDownloader::default();

    let result = downloader.download("not-a-valid-uhrp-url").await;
    assert!(
        result.is_err(),
        "Expected error for invalid UHRP URL in download, got: {:?}",
        result
    );

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("Invalid UHRP URL"),
        "Error should mention invalid URL, got: {}",
        err_msg
    );
}

/// Test that the downloader rejects URLs with invalid checksums.
#[tokio::test]
async fn test_downloader_resolve_rejects_bad_checksum() {
    let downloader = StorageDownloader::default();

    // Known bad checksum URL from TypeScript SDK tests
    let bad_url = "uhrp://XUU7cTfy6fA6q2neLDmzPqJnGB6o18PXKoGaWLPrH1SeWLKgdCKq";
    let result = downloader.resolve(bad_url).await;
    assert!(
        result.is_err(),
        "Expected error for bad checksum URL, got: {:?}",
        result
    );
}

/// Test downloader configuration with custom timeout.
#[tokio::test]
async fn test_downloader_config_custom_timeout() {
    let config = StorageDownloaderConfig {
        timeout_ms: Some(5000),
        ..Default::default()
    };
    let downloader = StorageDownloader::new(config);

    // Verify the downloader was created (no public timeout getter, but creation succeeds)
    assert!(std::mem::size_of_val(&downloader) > 0);
}

/// Test downloader configuration with no timeout.
#[tokio::test]
async fn test_downloader_config_no_timeout() {
    let config = StorageDownloaderConfig {
        timeout_ms: None,
        ..Default::default()
    };
    let downloader = StorageDownloader::new(config);

    // The downloader with no timeout should still be usable
    // (it will fall back to 30000ms internally in try_download)
    assert!(std::mem::size_of_val(&downloader) > 0);
}

/// Test that UHRP URL parsing works correctly for download operations.
/// This verifies the content-addressing chain: file -> hash -> URL -> hash.
#[tokio::test]
async fn test_downloader_uhrp_url_parsing() {
    use bsv_rs::storage::get_hash_from_url;

    let test_content = b"test content for download verification";
    let url = get_url_for_file(test_content).unwrap();

    // Verify the URL is valid
    assert!(is_valid_url(&url));

    // Verify we can extract the hash back from the URL
    let hash = get_hash_from_url(&url).unwrap();
    let expected_hash = bsv_rs::primitives::hash::sha256(test_content);
    assert_eq!(
        hash, expected_hash,
        "Hash extracted from UHRP URL should match SHA-256 of original content"
    );
}

// =============================================================================
// StorageUploader Tests - Renew request body verification
// =============================================================================

/// Test that the /renew POST body contains the correct UHRP URL and additional minutes.
#[tokio::test]
async fn test_uploader_renew_request_body() {
    let mock_server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/renew"))
        .and(body_string_contains(
            "\"uhrpUrl\":\"uhrp://test-file-hash\"",
        ))
        .and(body_string_contains("\"additionalMinutes\":2880"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "prevExpiryTime": 100,
            "newExpiryTime": 200,
            "amount": 10
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.renew_file("uhrp://test-file-hash", 2880).await;
    assert!(
        result.is_ok(),
        "Expected success for renew body verification, got: {:?}",
        result
    );
}

// =============================================================================
// StorageUploader Tests - Various MIME type handling
// =============================================================================

/// Test uploading files with different MIME types to verify each is sent correctly.
#[tokio::test]
async fn test_uploader_various_mime_types() {
    let mime_types = vec![
        ("text/plain", b"Hello" as &[u8]),
        ("application/json", b"{\"key\": \"value\"}"),
        ("image/jpeg", &[0xFF, 0xD8, 0xFF, 0xE0]),
        ("application/pdf", b"%PDF-1.4"),
    ];

    for (mime_type, data) in mime_types {
        let mock_server = MockServer::start().await;
        let presigned_url = format!("{}/put-file", mock_server.uri());

        Mock::given(method("POST"))
            .and(path("/upload"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "status": "success",
                "uploadURL": presigned_url,
                "requiredHeaders": {}
            })))
            .mount(&mock_server)
            .await;

        // Verify the content-type header matches the MIME type.
        Mock::given(method("PUT"))
            .and(path("/put-file"))
            .and(header("content-type", mime_type))
            .respond_with(ResponseTemplate::new(200).set_body_string("OK"))
            .expect(1)
            .mount(&mock_server)
            .await;

        let config = StorageUploaderConfig::new(mock_server.uri());
        let uploader = StorageUploader::new(config);
        let file = UploadableFile::new(data.to_vec(), mime_type);

        let result = uploader.publish_file(&file, None).await;
        assert!(
            result.is_ok(),
            "Expected success for MIME type '{}', got: {:?}",
            mime_type,
            result
        );
    }
}

// =============================================================================
// StorageUploader Tests - find_file with no data (file not found on server)
// =============================================================================

/// Test find_file when the file exists but data field is null/absent.
#[tokio::test]
async fn test_uploader_find_file_success_no_data() {
    let mock_server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/find"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success",
            "data": null
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let config = StorageUploaderConfig::new(mock_server.uri());
    let uploader = StorageUploader::new(config);

    let result = uploader.find_file("uhrp://nonexistent").await;
    assert!(result.is_ok(), "Expected success, got: {:?}", result);

    let file_data = result.unwrap();
    assert!(
        file_data.is_none(),
        "Expected None when data field is null, got: {:?}",
        file_data
    );
}