rspow 0.4.0

A multi-algorithm proof-of-work library in rust
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
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
//! RSPOW: simple multi-algorithm proof-of-work utilities.
//!
//! Supported algorithms:
//! - SHA-256, SHA-512, RIPEMD-320
//! - Scrypt, Argon2id (with custom `Params`)
//! - EquiX (Tor's Equi‑X client puzzle; we hash the solution bytes with `sha256`)
//!
//! Difficulty modes:
//! - `AsciiZeroPrefix` (default): hash must start with `difficulty` bytes of ASCII '0' (0x30).
//! - `LeadingZeroBits`: hash must have at least `difficulty` leading zero bits (big-endian within bytes).
//!
//! Quick examples:
//!
//! ```rust
//! use rspow::{PoW, PoWAlgorithm};
//!
//! let data = "hello";
//! let algorithm = PoWAlgorithm::Sha2_256;
//! let pow = PoW::new(data, 2, algorithm).unwrap();
//! let target = pow.calculate_target();
//! let (_hash, _nonce) = pow.calculate_pow(&target);
//! ```
//!
//! ```rust
//! use rspow::{PoW, PoWAlgorithm, DifficultyMode};
//!
//! let data = "hello";
//! let pow = PoW::with_mode(data, 10, PoWAlgorithm::Sha2_256, DifficultyMode::LeadingZeroBits).unwrap();
//! let (_hash, _nonce) = pow.calculate_pow(&[]); // target ignored in bits mode
//! ```
//!
use argon2::{Algorithm, Argon2, Version};
use ripemd::Ripemd320;
use serde::{ser::SerializeStruct, Deserialize, Serialize};
use sha2::{Digest, Sha256, Sha512};
// EquiX solver
use equix as equix_crate;

pub use argon2::Params as Argon2Params;
pub use scrypt::Params as ScryptParams;

// Expose KPoW (k puzzles with worker pool) utilities.
pub mod kpow;

pub mod bench {
    use super::{meets_leading_zero_bits, Argon2Params, PoWAlgorithm};
    use hex::encode as hex_encode;
    use serde::{Deserialize, Serialize};
    use std::convert::TryFrom;
    use std::time::Instant;

    /// Result of a single Proof-of-Work run.
    #[derive(Clone, Debug, Serialize, Deserialize)]
    pub struct BenchOutcome {
        pub bits: u32,
        pub data_len: usize,
        pub time_ms: u128,
        pub tries: u64,
        pub nonce: u64,
        pub hash_hex: String,
        pub m_kib: u32,
        pub t_cost: u32,
        pub p_cost: u32,
    }

    const Z95: f64 = 1.959963984540054;
    const Z99: f64 = 2.5758293035489004;

    fn confidence_bounds(mean: f64, stderr: f64) -> (f64, f64, f64, f64) {
        if stderr <= f64::EPSILON {
            return (mean, mean, mean, mean);
        }

        let ci95_low = mean - Z95 * stderr;
        let ci95_high = mean + Z95 * stderr;
        let ci99_low = mean - Z99 * stderr;
        let ci99_high = mean + Z99 * stderr;
        (ci95_low, ci95_high, ci99_low, ci99_high)
    }

    /// Construct Argon2 parameters from memory cost (KiB), time cost, and parallelism.
    #[allow(dead_code)]
    pub fn argon2_params_kib(
        memory_cost_kib: u32,
        time_cost: u32,
        parallelism: u32,
    ) -> Result<Argon2Params, String> {
        Argon2Params::new(memory_cost_kib, time_cost, parallelism, None)
            .map_err(|err| err.to_string())
    }

    /// Aggregated statistics over multiple runs.
    #[derive(Clone, Debug, Serialize, Deserialize)]
    pub struct BenchSummary {
        pub mean_time_ms: f64,
        pub std_time_ms: f64,
        pub min_time_ms: u128,
        pub max_time_ms: u128,
        pub stderr_time_ms: f64,
        pub ci95_low_time_ms: f64,
        pub ci95_high_time_ms: f64,
        pub ci99_low_time_ms: f64,
        pub ci99_high_time_ms: f64,
        pub mean_tries: f64,
        pub std_tries: f64,
        pub min_tries: u64,
        pub max_tries: u64,
        pub stderr_tries: f64,
        pub ci95_low_tries: f64,
        pub ci95_high_tries: f64,
        pub ci99_low_tries: f64,
        pub ci99_high_tries: f64,
    }

    /// Compute summary statistics across multiple outcomes.
    #[allow(dead_code)]
    pub fn summarize(outcomes: &[BenchOutcome]) -> Result<BenchSummary, String> {
        if outcomes.is_empty() {
            return Err("no outcomes supplied".to_owned());
        }

        let count = outcomes.len() as f64;

        let mut sum_time = 0.0f64;
        let mut sum_time_sq = 0.0f64;
        let mut sum_tries = 0.0f64;
        let mut sum_tries_sq = 0.0f64;
        let mut min_time = u128::MAX;
        let mut max_time = u128::MIN;
        let mut min_tries = u64::MAX;
        let mut max_tries = u64::MIN;

        for outcome in outcomes {
            let time = outcome.time_ms as f64;
            let tries = outcome.tries as f64;
            sum_time += time;
            sum_time_sq += time * time;
            sum_tries += tries;
            sum_tries_sq += tries * tries;
            min_time = min_time.min(outcome.time_ms);
            max_time = max_time.max(outcome.time_ms);
            min_tries = min_tries.min(outcome.tries);
            max_tries = max_tries.max(outcome.tries);
        }

        let mean_time_ms = sum_time / count;
        let n = outcomes.len() as f64;
        let std_time_ms = if outcomes.len() > 1 {
            let variance_time = (sum_time_sq - (sum_time * sum_time) / n) / (n - 1.0);
            variance_time.max(0.0).sqrt()
        } else {
            0.0
        };

        let stderr_time_ms = if n > 0.0 { std_time_ms / n.sqrt() } else { 0.0 };

        let (ci95_low_time_ms, ci95_high_time_ms, ci99_low_time_ms, ci99_high_time_ms) =
            confidence_bounds(mean_time_ms, stderr_time_ms);

        let mean_tries = sum_tries / count;
        let std_tries = if outcomes.len() > 1 {
            let variance_tries = (sum_tries_sq - (sum_tries * sum_tries) / n) / (n - 1.0);
            variance_tries.max(0.0).sqrt()
        } else {
            0.0
        };

        let stderr_tries = if n > 0.0 { std_tries / n.sqrt() } else { 0.0 };

        let (ci95_low_tries, ci95_high_tries, ci99_low_tries, ci99_high_tries) =
            confidence_bounds(mean_tries, stderr_tries);

        Ok(BenchSummary {
            mean_time_ms,
            std_time_ms,
            min_time_ms: min_time,
            max_time_ms: max_time,
            stderr_time_ms,
            ci95_low_time_ms,
            ci95_high_time_ms,
            ci99_low_time_ms,
            ci99_high_time_ms,
            mean_tries,
            std_tries,
            min_tries,
            max_tries,
            stderr_tries,
            ci95_low_tries,
            ci95_high_tries,
            ci99_low_tries,
            ci99_high_tries,
        })
    }

    /// CSV header shared by run rows and summary rows.
    #[allow(dead_code)]
    pub const fn csv_header() -> &'static str {
        "kind,algo,mode,m_kib,t_cost,p_cost,data_len,bits,run_idx,time_ms,tries,nonce,hash_hex,mean_time_ms,std_time_ms,stderr_time_ms,ci95_low_time_ms,ci95_high_time_ms,ci99_low_time_ms,ci99_high_time_ms,min_time_ms,max_time_ms,mean_tries,std_tries,stderr_tries,ci95_low_tries,ci95_high_tries,ci99_low_tries,ci99_high_tries,min_tries,max_tries"
    }

    /// Format a single run outcome as a CSV row.
    #[allow(dead_code)]
    pub fn csv_row_run(outcome: &BenchOutcome, algo: &str, mode: &str, run_idx: u32) -> String {
        format!(
            "run,{algo},{mode},{},{},{},{},{},{},{},{},{},{},,,,,,,,",
            outcome.m_kib,
            outcome.t_cost,
            outcome.p_cost,
            outcome.data_len,
            outcome.bits,
            run_idx,
            outcome.time_ms,
            outcome.tries,
            outcome.nonce,
            outcome.hash_hex
        )
    }

    /// Format summary statistics as a CSV row.
    #[allow(dead_code)]
    #[allow(clippy::too_many_arguments)]
    pub fn csv_row_summary(
        bits: u32,
        data_len: usize,
        m_kib: u32,
        t_cost: u32,
        p_cost: u32,
        summary: &BenchSummary,
        algo: &str,
        mode: &str,
    ) -> String {
        format!(
            "summary,{algo},{mode},{m_kib},{t_cost},{p_cost},{data_len},{bits},,,,,,{:.6},{:.6},{:.6},{:.6},{:.6},{:.6},{:.6},{},{},{:.6},{:.6},{:.6},{:.6},{:.6},{:.6},{:.6},{},{}",
            summary.mean_time_ms,
            summary.std_time_ms,
            summary.stderr_time_ms,
            summary.ci95_low_time_ms,
            summary.ci95_high_time_ms,
            summary.ci99_low_time_ms,
            summary.ci99_high_time_ms,
            summary.min_time_ms,
            summary.max_time_ms,
            summary.mean_tries,
            summary.std_tries,
            summary.stderr_tries,
            summary.ci95_low_tries,
            summary.ci95_high_tries,
            summary.ci99_low_tries,
            summary.ci99_high_tries,
            summary.min_tries,
            summary.max_tries
        )
    }

    /// Run Argon2id PoW search once using LeadingZeroBits difficulty.
    #[allow(dead_code)]
    pub fn bench_argon2_leading_bits_once(
        data: &[u8],
        bits: u32,
        params: &Argon2Params,
        start_nonce: u64,
    ) -> Result<BenchOutcome, String> {
        let mut nonce = start_nonce;
        let mut tries: u64 = 0;
        let algorithm = PoWAlgorithm::Argon2id(params.clone());
        let start = Instant::now();

        loop {
            let nonce_usize = usize::try_from(nonce)
                .map_err(|_| "nonce exceeds usize::MAX on this platform".to_owned())?;
            let hash = algorithm.calculate(data, nonce_usize);
            tries = tries
                .checked_add(1)
                .ok_or_else(|| "tries overflow".to_owned())?;
            if meets_leading_zero_bits(&hash, bits) {
                let time_ms = start.elapsed().as_millis();
                return Ok(BenchOutcome {
                    bits,
                    data_len: data.len(),
                    time_ms,
                    tries,
                    nonce,
                    hash_hex: hex_encode(hash),
                    m_kib: params.m_cost(),
                    t_cost: params.t_cost(),
                    p_cost: params.p_cost(),
                });
            }
            nonce = nonce
                .checked_add(1)
                .ok_or_else(|| "nonce overflow".to_owned())?;
        }
    }

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

        #[test]
        fn summarize_basic_stats() {
            let outcomes = [
                BenchOutcome {
                    bits: 1,
                    data_len: 4,
                    time_ms: 10,
                    tries: 2,
                    nonce: 5,
                    hash_hex: String::new(),
                    m_kib: 8,
                    t_cost: 1,
                    p_cost: 1,
                },
                BenchOutcome {
                    bits: 1,
                    data_len: 4,
                    time_ms: 20,
                    tries: 4,
                    nonce: 6,
                    hash_hex: String::new(),
                    m_kib: 8,
                    t_cost: 1,
                    p_cost: 1,
                },
            ];

            let summary = summarize(&outcomes).expect("summary");
            assert_eq!(summary.min_time_ms, 10);
            assert_eq!(summary.max_time_ms, 20);
            assert_eq!(summary.min_tries, 2);
            assert_eq!(summary.max_tries, 4);
            assert!((summary.mean_time_ms - 15.0).abs() < f64::EPSILON);
            assert!((summary.mean_tries - 3.0).abs() < f64::EPSILON);
            assert!((summary.std_time_ms - 7.0710678118654755).abs() < 1e-9);
            assert!((summary.stderr_time_ms - 5.0).abs() < 1e-9);
            assert!((summary.ci95_low_time_ms - 5.200180077299731).abs() < 1e-6);
            assert!((summary.ci95_high_time_ms - 24.79981992270027).abs() < 1e-6);
            assert!((summary.ci99_low_time_ms - 2.120853482255498).abs() < 1e-6);
            assert!((summary.ci99_high_time_ms - 27.879146517744502).abs() < 1e-6);
            assert!((summary.std_tries - 1.4142135623730951).abs() < 1e-9);
            assert!((summary.stderr_tries - 1.0).abs() < 1e-9);
            assert!((summary.ci95_low_tries - 1.040036015459946).abs() < 1e-6);
            assert!((summary.ci95_high_tries - 4.959963984540054).abs() < 1e-6);
            assert!((summary.ci99_low_tries - 0.4241706964510996).abs() < 1e-6);
            assert!((summary.ci99_high_tries - 5.5758293035489).abs() < 1e-6);
        }

        #[test]
        fn summarize_single_sample() {
            let outcomes = [BenchOutcome {
                bits: 1,
                data_len: 4,
                time_ms: 42,
                tries: 7,
                nonce: 10,
                hash_hex: String::new(),
                m_kib: 8,
                t_cost: 1,
                p_cost: 1,
            }];

            let summary = summarize(&outcomes).expect("summary");
            assert_eq!(summary.mean_time_ms, 42.0);
            assert_eq!(summary.std_time_ms, 0.0);
            assert_eq!(summary.stderr_time_ms, 0.0);
            assert_eq!(summary.ci95_low_time_ms, 42.0);
            assert_eq!(summary.ci95_high_time_ms, 42.0);
            assert_eq!(summary.ci99_low_time_ms, 42.0);
            assert_eq!(summary.ci99_high_time_ms, 42.0);
            assert_eq!(summary.mean_tries, 7.0);
            assert_eq!(summary.std_tries, 0.0);
            assert_eq!(summary.stderr_tries, 0.0);
        }

        #[test]
        fn csv_alignment_summary_columns() {
            let header = csv_header();
            let h: Vec<&str> = header.split(',').collect();
            // Build a tiny summary from two outcomes
            let outcomes = [
                BenchOutcome {
                    bits: 1,
                    data_len: 4,
                    time_ms: 10,
                    tries: 2,
                    nonce: 0,
                    hash_hex: String::new(),
                    m_kib: 8,
                    t_cost: 1,
                    p_cost: 1,
                },
                BenchOutcome {
                    bits: 1,
                    data_len: 4,
                    time_ms: 20,
                    tries: 4,
                    nonce: 0,
                    hash_hex: String::new(),
                    m_kib: 8,
                    t_cost: 1,
                    p_cost: 1,
                },
            ];
            let s = summarize(&outcomes).unwrap();
            let row = csv_row_summary(1, 4, 8, 1, 1, &s, "argon2id", "leading_zero_bits");
            let c: Vec<&str> = row.split(',').collect();
            assert_eq!(h.len(), c.len(), "header/row column count mismatch");
            // Header indices (1-based): 19=ci99_low_time_ms, 20=ci99_high_time_ms
            let ci99_low_time: f64 = c[18].parse().unwrap();
            let ci99_high_time: f64 = c[19].parse().unwrap();
            assert!(ci99_low_time <= ci99_high_time);
            // 28=ci99_low_tries, 29=ci99_high_tries (1-based)
            let ci99_low_tries: f64 = c[27].parse().unwrap();
            let ci99_high_tries: f64 = c[28].parse().unwrap();
            assert!(ci99_low_tries <= ci99_high_tries);
        }
    }
}

// ===== EquiX proof-carrying (low‑cost verification) helpers =====

/// 16‑byte EquiX solution (8×u16, LE) — stable wrapper for external use.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EquixSolution(pub [u8; 16]);

/// A proof for EquiX: includes `work_nonce` and the concrete solution bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EquixProof {
    /// Client‑selected search nonce; server replays it to rebuild the challenge.
    pub work_nonce: u64,
    /// Concrete EquiX solution bytes; verifier checks with `equix::verify_bytes`.
    pub solution: EquixSolution,
}

/// A bundle of EquiX proofs along with a base tag for replay protection.
/// Server can store only the `base_tag`; the remaining tags can be derived deterministically.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EquixProofBundle {
    pub base_tag: [u8; 32],
    pub proofs: Vec<EquixProof>,
}

impl EquixProofBundle {
    /// Verify all proofs against the provided seed and difficulty.
    pub fn verify_all(&self, seed: &[u8], bits: u32) -> Result<Vec<bool>, String> {
        let mut out = Vec::with_capacity(self.proofs.len());
        for p in &self.proofs {
            let ok = equix_check_bits(seed, p, bits)?;
            out.push(ok);
        }
        Ok(out)
    }

    /// Derived tags for proofs[1..]; server can avoid storing multiple keys.
    pub fn derived_tags(&self) -> Vec<[u8; 32]> {
        if self.proofs.len() <= 1 {
            return Vec::new();
        }
        derive_replay_tags(&self.base_tag, self.proofs.len() - 1)
    }
}

/// Build EquiX challenge bytes from an application‑defined seed and a `work_nonce`.
///
/// Recommendation: let `seed = SHA256("rspow:equix:v1|" || encode(server_nonce) || encode(data))`.
/// Then reuse `seed` across attempts and only vary `work_nonce` per try.
pub fn equix_challenge(seed: &[u8], work_nonce: u64) -> Vec<u8> {
    let mut ch = Vec::with_capacity(seed.len() + 8);
    ch.extend_from_slice(seed);
    ch.extend_from_slice(&work_nonce.to_le_bytes());
    ch
}

/// Verify a single EquiX proof and return `sha256(solution_bytes)` if valid.
///
/// This is an O(1) verification path: it does not try to solve EquiX.
pub fn equix_verify_solution(seed: &[u8], proof: &EquixProof) -> Result<[u8; 32], String> {
    let challenge = equix_challenge(seed, proof.work_nonce);
    equix_crate::verify_bytes(&challenge, &proof.solution.0).map_err(|e| e.to_string())?;
    let mut hasher = Sha256::new();
    hasher.update(proof.solution.0);
    let h = hasher.finalize();
    Ok(h.into())
}

/// Verify that the proof meets a leading‑zero‑bits difficulty.
pub fn equix_check_bits(seed: &[u8], proof: &EquixProof, bits: u32) -> Result<bool, String> {
    let hash = equix_verify_solution(seed, proof)?;
    Ok(meets_leading_zero_bits(&hash, bits))
}

/// Solve EquiX by varying `work_nonce`, returning the first proof meeting `bits`.
///
/// This is the client‑side search routine. It skips challenges that construct/solve with
/// zero solutions and continues with the next `work_nonce`.
pub fn equix_solve_with_bits(
    seed: &[u8],
    bits: u32,
    start_work_nonce: u64,
) -> Result<(EquixProof, [u8; 32]), String> {
    let mut work_nonce = start_work_nonce;
    loop {
        let challenge = equix_challenge(seed, work_nonce);
        // Build EquiX; on rare constraint errors, skip to next work_nonce.
        let equix = match equix_crate::EquiX::new(&challenge) {
            Ok(e) => e,
            Err(_) => {
                work_nonce = work_nonce
                    .checked_add(1)
                    .ok_or_else(|| "work_nonce overflow".to_owned())?;
                continue;
            }
        };
        let solutions = equix.solve();
        for sol in solutions.iter() {
            let bytes = sol.to_bytes();
            let mut hasher = Sha256::new();
            hasher.update(bytes);
            let hash: [u8; 32] = hasher.finalize().into();
            if meets_leading_zero_bits(&hash, bits) {
                let proof = EquixProof {
                    work_nonce,
                    solution: EquixSolution(bytes),
                };
                return Ok((proof, hash));
            }
        }
        work_nonce = work_nonce
            .checked_add(1)
            .ok_or_else(|| "work_nonce overflow".to_owned())?;
    }
}

/// Parallel EquiX solve: collect up to `hits` proofs using `threads` workers, varying `work_nonce`.
#[allow(clippy::type_complexity)]
pub fn equix_solve_parallel_hits(
    seed: &[u8],
    bits: u32,
    hits: usize,
    threads: usize,
    start_work_nonce: u64,
) -> Result<Vec<(EquixProof, [u8; 32])>, String> {
    use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};
    use std::thread;

    if threads == 0 || hits == 0 {
        return Err("threads and hits must be >= 1".to_owned());
    }
    let seed = seed.to_vec();
    let next_wn = Arc::new(AtomicU64::new(start_work_nonce));
    let found = Arc::new(AtomicUsize::new(0));
    let stop = Arc::new(AtomicBool::new(false));
    let out: Arc<Mutex<Vec<(EquixProof, [u8; 32])>>> =
        Arc::new(Mutex::new(Vec::with_capacity(hits)));

    let mut joins = Vec::with_capacity(threads);
    for _ in 0..threads {
        let seed_t = seed.clone();
        let next_t = next_wn.clone();
        let found_t = found.clone();
        let stop_t = stop.clone();
        let out_t = out.clone();
        let j = thread::spawn(move || {
            loop {
                if stop_t.load(Ordering::Relaxed) {
                    break;
                }
                let wn = next_t.fetch_add(1, Ordering::Relaxed);
                let challenge = equix_challenge(&seed_t, wn);
                let eq = match equix_crate::EquiX::new(&challenge) {
                    Ok(e) => e,
                    Err(_) => continue,
                };
                let sols = eq.solve();
                for sol in sols.iter() {
                    let bytes = sol.to_bytes();
                    let mut hasher = Sha256::new();
                    hasher.update(bytes);
                    let hash: [u8; 32] = hasher.finalize().into();
                    if meets_leading_zero_bits(&hash, bits) {
                        let proof = EquixProof {
                            work_nonce: wn,
                            solution: EquixSolution(bytes),
                        };
                        if let Ok(mut v) = out_t.lock() {
                            if v.len() < hits {
                                v.push((proof, hash));
                                let f = found_t.fetch_add(1, Ordering::SeqCst) + 1;
                                if f >= hits {
                                    stop_t.store(true, Ordering::SeqCst);
                                }
                            }
                        }
                        break; // next work_nonce
                    }
                }
            }
        });
        joins.push(j);
    }
    for j in joins {
        let _ = j.join();
    }
    let out = out
        .lock()
        .map(|v| v.clone())
        .map_err(|_| "poison".to_owned())?;
    Ok(out)
}

/// Derive replay tags from a base tag to avoid storing multiple keys server-side.
/// If your server has a secret, prefer HMAC(base, idx) at the application layer.
pub fn derive_replay_tags(base_tag: &[u8; 32], count: usize) -> Vec<[u8; 32]> {
    let mut v = Vec::with_capacity(count);
    for i in 1..=count {
        let mut h = Sha256::new();
        h.update(b"rspow:replay:v1|");
        h.update(base_tag);
        h.update((i as u64).to_le_bytes());
        v.push(h.finalize().into());
    }
    v
}

// ===== Generic parallel PoW (multi-hit) =====

/// A single PoW hit found by the parallel solver.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PowHit {
    pub nonce: u64,
    pub hash: [u8; 32],
}

/// Configuration for the parallel PoW solver.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ParPowCfg {
    pub threads: usize,
    pub hits: usize,
    pub start_nonce: u64,
}

impl ParPowCfg {
    /// Build a configuration with default threads = max(1, num_cpus-1), hits=1, start_nonce=0.
    pub fn default_with_hits(hits: usize) -> Self {
        let p = std::thread::available_parallelism()
            .map(|nz| nz.get())
            .unwrap_or(1)
            .saturating_sub(1)
            .max(1);
        ParPowCfg {
            threads: p,
            hits,
            start_nonce: 0,
        }
    }
}

/// Solve a PoW in parallel and collect up to `cfg.hits` distinct nonces that satisfy the difficulty.
/// Works with any `PoWAlgorithm` and both difficulty modes.
pub fn pow_solve_parallel_hits(pow: &PoW, cfg: &ParPowCfg) -> Result<Vec<PowHit>, String> {
    use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};
    use std::thread;

    if cfg.threads == 0 || cfg.hits == 0 {
        return Err("threads and hits must be >= 1".to_owned());
    }

    let pow = pow.clone();
    let target_ascii = match pow.mode {
        DifficultyMode::AsciiZeroPrefix => Some(pow.calculate_target()),
        DifficultyMode::LeadingZeroBits => None,
    };
    let next_nonce = Arc::new(AtomicU64::new(cfg.start_nonce));
    let found = Arc::new(AtomicUsize::new(0));
    let stop = Arc::new(AtomicBool::new(false));
    let hits: Arc<Mutex<Vec<PowHit>>> = Arc::new(Mutex::new(Vec::with_capacity(cfg.hits)));

    let mut joins = Vec::with_capacity(cfg.threads);
    for _ in 0..cfg.threads {
        let pow_t = pow.clone();
        let target_t = target_ascii.clone();
        let next = next_nonce.clone();
        let found_t = found.clone();
        let stop_t = stop.clone();
        let hits_t = hits.clone();
        let hits_cap = cfg.hits;
        let j = thread::spawn(move || loop {
            if stop_t.load(Ordering::Relaxed) {
                break;
            }
            let n = next.fetch_add(1, Ordering::Relaxed) as usize;
            let hash_vec = pow_t.algorithm.calculate(&pow_t.data, n);
            let ok = match pow_t.mode {
                DifficultyMode::AsciiZeroPrefix => {
                    let t = target_t.as_ref().expect("ascii target exists");
                    hash_vec.starts_with(t)
                }
                DifficultyMode::LeadingZeroBits => {
                    meets_leading_zero_bits(&hash_vec, pow_t.difficulty as u32)
                }
            };
            if ok {
                let mut h32 = [0u8; 32];
                h32.copy_from_slice(&hash_vec[..32.min(hash_vec.len())]);
                if let Ok(mut v) = hits_t.lock() {
                    if v.len() < hits_cap {
                        v.push(PowHit {
                            nonce: n as u64,
                            hash: h32,
                        });
                        let f = found_t.fetch_add(1, Ordering::SeqCst) + 1;
                        if f >= hits_cap {
                            stop_t.store(true, Ordering::SeqCst);
                            break;
                        }
                    }
                }
            }
        });
        joins.push(j);
    }
    for j in joins {
        let _ = j.join();
    }
    let out = hits
        .lock()
        .map(|v| v.clone())
        .map_err(|_| "poison".to_owned())?;
    Ok(out)
}

/// Enum defining different Proof of Work (PoW) algorithms.
#[allow(non_camel_case_types)]
#[derive(Clone, Debug)]
pub enum PoWAlgorithm {
    Sha2_256,
    Sha2_512,
    RIPEMD_320,
    Scrypt(ScryptParams),
    Argon2id(Argon2Params),
    /// Equi‑X client puzzle: challenge is `data || nonce_le`.
    /// If one or more solutions exist, take the lexicographically smallest
    /// solution's bytes, hash with `sha256`, and use that as the output.
    /// If there is no solution or construction fails, return 32 bytes of 0xFF
    /// (ensures difficulty check fails).
    EquiX,
}

impl PoWAlgorithm {
    /// Calculates SHA-256 hash with given data and nonce.
    pub fn calculate_sha2_256(data: &[u8], nonce: usize) -> Vec<u8> {
        let mut hasher = Sha256::new();
        hasher.update(data);

        hasher.update(nonce.to_le_bytes());

        let final_hash = hasher.finalize();

        final_hash.to_vec()
    }

    /// Calculates SHA-512 hash with given data and nonce.
    pub fn calculate_sha2_512(data: &[u8], nonce: usize) -> Vec<u8> {
        let mut hasher = Sha512::new();
        hasher.update(data);

        hasher.update(nonce.to_le_bytes());

        let final_hash = hasher.finalize();

        final_hash.to_vec()
    }

    /// Calculates RIPEMD320 hash with given data and nonce.
    pub fn calculate_ripemd_320(data: &[u8], nonce: usize) -> Vec<u8> {
        let mut hasher = Ripemd320::new();
        hasher.update(data);

        hasher.update(nonce.to_le_bytes());

        let final_hash = hasher.finalize();

        final_hash.to_vec()
    }

    /// Calculates Argon2id hash with given data and nonce.
    pub fn calculate_scrypt(data: &[u8], nonce: usize, params: &ScryptParams) -> Vec<u8> {
        let mut output = vec![0; 32];

        let _ = scrypt::scrypt(data, &nonce.to_le_bytes(), params, &mut output);

        output
    }

    /// Calculates Scrypt hash with given data and nonce.
    pub fn calculate_argon2id(data: &[u8], nonce: usize, params: &Argon2Params) -> Vec<u8> {
        let mut output = vec![0; 32];
        let a2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params.to_owned());
        a2.hash_password_into(data, &nonce.to_le_bytes(), &mut output)
            .unwrap();

        output
    }

    /// Calculates EquiX-based pseudo-hash with given data and nonce.
    ///
    /// Rule: challenge = `data || nonce.to_le_bytes()`. Run EquiX.
    /// If solutions exist, choose the lexicographically smallest 16‑byte
    /// solution and return `sha256(solution_bytes)`; otherwise or on error,
    /// return 32 bytes of `0xFF`.
    pub fn calculate_equix(data: &[u8], nonce: usize) -> Vec<u8> {
        // Build challenge: data || nonce (little‑endian)
        let mut challenge = Vec::with_capacity(data.len() + std::mem::size_of::<usize>());
        challenge.extend_from_slice(data);
        challenge.extend_from_slice(&nonce.to_le_bytes());

        // Instantiate EquiX and solve
        let equix = match equix_crate::EquiX::new(&challenge) {
            Ok(e) => e,
            Err(_) => return vec![0xFFu8; 32],
        };
        let solutions = equix.solve();
        if solutions.is_empty() {
            return vec![0xFFu8; 32];
        }

        // Pick lexicographically smallest solution bytes
        let mut best: Option<Vec<u8>> = None;
        for sol in solutions.iter() {
            let bytes = sol.to_bytes(); // fixed 16 bytes
            match &mut best {
                None => best = Some(bytes.to_vec()),
                Some(prev) => {
                    if bytes.as_slice() < prev.as_slice() {
                        *prev = bytes.to_vec();
                    }
                }
            }
        }

        let best_bytes = best.expect("solutions not empty");
        let mut hasher = Sha256::new();
        hasher.update(&best_bytes);
        hasher.finalize().to_vec()
    }

    /// Calculates hash based on the selected algorithm.
    pub fn calculate(&self, data: &[u8], nonce: usize) -> Vec<u8> {
        match self {
            Self::Sha2_256 => Self::calculate_sha2_256(data, nonce),
            Self::Sha2_512 => Self::calculate_sha2_512(data, nonce),
            Self::RIPEMD_320 => Self::calculate_ripemd_320(data, nonce),
            Self::Scrypt(params) => Self::calculate_scrypt(data, nonce, params),
            Self::Argon2id(params) => Self::calculate_argon2id(data, nonce, params),
            Self::EquiX => Self::calculate_equix(data, nonce),
        }
    }
}

/// Utility: check whether `hash` has at least `bits` leading zero bits.
///
/// Convention: count leading zero bits in big-endian bit order within each byte
/// (i.e., the most significant bit is checked first).
/// - When `bits == 0`, return `true`.
/// - When `bits > hash.len() * 8`, return `false`.
pub fn meets_leading_zero_bits(hash: &[u8], bits: u32) -> bool {
    if bits == 0 {
        return true;
    }
    let total_bits = (hash.len() as u32) * 8;
    if bits > total_bits {
        return false;
    }

    let full_bytes = (bits / 8) as usize;
    let rem_bits = (bits % 8) as u8;

    // Full-zero check for bytes fully covered by `bits`.
    for b in hash.iter().take(full_bytes) {
        if *b != 0 {
            return false;
        }
    }

    // Remaining high bits in the next byte must be zero as well.
    if rem_bits > 0 {
        let b = hash[full_bytes];
        let mask = 0xFFu8 << (8 - rem_bits);
        if (b & mask) != 0 {
            return false;
        }
    }

    true
}

/// Difficulty modes supported by PoW.
#[derive(Clone, Copy, Debug)]
pub enum DifficultyMode {
    /// Legacy mode: prefix must be ASCII '0' bytes (0x30), one per difficulty level.
    AsciiZeroPrefix,
    /// New mode: require a given number of leading zero bits.
    LeadingZeroBits,
}

/// Struct representing Proof of Work (PoW) with data, difficulty, and algorithm.
#[derive(Clone, Debug)]
pub struct PoW {
    data: Vec<u8>,
    difficulty: usize,
    algorithm: PoWAlgorithm,
    mode: DifficultyMode,
}

// ---- Eq / PartialEq / Hash for DifficultyMode, PoWAlgorithm, PoW ----

impl PartialEq for DifficultyMode {
    fn eq(&self, other: &Self) -> bool {
        matches!(
            (self, other),
            (Self::AsciiZeroPrefix, Self::AsciiZeroPrefix)
                | (Self::LeadingZeroBits, Self::LeadingZeroBits)
        )
    }
}
impl Eq for DifficultyMode {}
impl std::hash::Hash for DifficultyMode {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            DifficultyMode::AsciiZeroPrefix => 0u8.hash(state),
            DifficultyMode::LeadingZeroBits => 1u8.hash(state),
        }
    }
}

impl PartialEq for PoWAlgorithm {
    fn eq(&self, other: &Self) -> bool {
        use PoWAlgorithm::*;
        match (self, other) {
            (Sha2_256, Sha2_256) => true,
            (Sha2_512, Sha2_512) => true,
            (RIPEMD_320, RIPEMD_320) => true,
            (Scrypt(a), Scrypt(b)) => a.log_n() == b.log_n() && a.r() == b.r() && a.p() == b.p(),
            (Argon2id(a), Argon2id(b)) => {
                a.m_cost() == b.m_cost() && a.t_cost() == b.t_cost() && a.p_cost() == b.p_cost()
            }
            (EquiX, EquiX) => true,
            _ => false,
        }
    }
}
impl Eq for PoWAlgorithm {}
impl std::hash::Hash for PoWAlgorithm {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        use PoWAlgorithm::*;
        match self {
            Sha2_256 => 0u8.hash(state),
            Sha2_512 => 1u8.hash(state),
            RIPEMD_320 => 2u8.hash(state),
            Scrypt(p) => {
                3u8.hash(state);
                p.log_n().hash(state);
                p.r().hash(state);
                p.p().hash(state);
            }
            Argon2id(p) => {
                4u8.hash(state);
                p.m_cost().hash(state);
                p.t_cost().hash(state);
                p.p_cost().hash(state);
            }
            EquiX => 5u8.hash(state),
        }
    }
}

impl PartialEq for PoW {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
            && self.difficulty == other.difficulty
            && self.algorithm == other.algorithm
            && self.mode == other.mode
    }
}
impl Eq for PoW {}
impl std::hash::Hash for PoW {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.data.hash(state);
        self.difficulty.hash(state);
        self.algorithm.hash(state);
        self.mode.hash(state);
    }
}

// ---- Serde for DifficultyMode, PoWAlgorithm, PoW ----

impl Serialize for DifficultyMode {
    fn serialize<S>(
        &self,
        serializer: S,
    ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>
    where
        S: serde::Serializer,
    {
        match self {
            DifficultyMode::AsciiZeroPrefix => serializer.serialize_str("AsciiZeroPrefix"),
            DifficultyMode::LeadingZeroBits => serializer.serialize_str("LeadingZeroBits"),
        }
    }
}

impl<'de> Deserialize<'de> for DifficultyMode {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        match s.as_str() {
            "AsciiZeroPrefix" => Ok(DifficultyMode::AsciiZeroPrefix),
            "LeadingZeroBits" => Ok(DifficultyMode::LeadingZeroBits),
            other => Err(serde::de::Error::unknown_variant(
                other,
                &["AsciiZeroPrefix", "LeadingZeroBits"],
            )),
        }
    }
}

impl Serialize for PoWAlgorithm {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use PoWAlgorithm::*;
        match self {
            Sha2_256 => serializer.serialize_str("Sha2_256"),
            Sha2_512 => serializer.serialize_str("Sha2_512"),
            RIPEMD_320 => serializer.serialize_str("RIPEMD_320"),
            EquiX => serializer.serialize_str("EquiX"),
            Scrypt(p) => {
                #[derive(Serialize)]
                struct ScryptParamsSer {
                    log_n: u8,
                    r: u32,
                    p: u32,
                }
                let wrapper = ScryptParamsSer {
                    log_n: p.log_n(),
                    r: p.r(),
                    p: p.p(),
                };
                let mut st = serializer.serialize_struct("Scrypt", 1)?;
                st.serialize_field("Scrypt", &wrapper)?;
                st.end()
            }
            Argon2id(p) => {
                #[derive(Serialize)]
                struct Argon2ParamsSer {
                    m_kib: u32,
                    t_cost: u32,
                    p_cost: u32,
                }
                let wrapper = Argon2ParamsSer {
                    m_kib: p.m_cost(),
                    t_cost: p.t_cost(),
                    p_cost: p.p_cost(),
                };
                let mut st = serializer.serialize_struct("Argon2id", 1)?;
                st.serialize_field("Argon2id", &wrapper)?;
                st.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for PoWAlgorithm {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::{Error, MapAccess, Visitor};
        use std::fmt;

        // Accept either a unit string variant or an object {Variant: {..}} for params variants
        struct AlgoVisitor;
        impl<'de> Visitor<'de> for AlgoVisitor {
            type Value = PoWAlgorithm;
            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("PoWAlgorithm as string or single-key object")
            }
            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: Error,
            {
                match v {
                    "Sha2_256" => Ok(PoWAlgorithm::Sha2_256),
                    "Sha2_512" => Ok(PoWAlgorithm::Sha2_512),
                    "RIPEMD_320" => Ok(PoWAlgorithm::RIPEMD_320),
                    "EquiX" => Ok(PoWAlgorithm::EquiX),
                    _ => Err(E::unknown_variant(
                        v,
                        &[
                            "Sha2_256",
                            "Sha2_512",
                            "RIPEMD_320",
                            "Scrypt",
                            "Argon2id",
                            "EquiX",
                        ],
                    )),
                }
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                if let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "Scrypt" => {
                            #[derive(Deserialize)]
                            struct ScryptParamsDe {
                                log_n: u8,
                                r: u32,
                                p: u32,
                            }
                            let p = map.next_value::<ScryptParamsDe>()?;
                            // We default to 32 bytes output length which matches this crate's use.
                            let params = ScryptParams::new(p.log_n, p.r, p.p, 32)
                                .map_err(|e| A::Error::custom(e.to_string()))?;
                            Ok(PoWAlgorithm::Scrypt(params))
                        }
                        "Argon2id" => {
                            #[derive(Deserialize)]
                            struct Argon2ParamsDe {
                                m_kib: u32,
                                t_cost: u32,
                                p_cost: u32,
                            }
                            let p = map.next_value::<Argon2ParamsDe>()?;
                            let params = Argon2Params::new(p.m_kib, p.t_cost, p.p_cost, None)
                                .map_err(|e| A::Error::custom(e.to_string()))?;
                            Ok(PoWAlgorithm::Argon2id(params))
                        }
                        other => Err(A::Error::unknown_field(other, &["Scrypt", "Argon2id"])),
                    }
                } else {
                    Err(A::Error::custom("empty map for PoWAlgorithm"))
                }
            }
        }
        deserializer.deserialize_any(AlgoVisitor)
    }
}

impl Serialize for PoW {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;
        let mut st = serializer.serialize_struct("PoW", 4)?;
        st.serialize_field("data", &self.data)?;
        st.serialize_field("difficulty", &self.difficulty)?;
        st.serialize_field("algorithm", &self.algorithm)?;
        st.serialize_field("mode", &self.mode)?;
        st.end()
    }
}

impl<'de> Deserialize<'de> for PoW {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct PoWDe {
            data: Vec<u8>,
            difficulty: usize,
            algorithm: PoWAlgorithm,
            mode: DifficultyMode,
        }
        let raw = PoWDe::deserialize(deserializer)?;
        Ok(PoW {
            data: raw.data,
            difficulty: raw.difficulty,
            algorithm: raw.algorithm,
            mode: raw.mode,
        })
    }
}

impl PoW {
    /// Creates a new instance of PoW with serialized data, difficulty, and algorithm.
    pub fn new(
        data: impl Serialize,
        difficulty: usize,
        algorithm: PoWAlgorithm,
    ) -> Result<Self, String> {
        Ok(PoW {
            data: serde_json::to_vec(&data).unwrap(),
            difficulty,
            algorithm,
            mode: DifficultyMode::AsciiZeroPrefix,
        })
    }

    /// Creates a new instance of PoW with explicit difficulty mode.
    pub fn with_mode(
        data: impl Serialize,
        difficulty: usize,
        algorithm: PoWAlgorithm,
        mode: DifficultyMode,
    ) -> Result<Self, String> {
        Ok(PoW {
            data: serde_json::to_vec(&data).unwrap(),
            difficulty,
            algorithm,
            mode,
        })
    }

    /// Calculates the target of ASCII '0' bytes based on difficulty.
    ///
    /// Note: meaningful only for `AsciiZeroPrefix` mode; ignored for `LeadingZeroBits`.
    pub fn calculate_target(&self) -> Vec<u8> {
        // 0x30 is code for ascii character '0'
        vec![0x30u8; self.difficulty]
    }

    /// Calculates PoW with the given target hash.
    /// For `AsciiZeroPrefix`, the `target` must be the ASCII '0' prefix of length `difficulty`.
    /// For `LeadingZeroBits`, `target` is ignored; `difficulty` is interpreted as bit count.
    pub fn calculate_pow(&self, target: &[u8]) -> (Vec<u8>, usize) {
        let mut nonce = 0;

        loop {
            let hash = self.algorithm.calculate(&self.data, nonce);
            match self.mode {
                DifficultyMode::AsciiZeroPrefix => {
                    if &hash[..target.len()] == target {
                        return (hash, nonce);
                    }
                }
                DifficultyMode::LeadingZeroBits => {
                    if meets_leading_zero_bits(&hash, self.difficulty as u32) {
                        return (hash, nonce);
                    }
                }
            }
            nonce += 1;
        }
    }

    /// Verifies PoW with the given target hash and PoW result.
    pub fn verify_pow(&self, target: &[u8], pow_result: (Vec<u8>, usize)) -> bool {
        let (hash, nonce) = pow_result;

        let calculated_hash = self.algorithm.calculate(&self.data, nonce);
        match self.mode {
            DifficultyMode::AsciiZeroPrefix => {
                if &calculated_hash[..target.len()] == target && calculated_hash == hash {
                    return true;
                }
                false
            }
            DifficultyMode::LeadingZeroBits => {
                if meets_leading_zero_bits(&calculated_hash, self.difficulty as u32)
                    && calculated_hash == hash
                {
                    return true;
                }
                false
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{from_str, to_string};
    use std::collections::HashSet;

    #[test]
    fn test_pow_algorithm_sha2_256() {
        let data = b"hello world";
        let nonce = 12345;
        let expected_hash = [
            113, 212, 92, 254, 42, 99, 0, 112, 60, 9, 31, 138, 105, 191, 234, 231, 122, 30, 73, 12,
            3, 10, 182, 230, 134, 80, 94, 32, 162, 164, 204, 9,
        ];
        let hash = PoWAlgorithm::calculate_sha2_256(data, nonce);

        assert_eq!(hash, expected_hash);
    }

    #[test]
    fn test_pow_algorithm_sha2_512() {
        let data = b"hello world";
        let nonce = 12345;
        let expected_hash = [
            166, 65, 125, 254, 189, 250, 254, 9, 146, 145, 86, 129, 163, 210, 160, 17, 234, 234,
            87, 92, 214, 37, 91, 204, 146, 93, 65, 135, 191, 41, 107, 117, 29, 81, 124, 53, 202,
            89, 149, 159, 8, 113, 241, 163, 84, 231, 16, 32, 237, 17, 9, 182, 201, 68, 83, 241, 39,
            23, 106, 152, 58, 110, 134, 144,
        ];
        let hash = PoWAlgorithm::calculate_sha2_512(data, nonce);

        assert_eq!(hash, expected_hash);
    }

    #[test]
    fn test_pow_algorithm_ripemd_320() {
        let data = b"hello world";
        let nonce = 12345;
        let expected_hash = [
            136, 243, 131, 91, 134, 239, 75, 101, 140, 4, 66, 6, 143, 87, 176, 118, 94, 92, 142,
            211, 74, 63, 182, 20, 119, 221, 125, 126, 20, 227, 45, 10, 34, 110, 210, 133, 131, 44,
            45, 23,
        ];

        let hash = PoWAlgorithm::calculate_ripemd_320(data, nonce);

        assert_eq!(hash, expected_hash);
    }

    #[test]
    fn test_pow_algorithm_dispatch_ripemd_320() {
        let data = b"hello world";
        let nonce = 12345;
        let via_dispatch = PoWAlgorithm::RIPEMD_320.calculate(data, nonce);
        let direct = PoWAlgorithm::calculate_ripemd_320(data, nonce);
        assert_eq!(via_dispatch, direct);
    }

    #[test]
    fn test_pow_algorithm_scrypt() {
        let data = b"hello world";
        let nonce = 12345;
        let params = ScryptParams::new(8, 4, 1, 32).unwrap();
        let expected_hash = [
            214, 100, 105, 187, 137, 13, 176, 155, 184, 158, 6, 229, 136, 55, 197, 78, 159, 216,
            153, 53, 214, 163, 145, 214, 252, 84, 4, 185, 92, 91, 111, 234,
        ];

        let hash = PoWAlgorithm::calculate_scrypt(data, nonce, &params);

        assert_eq!(hash, expected_hash);
    }

    #[test]
    fn test_pow_algorithm_argon2id() {
        let data = b"hello world";
        let nonce = 12345;
        let params = Argon2Params::new(16, 2, 2, None).unwrap();
        let expected_hash = [
            243, 150, 29, 238, 126, 244, 47, 122, 69, 22, 69, 20, 102, 5, 218, 124, 251, 140, 204,
            53, 133, 2, 147, 207, 66, 17, 241, 177, 20, 249, 251, 155,
        ];

        let hash = PoWAlgorithm::calculate_argon2id(data, nonce, &params);

        assert_eq!(hash, expected_hash);
    }
    #[test]
    fn test_pow_calculate_pow() {
        let data = "hello world";
        let difficulty = 2;
        let target = "00".as_bytes();
        let algorithm = PoWAlgorithm::Sha2_512;
        let pow = PoW::new(data, difficulty, algorithm).unwrap();

        let (hash, nonce) = pow.calculate_pow(&target);

        assert!(hash.starts_with(&target[..difficulty]));

        assert!(pow.verify_pow(&target, (hash.clone(), nonce)));
    }

    #[test]
    fn test_pow_calculate_pow_leading_zero_bits() {
        // Use fast hash to keep test time acceptable.
        let data = "hello world";
        let bits = 8; // ~256 expected tries
        let algorithm = PoWAlgorithm::Sha2_256;
        let pow = PoW::with_mode(data, bits, algorithm, DifficultyMode::LeadingZeroBits).unwrap();

        // target is ignored for bits mode; pass empty slice for clarity.
        let (hash, nonce) = pow.calculate_pow(&[]);
        assert!(meets_leading_zero_bits(&hash, bits as u32));
        assert!(pow.verify_pow(&[], (hash, nonce)));
    }

    // -------- Leading‑zero‑bits helper tests --------
    #[test]
    fn test_meets_leading_zero_bits_basic() {
        // 0x00 0x00 0xFF -> first 16 bits are 0; the 17th bit is 1
        let h = [0x00u8, 0x00u8, 0xFFu8];
        assert!(meets_leading_zero_bits(&h, 0));
        assert!(meets_leading_zero_bits(&h, 1));
        assert!(meets_leading_zero_bits(&h, 7));
        assert!(meets_leading_zero_bits(&h, 8));
        assert!(meets_leading_zero_bits(&h, 9));
        assert!(meets_leading_zero_bits(&h, 15));
        assert!(meets_leading_zero_bits(&h, 16));
        assert!(!meets_leading_zero_bits(&h, 17));
    }

    #[test]
    fn test_meets_leading_zero_bits_edges() {
        // MSB is 1: 0x80 -> 1000_0000
        let h1 = [0x80u8, 0x00u8];
        assert!(!meets_leading_zero_bits(&h1, 1));

        // 0x7F -> 0111_1111, has only 1 leading zero bit
        let h2 = [0x7Fu8, 0xFFu8];
        assert!(meets_leading_zero_bits(&h2, 1));
        assert!(!meets_leading_zero_bits(&h2, 2));

        // 0x00 0x80: first 8 bits are zero; the 9th is 1
        let h3 = [0x00u8, 0x80u8];
        assert!(meets_leading_zero_bits(&h3, 8));
        assert!(!meets_leading_zero_bits(&h3, 9));

        // Out of range: bits exceed available bit length
        let h4 = [0x00u8, 0x00u8, 0x00u8];
        assert!(meets_leading_zero_bits(&h4, 24));
        assert!(!meets_leading_zero_bits(&h4, 25));
    }

    // -------- Serde/Eq/Hash regression tests --------
    #[test]
    fn serde_roundtrip_powalgorithm_variants() {
        let a1 = PoWAlgorithm::Sha2_256;
        let s1 = to_string(&a1).unwrap();
        let b1: PoWAlgorithm = from_str(&s1).unwrap();
        assert_eq!(a1, b1);

        let a2 = PoWAlgorithm::Argon2id(Argon2Params::new(16, 2, 1, None).unwrap());
        let s2 = to_string(&a2).unwrap();
        let b2: PoWAlgorithm = from_str(&s2).unwrap();
        assert_eq!(a2, b2);

        let a3 = PoWAlgorithm::Scrypt(ScryptParams::new(8, 4, 1, 32).unwrap());
        let s3 = to_string(&a3).unwrap();
        let b3: PoWAlgorithm = from_str(&s3).unwrap();
        assert_eq!(a3, b3);

        let a4 = PoWAlgorithm::EquiX;
        let s4 = to_string(&a4).unwrap();
        let b4: PoWAlgorithm = from_str(&s4).unwrap();
        assert_eq!(a4, b4);
    }

    #[test]
    fn serde_roundtrip_pow() {
        let pow = PoW::with_mode(
            "data",
            12,
            PoWAlgorithm::Sha2_256,
            DifficultyMode::LeadingZeroBits,
        )
        .unwrap();
        let s = to_string(&pow).unwrap();
        let back: PoW = from_str(&s).unwrap();
        assert_eq!(pow, back);
    }

    #[test]
    fn hash_set_pow_and_algo() {
        let pow = PoW::new("hi", 2, PoWAlgorithm::Sha2_512).unwrap();
        let mut hs = HashSet::new();
        hs.insert(pow.clone());
        assert!(hs.contains(&pow));

        let algo = PoWAlgorithm::Argon2id(Argon2Params::new(32, 3, 2, None).unwrap());
        let mut hs2 = HashSet::new();
        hs2.insert(algo.clone());
        assert!(hs2.contains(&algo));
    }

    // -------- EquiX basic integration tests --------
    #[test]
    fn test_pow_algorithm_equix_calculate_deterministic() {
        let data = b"hello world";
        let nonce = 42usize;
        let h1 = PoWAlgorithm::calculate_equix(data, nonce);
        let h2 = PoWAlgorithm::calculate_equix(data, nonce);
        assert_eq!(h1, h2);
        assert_eq!(h1.len(), 32);
    }

    #[test]
    fn test_pow_equix_bits_zero_trivial() {
        // bits=0 should pass immediately at nonce=0 (verification also succeeds),
        // providing a fast regression without heavy computation.
        let data = "hello equix";
        let pow = PoW::with_mode(
            data,
            0,
            PoWAlgorithm::EquiX,
            DifficultyMode::LeadingZeroBits,
        )
        .unwrap();
        let (hash, nonce) = pow.calculate_pow(&[]);
        assert_eq!(nonce, 0);
        assert_eq!(hash.len(), 32);
        assert!(pow.verify_pow(&[], (hash, nonce)));
    }

    // -------- Proof-carrying EquiX tests (low-cost verification) --------
    #[test]
    fn test_equix_proof_roundtrip_bits0() {
        // Derive a seed once; in production you should domain-separate and include server_nonce+data.
        let mut seed_hasher = Sha256::new();
        seed_hasher.update(b"seed-for-test");
        let seed = seed_hasher.finalize();

        // Solve for bits=0 starting from work_nonce=0.
        let (proof, hash) = equix_solve_with_bits(&seed, 0, 0).expect("solve");
        // Verify returns the same hash and meets bits=0 trivially.
        let verified_hash = equix_verify_solution(&seed, &proof).expect("verify");
        assert_eq!(hash, verified_hash);
        assert!(equix_check_bits(&seed, &proof, 0).unwrap());
    }

    #[test]
    fn test_equix_verify_with_manual_solution() {
        // Build a challenge with small search window to find any solution.
        let mut seed_hasher = Sha256::new();
        seed_hasher.update(b"seed-for-test-2");
        let seed = seed_hasher.finalize();

        let mut found = None;
        for wn in 0u64..64 {
            let challenge = equix_challenge(&seed, wn);
            if let Ok(eq) = equix_crate::EquiX::new(&challenge) {
                let sols = eq.solve();
                if let Some(sol) = sols.iter().next() {
                    found = Some((wn, EquixSolution(sol.to_bytes())));
                    break;
                }
            }
        }
        let (work_nonce, solution) = found.expect("at least one solution in small window");
        let proof = EquixProof {
            work_nonce,
            solution,
        };

        let h = equix_verify_solution(&seed, &proof).expect("verify");
        assert_eq!(h.len(), 32);
        // bits=0 must pass; bits=1 may or may not pass — just check the trivial case.
        assert!(equix_check_bits(&seed, &proof, 0).unwrap());
    }

    #[test]
    fn test_equix_verify_rejects_tampered_solution() {
        let mut seed_hasher = Sha256::new();
        seed_hasher.update(b"seed-for-test-3");
        let seed = seed_hasher.finalize();

        // Find a valid proof (bits=0, trivial).
        let (mut proof, _h) = equix_solve_with_bits(&seed, 0, 0).expect("solve");
        // Tamper one byte in the solution; verify should fail.
        proof.solution.0[0] ^= 0x01;
        assert!(equix_verify_solution(&seed, &proof).is_err());
    }
}