ant-evm 0.1.21

EVM transfers for Autonomi
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
// Copyright 2025 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use std::collections::HashSet;

use super::merkle_tree::{BadMerkleProof, MerkleBranch, MidpointProof};
use crate::RewardsAddress;
use evmlib::merkle_batch_payment::{
    CandidateNode, CostUnitOverflow, PoolCommitment, PoolCommitmentPacked, PoolHash,
    calculate_total_cost_unit, encode_data_type_and_cost,
};
use evmlib::quoting_metrics::QuotingMetrics;
use libp2p::{
    PeerId,
    identity::{Keypair, PublicKey},
};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tiny_keccak::{Hasher, Sha3};
use xor_name::XorName;

pub use evmlib::merkle_batch_payment::CANDIDATES_PER_POOL;

/// Errors that can occur during Merkle payment verification
#[derive(Debug, Error)]
pub enum MerklePaymentVerificationError {
    #[error("Winner pool hash mismatch: expected {expected:?}, got {got:?}")]
    WinnerPoolHashMismatch { expected: PoolHash, got: PoolHash },
    #[error("Merkle proof verification failed: {0}")]
    MerkleProofFailed(#[from] BadMerkleProof),
    #[error(
        "Paid addresses not subset of candidate pool. Paid: {smart_contract_paid_node_addresses:?}, Candidates: {candidate_addresses:?}"
    )]
    PaidAddressesNotSubset {
        smart_contract_paid_node_addresses: Vec<RewardsAddress>,
        candidate_addresses: Vec<RewardsAddress>,
    },
    #[error("Wrong number of paid addresses: expected {expected}, got {got}")]
    WrongPaidAddressCount { expected: usize, got: usize },
    #[error("Invalid node signature for address {address}")]
    InvalidNodeSignature { address: RewardsAddress },
    #[error("Timestamp mismatch for node {address}: expected {expected}, got {got}")]
    TimestampMismatch {
        address: RewardsAddress,
        expected: u64,
        got: u64,
    },
    #[error("Pool commitment does not match the pool")]
    CommitmentDoesNotMatchPool,
    #[error("Paid node index {index} is out of bounds for pool size {pool_size}")]
    PaidNodeIndexOutOfBounds { index: usize, pool_size: usize },
    #[error("Address mismatch at index {index}: expected {expected}, got {actual}")]
    PaidAddressMismatch {
        index: usize,
        expected: RewardsAddress,
        actual: RewardsAddress,
    },
    #[error("Invalid node peer id for address {address} at index {index}")]
    InvalidNodePeerId {
        index: usize,
        address: RewardsAddress,
    },
    #[error("Data type mismatch: expected {expected}, got {got} at node {address}")]
    DataTypeMismatch {
        address: RewardsAddress,
        expected: u32,
        got: u32,
    },
    #[error("Data size mismatch: expected {expected}, got {got} at node {address}")]
    DataSizeMismatch {
        address: RewardsAddress,
        expected: usize,
        got: usize,
    },
    #[error(
        "Cost unit mismatch at candidate index {index}: on-chain packed={on_chain_packed}, expected packed={expected_packed}"
    )]
    CostUnitMismatch {
        index: usize,
        on_chain_packed: String,
        expected_packed: String,
    },
    #[error("Winner pool hash not found in on-chain packed commitments")]
    WinnerPoolNotInCommitments,
    #[error("Cost unit overflow during packing: {0}")]
    CostUnitOverflow(#[from] CostUnitOverflow),
}

/// A node's signed quote for potential reward eligibility
///
/// Nodes create this structure in response to a client's quote request. The client provides
/// a `merkle_payment_timestamp`, which nodes verify is not outdated (not in the future or expired).
/// Nodes then sign their quoting metrics and payment address with this timestamp, establishing
/// their candidacy to be selected for payment rewards. The client collects these from multiple
/// nodes to build a [`MerklePaymentCandidatePool`].
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct MerklePaymentCandidateNode {
    /// Node's libp2p public key
    /// PeerId can be derived from this: PeerId::from(PublicKey::try_decode_protobuf(pub_key))
    pub pub_key: Vec<u8>,

    /// Node's storage metrics at quote time
    pub quoting_metrics: QuotingMetrics,

    /// Node's Ethereum address for payment
    pub reward_address: RewardsAddress,

    /// Quote timestamp (provided by the client)
    pub merkle_payment_timestamp: u64,

    /// Signature over hash(quoting_metrics || reward_address || timestamp)
    pub signature: Vec<u8>,
}

impl MerklePaymentCandidateNode {
    /// Create a new candidate node with signed commitment
    ///
    /// # Arguments
    /// * `keypair` - Node's libp2p keypair for signing
    /// * `quoting_metrics` - Node's storage metrics at quote time
    /// * `reward_address` - Node's Ethereum address for payment
    /// * `timestamp` - Quote timestamp
    ///
    /// # Returns
    /// * `Result<Self, MerklePaymentError>` - Signed candidate node or signing error
    pub fn new(
        keypair: &Keypair,
        quoting_metrics: QuotingMetrics,
        reward_address: RewardsAddress,
        merkle_payment_timestamp: u64,
    ) -> Result<Self, libp2p::identity::SigningError> {
        // Extract public key in protobuf format
        let pub_key = keypair.public().encode_protobuf();

        // Sign the content
        let msg = Self::bytes_to_sign(&quoting_metrics, &reward_address, merkle_payment_timestamp);
        let signature = keypair.sign(&msg)?;

        Ok(Self {
            pub_key,
            quoting_metrics,
            reward_address,
            merkle_payment_timestamp,
            signature,
        })
    }

    /// Get the bytes to sign
    pub fn bytes_to_sign(
        quoting_metrics: &QuotingMetrics,
        reward_address: &RewardsAddress,
        timestamp: u64,
    ) -> Vec<u8> {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&quoting_metrics.to_bytes());
        bytes.extend_from_slice(reward_address.as_slice());
        bytes.extend_from_slice(&timestamp.to_le_bytes());
        bytes
    }

    /// Convert to deterministic byte representation for hashing
    fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&self.pub_key);
        bytes.extend_from_slice(&self.quoting_metrics.to_bytes());
        bytes.extend_from_slice(self.reward_address.as_slice());
        bytes.extend_from_slice(&self.merkle_payment_timestamp.to_le_bytes());
        bytes.extend_from_slice(&self.signature);
        bytes
    }

    /// Derive PeerId from public key
    pub fn peer_id(&self) -> Result<PeerId, libp2p::identity::DecodingError> {
        PublicKey::try_decode_protobuf(&self.pub_key).map(|pk| pk.to_peer_id())
    }

    /// Verify signature is valid for this node
    pub fn verify_signature(&self) -> bool {
        let pub_key = match PublicKey::try_decode_protobuf(&self.pub_key) {
            Ok(pk) => pk,
            Err(_) => return false,
        };

        let msg = Self::bytes_to_sign(
            &self.quoting_metrics,
            &self.reward_address,
            self.merkle_payment_timestamp,
        );
        pub_key.verify(&msg, &self.signature)
    }
}

/// One candidate pool: midpoint proof + nodes who could store addresses
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct MerklePaymentCandidatePool {
    /// The midpoint proof from ant-evm's merkle_tree module
    pub midpoint_proof: MidpointProof,

    /// Candidate nodes for this pool
    /// Provides redundancy - only 'depth' of these will be selected as winners
    pub candidate_nodes: [MerklePaymentCandidateNode; CANDIDATES_PER_POOL],
}

/// Compute SHA3-256 hash of input bytes
pub(crate) fn sha3_256(input: &[u8]) -> [u8; 32] {
    let mut sha3 = Sha3::v256();
    let mut output = [0u8; 32];
    sha3.update(input);
    sha3.finalize(&mut output);
    output
}

impl MerklePaymentCandidatePool {
    /// Compute deterministic hash for on-chain storage key
    pub fn hash(&self) -> PoolHash {
        let mut bytes = Vec::new();

        // Hash of the intersection proof
        bytes.extend_from_slice(&self.midpoint_proof.hash());

        // Number of candidate nodes
        bytes.extend_from_slice(&(self.candidate_nodes.len() as u32).to_le_bytes());

        // Each candidate node's data
        for node in &self.candidate_nodes {
            bytes.extend_from_slice(&node.to_bytes());
        }

        sha3_256(&bytes)
    }

    /// Convert to minimal commitment for smart contract submission
    pub fn to_commitment(&self) -> PoolCommitment {
        let candidates: [CandidateNode; CANDIDATES_PER_POOL] =
            self.candidate_nodes.clone().map(|node| CandidateNode {
                rewards_address: node.reward_address,
                metrics: node.quoting_metrics.clone(),
            });

        PoolCommitment {
            pool_hash: self.hash(),
            candidates,
        }
    }

    /// Convert to packed commitment for compact calldata (v2)
    ///
    /// This produces a smaller on-chain representation by packing
    /// data type and total cost unit into a single U256.
    pub fn to_commitment_packed(&self) -> Result<PoolCommitmentPacked, CostUnitOverflow> {
        self.to_commitment().to_packed()
    }

    /// Verify that on-chain cost units match what the signed metrics produce
    ///
    /// This takes the packed commitments decoded from the payment transaction calldata
    /// and verifies that the winner pool's candidates have cost units consistent with
    /// their signed quoting metrics. This prevents clients from sending lower cost units
    /// to the contract than what the nodes' metrics would produce.
    ///
    /// # Arguments
    /// * `on_chain_commitments` - All packed commitments decoded from the tx calldata
    /// * `winner_pool_hash` - The winner pool hash to find in the commitments
    pub fn verify_cost_units(
        &self,
        on_chain_commitments: &[PoolCommitmentPacked],
        winner_pool_hash: &PoolHash,
    ) -> Result<(), MerklePaymentVerificationError> {
        // Find the winner pool in the on-chain commitments
        let on_chain_winner = on_chain_commitments
            .iter()
            .find(|pc| pc.pool_hash == *winner_pool_hash)
            .ok_or(MerklePaymentVerificationError::WinnerPoolNotInCommitments)?;

        // For each candidate, verify the on-chain packed value matches what signed metrics produce
        for (i, (on_chain_candidate, signed_node)) in on_chain_winner
            .candidates
            .iter()
            .zip(self.candidate_nodes.iter())
            .enumerate()
        {
            // Compute expected packed value from signed metrics
            let expected_data_type =
                evmlib::contract::data_type_conversion(signed_node.quoting_metrics.data_type);
            let expected_cost_unit = calculate_total_cost_unit(&signed_node.quoting_metrics);
            let expected_packed =
                encode_data_type_and_cost(expected_data_type, expected_cost_unit)?;

            if on_chain_candidate.data_type_and_total_cost_unit != expected_packed {
                return Err(MerklePaymentVerificationError::CostUnitMismatch {
                    index: i,
                    on_chain_packed: on_chain_candidate.data_type_and_total_cost_unit.to_string(),
                    expected_packed: expected_packed.to_string(),
                });
            }
        }

        Ok(())
    }

    /// Helper function for PoolCommitment verification
    ///
    /// This verifies that a commitment matches a pool and that the pool signatures are valid.
    pub fn verify_commitment(
        &self,
        commitment: &PoolCommitment,
        merkle_payment_timestamp: u64,
    ) -> Result<(), MerklePaymentVerificationError> {
        self.verify_signatures(merkle_payment_timestamp)?;
        let expected_commitment = self.to_commitment();
        if commitment != &expected_commitment {
            return Err(MerklePaymentVerificationError::CommitmentDoesNotMatchPool);
        }
        Ok(())
    }

    /// Get the addresses of the candidate nodes
    pub fn candidate_nodes_addresses(&self) -> HashSet<RewardsAddress> {
        self.candidate_nodes
            .iter()
            .map(|node| node.reward_address)
            .collect()
    }

    /// Verify that the signatures in the candidate pool are valid
    ///
    /// Checks:
    /// 1. All node signatures are valid
    /// 2. All timestamps match the merkle payment timestamp
    /// 3. All nodes quote the same data_type and data_size
    ///
    /// It does not verify the pool branch proof.
    pub fn verify_signatures(
        &self,
        merkle_payment_timestamp: u64,
    ) -> Result<(), MerklePaymentVerificationError> {
        // Verify all node signatures
        for node in &self.candidate_nodes {
            if !node.verify_signature() {
                return Err(MerklePaymentVerificationError::InvalidNodeSignature {
                    address: node.reward_address,
                });
            }
        }

        // Verify all timestamps match the merkle payment timestamp
        for node in &self.candidate_nodes {
            if node.merkle_payment_timestamp != merkle_payment_timestamp {
                return Err(MerklePaymentVerificationError::TimestampMismatch {
                    address: node.reward_address,
                    expected: merkle_payment_timestamp,
                    got: node.merkle_payment_timestamp,
                });
            }
        }

        // Verify all nodes are quoting for the same data_type and data_size
        // All nodes in a pool should be providing quotes for the same data
        if let Some(first_node) = self.candidate_nodes.first() {
            let expected_data_type = first_node.quoting_metrics.data_type;
            let expected_data_size = first_node.quoting_metrics.data_size;

            for node in &self.candidate_nodes[..] {
                if node.quoting_metrics.data_type != expected_data_type {
                    return Err(MerklePaymentVerificationError::DataTypeMismatch {
                        address: node.reward_address,
                        expected: expected_data_type,
                        got: node.quoting_metrics.data_type,
                    });
                }

                if node.quoting_metrics.data_size != expected_data_size {
                    return Err(MerklePaymentVerificationError::DataSizeMismatch {
                        address: node.reward_address,
                        expected: expected_data_size,
                        got: node.quoting_metrics.data_size,
                    });
                }
            }
        }

        Ok(())
    }
}

/// Data package sent from client to node for data storage and payment verification
///
/// Contains everything a node needs to verify:
/// 1. The data belongs to a paid Merkle tree (via proof)
/// 2. Payment was made to the correct pool (via winner pool proof and smart contract query)
/// 3. The node is eligible to store this data (if they're in the winner pool)
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct MerklePaymentProof {
    /// The data's XorName
    pub address: XorName,

    /// Merkle proof that this data belongs to the paid tree
    pub data_proof: MerkleBranch,

    /// The winner pool selected by the smart contract
    /// Contains the full candidate pool with signatures and intersection proof
    pub winner_pool: MerklePaymentCandidatePool,
}

impl MerklePaymentProof {
    /// Create a new Merkle payment proof
    pub fn new(
        address: XorName,
        data_proof: MerkleBranch,
        winner_pool: MerklePaymentCandidatePool,
    ) -> Self {
        Self {
            address,
            data_proof,
            winner_pool,
        }
    }

    /// Get the hash of the winner pool (used to query smart contract for payment info)
    pub fn winner_pool_hash(&self) -> PoolHash {
        self.winner_pool.hash()
    }

    /// Get the corresponding peer ids for the paid nodes using their indices in the winner pool
    ///
    /// This uses the indices from the smart contract to identify exactly which nodes were paid.
    /// This is necessary because multiple nodes can share the same reward address.
    ///
    /// # Arguments
    /// * `paid_nodes` - The (address, index) pairs from the smart contract
    ///
    /// # Returns
    /// * `Ok(Vec<PeerId>)` - PeerIds of the paid nodes, in the same order as the input
    /// * `Err(PaidNodeIndexOutOfBounds)` - If any index is out of bounds
    /// * `Err(InvalidNodePeerId)` - If any paid node has an invalid public key
    /// * `Err(PaidAddressMismatch)` - If address at index doesn't match expected address
    pub fn corresponding_peer_ids(
        &self,
        paid_nodes: &[(RewardsAddress, usize)],
    ) -> Result<Vec<PeerId>, MerklePaymentVerificationError> {
        let mut peer_ids = Vec::with_capacity(paid_nodes.len());

        for (expected_address, index) in paid_nodes {
            let node = self.winner_pool.candidate_nodes.get(*index).ok_or(
                MerklePaymentVerificationError::PaidNodeIndexOutOfBounds {
                    index: *index,
                    pool_size: self.winner_pool.candidate_nodes.len(),
                },
            )?;

            // Verify the address at this index matches what the smart contract says
            if node.reward_address != *expected_address {
                return Err(MerklePaymentVerificationError::PaidAddressMismatch {
                    index: *index,
                    expected: *expected_address,
                    actual: node.reward_address,
                });
            }

            // Derive the PeerId from the node's public key
            let peer_id =
                node.peer_id()
                    .map_err(|_| MerklePaymentVerificationError::InvalidNodePeerId {
                        address: node.reward_address,
                        index: *index,
                    })?;

            peer_ids.push(peer_id);
        }

        Ok(peer_ids)
    }

    /// Verify the payment proof against the smart contract payment info
    ///
    /// # Arguments
    /// * `smart_contract_depth` - The depth value stored in the smart contract
    /// * `smart_contract_timestamp` - The merkle payment timestamp stored in the smart contract
    /// * `smart_contract_pool_hash` - The hash of the winner pool stored in the smart contract
    /// * `smart_contract_paid_nodes` - The (address, index) pairs of paid nodes from the smart contract
    pub fn verify(
        &self,
        smart_contract_depth: u8,
        smart_contract_timestamp: u64,
        smart_contract_pool_hash: &PoolHash,
        smart_contract_paid_nodes: &[(RewardsAddress, usize)],
    ) -> Result<(), MerklePaymentVerificationError> {
        // Verify the winner pool signatures and timestamps first
        self.winner_pool
            .verify_signatures(smart_contract_timestamp)?;

        // Verify the winner pool hash matches the smart contract pool hash
        let actual_hash = self.winner_pool.hash();
        if actual_hash != *smart_contract_pool_hash {
            return Err(MerklePaymentVerificationError::WinnerPoolHashMismatch {
                expected: *smart_contract_pool_hash,
                got: actual_hash,
            });
        }
        let smart_contract_root = self.winner_pool.midpoint_proof.root();

        // Verify the core Merkle proof using the tree-level verification
        crate::merkle_payments::verify_merkle_proof(
            &self.address,
            &self.data_proof,
            &self.winner_pool.midpoint_proof,
            smart_contract_depth,
            smart_contract_root,
            smart_contract_timestamp,
        )?;

        // Verify the correct number of nodes were paid (should equal depth)
        if smart_contract_paid_nodes.len() != smart_contract_depth as usize {
            return Err(MerklePaymentVerificationError::WrongPaidAddressCount {
                expected: smart_contract_depth as usize,
                got: smart_contract_paid_nodes.len(),
            });
        }

        // Verify all paid node (address, index) pairs are valid
        // This also verifies addresses match what's at those indices
        self.corresponding_peer_ids(smart_contract_paid_nodes)?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::merkle_payments::merkle_tree::MerkleTree;
    use evmlib::quoting_metrics::QuotingMetrics;
    use std::time::{SystemTime, UNIX_EPOCH};
    use tempfile::TempDir;

    fn make_test_addresses(count: usize) -> Vec<XorName> {
        (0..count)
            .map(|i| XorName::from_content(&i.to_le_bytes()))
            .collect()
    }

    fn create_mock_quoting_metrics(node_id: usize) -> QuotingMetrics {
        QuotingMetrics {
            data_type: 0,
            data_size: 4 * 1024 * 1024, // 4MB
            close_records_stored: node_id * 100,
            records_per_type: vec![],
            max_records: 1000,
            received_payment_count: node_id * 10,
            live_time: 3600 + (node_id as u64),
            network_density: Some([node_id as u8; 32]),
            network_size: Some(1000),
        }
    }

    /// Helper to create an array of CANDIDATES_PER_POOL test nodes with unique addresses
    fn create_test_candidate_nodes(
        timestamp: u64,
    ) -> [MerklePaymentCandidateNode; CANDIDATES_PER_POOL] {
        std::array::from_fn(|i| {
            let keypair = Keypair::generate_ed25519();
            MerklePaymentCandidateNode::new(
                &keypair,
                create_mock_quoting_metrics(i),
                RewardsAddress::from([i as u8; 20]),
                timestamp,
            )
            .expect("Failed to create candidate node")
        })
    }

    /// Helper to create an array of CANDIDATES_PER_POOL test nodes and return their PeerIds
    fn create_test_candidate_nodes_with_peer_ids(
        timestamp: u64,
    ) -> (
        [MerklePaymentCandidateNode; CANDIDATES_PER_POOL],
        Vec<PeerId>,
    ) {
        let mut peer_ids = Vec::with_capacity(CANDIDATES_PER_POOL);
        let nodes = std::array::from_fn(|i| {
            let keypair = Keypair::generate_ed25519();
            let peer_id = keypair.public().to_peer_id();
            let node = MerklePaymentCandidateNode::new(
                &keypair,
                create_mock_quoting_metrics(i),
                RewardsAddress::from([i as u8; 20]),
                timestamp,
            )
            .expect("Failed to create candidate node");
            peer_ids.push(peer_id);
            node
        });
        (nodes, peer_ids)
    }

    #[test]
    fn test_candidate_node_constructor_and_signature() {
        // Create a keypair for signing
        let keypair = Keypair::generate_ed25519();
        let peer_id = keypair.public().to_peer_id();

        // Create test data
        let quoting_metrics = create_mock_quoting_metrics(42);
        let reward_address = RewardsAddress::from([0x42; 20]);
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create candidate node using constructor
        let node = MerklePaymentCandidateNode::new(
            &keypair,
            quoting_metrics.clone(),
            reward_address,
            timestamp,
        )
        .expect("Failed to create candidate node");

        // Verify the peer_id matches
        assert_eq!(
            node.peer_id().expect("Failed to derive peer_id"),
            peer_id,
            "PeerId should match keypair"
        );

        // Verify the signature is valid
        assert!(
            node.verify_signature(),
            "Signature should be valid for the signed data"
        );

        // Verify all fields are correctly set
        assert_eq!(node.reward_address, reward_address);
        assert_eq!(node.merkle_payment_timestamp, timestamp);
        assert_eq!(
            node.quoting_metrics.close_records_stored,
            quoting_metrics.close_records_stored
        );
    }

    #[test]
    fn test_signature_verification_with_tampering() {
        // Create a valid signed node
        let keypair = Keypair::generate_ed25519();
        let quoting_metrics = create_mock_quoting_metrics(1);
        let reward_address = RewardsAddress::from([0x11; 20]);
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let mut node = MerklePaymentCandidateNode::new(
            &keypair,
            quoting_metrics.clone(),
            reward_address,
            timestamp,
        )
        .expect("Failed to create candidate node");

        // Valid signature should verify
        assert!(
            node.verify_signature(),
            "Original signature should be valid"
        );

        // Tamper with reward address - signature should now fail
        node.reward_address = RewardsAddress::from([0x22; 20]);
        assert!(
            !node.verify_signature(),
            "Signature should fail after tampering with reward_address"
        );

        // Restore and tamper with quoting metrics
        node.reward_address = reward_address;
        node.quoting_metrics.close_records_stored = 999;
        assert!(
            !node.verify_signature(),
            "Signature should fail after tampering with quoting_metrics"
        );

        // Restore and tamper with timestamp (use a clearly different time)
        node.quoting_metrics = quoting_metrics;
        node.merkle_payment_timestamp = timestamp + 3600; // 1 hour later
        assert!(
            !node.verify_signature(),
            "Signature should fail after tampering with timestamp"
        );

        // Test with wrong keypair's signature
        let wrong_keypair = Keypair::generate_ed25519();
        let wrong_node = MerklePaymentCandidateNode::new(
            &wrong_keypair,
            create_mock_quoting_metrics(2),
            RewardsAddress::from([0x33; 20]),
            timestamp,
        )
        .expect("Failed to create node with wrong keypair");

        // Swap signatures between nodes
        let original_signature = node.signature.clone();
        node.signature = wrong_node.signature.clone();
        assert!(
            !node.verify_signature(),
            "Signature from different keypair should fail"
        );

        // Verify original signature still works when restored
        node.signature = original_signature;
        node.reward_address = reward_address;
        node.merkle_payment_timestamp = timestamp;
        assert!(
            node.verify_signature(),
            "Original signature should work after restoration"
        );
    }

    #[test]
    fn test_pool_commitment_verification() {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create a simple merkle tree
        let addresses = make_test_addresses(10);
        let tree = MerkleTree::from_xornames(addresses).unwrap();

        // Get a reward candidate pool
        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
        let reward_pool = &reward_candidates[0];

        // Create candidate nodes array directly
        let candidate_nodes = create_test_candidate_nodes(timestamp);

        let pool = MerklePaymentCandidatePool {
            midpoint_proof: reward_pool.clone(),
            candidate_nodes,
        };

        // Create commitment from pool
        let commitment = pool.to_commitment();

        // Verify commitment matches pool
        assert!(
            pool.verify_commitment(&commitment, timestamp).is_ok(),
            "Commitment should verify against original pool"
        );

        // Test 1: Verify pool_hash is correct
        assert_eq!(
            commitment.pool_hash,
            pool.hash(),
            "Commitment pool_hash should match pool.hash()"
        );

        // Test 2: Verify candidates match
        let expected_candidates: [CandidateNode; CANDIDATES_PER_POOL] =
            pool.candidate_nodes.clone().map(|node| CandidateNode {
                rewards_address: node.reward_address,
                metrics: node.quoting_metrics.clone(),
            });
        assert_eq!(
            commitment.candidates, expected_candidates,
            "Commitment candidates should match pool nodes"
        );
        assert_eq!(
            commitment.candidates.len(),
            CANDIDATES_PER_POOL,
            "Should have exactly {CANDIDATES_PER_POOL} candidates",
        );

        // Test 3: Tamper with pool - verification should fail
        let mut tampered_pool = pool.clone();
        tampered_pool.candidate_nodes[0].reward_address = RewardsAddress::from([0xFF; 20]);
        assert!(
            tampered_pool
                .verify_commitment(&commitment, timestamp)
                .is_err(),
            "Commitment should not verify against tampered pool"
        );

        // Test 4: Create commitment from tampered pool and verify it doesn't match original commitment
        let tampered_commitment = tampered_pool.to_commitment();
        assert_ne!(
            commitment.pool_hash, tampered_commitment.pool_hash,
            "Tampered pool should have different hash"
        );
        assert_ne!(
            commitment.candidates[0].rewards_address,
            tampered_commitment.candidates[0].rewards_address,
            "Tampered pool should have different addresses"
        );

        // Test 5: Verify determinism - same pool generates same commitment
        let commitment2 = pool.to_commitment();
        assert_eq!(
            commitment.pool_hash, commitment2.pool_hash,
            "Same pool should generate same commitment hash"
        );
        assert_eq!(
            commitment.candidates, commitment2.candidates,
            "Same pool should generate same candidates"
        );
    }

    #[test]
    fn test_pool_verify_method() {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create a valid pool with properly signed nodes
        let addresses = make_test_addresses(10);
        let tree = MerkleTree::from_xornames(addresses).unwrap();
        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
        let reward_pool = &reward_candidates[0];

        // Create candidate nodes array directly
        let candidate_nodes = create_test_candidate_nodes(timestamp);

        let pool = MerklePaymentCandidatePool {
            midpoint_proof: reward_pool.clone(),
            candidate_nodes,
        };

        // Test 1: Valid pool should verify
        assert!(
            pool.verify_signatures(timestamp).is_ok(),
            "Valid pool should verify successfully"
        );

        // Test 2: Pool with invalid signature should fail
        let mut invalid_sig_pool = pool.clone();
        invalid_sig_pool.candidate_nodes[0].signature = vec![0xFF; 64]; // Corrupt signature
        assert!(
            invalid_sig_pool.verify_signatures(timestamp).is_err(),
            "Pool with invalid signature should fail verification"
        );

        // Test 3: Pool with tampered node data should fail
        let mut tampered_pool = pool.clone();
        tampered_pool.candidate_nodes[0].reward_address = RewardsAddress::from([0xFF; 20]);
        assert!(
            tampered_pool.verify_signatures(timestamp).is_err(),
            "Pool with tampered node data should fail verification (signature mismatch)"
        );
    }

    #[test]
    fn test_pool_verify_timestamp_consistency() {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create a valid pool
        let addresses = make_test_addresses(10);
        let tree = MerkleTree::from_xornames(addresses).unwrap();
        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
        let reward_pool = &reward_candidates[0];

        // Create candidate nodes array directly
        let candidate_nodes = create_test_candidate_nodes(timestamp);

        let pool = MerklePaymentCandidatePool {
            midpoint_proof: reward_pool.clone(),
            candidate_nodes,
        };

        // Valid pool with identical timestamps should verify
        assert!(
            pool.verify_signatures(timestamp).is_ok(),
            "Pool with identical timestamps should verify"
        );

        // Create pool with mismatched timestamps
        let mut mismatched_pool = pool.clone();
        let different_keypair = Keypair::generate_ed25519();
        let different_timestamp = timestamp + 3600; // 1 hour later
        mismatched_pool.candidate_nodes[5] = MerklePaymentCandidateNode::new(
            &different_keypair,
            create_mock_quoting_metrics(5),
            RewardsAddress::from([5u8; 20]),
            different_timestamp,
        )
        .expect("Failed to create node with different timestamp");

        assert!(
            mismatched_pool.verify_signatures(timestamp).is_err(),
            "Pool with mismatched timestamps should fail verification"
        );
    }

    #[test]
    fn test_invalid_public_key_error() {
        // Create a node with invalid pub_key
        let keypair = Keypair::generate_ed25519();
        let mut node = MerklePaymentCandidateNode::new(
            &keypair,
            create_mock_quoting_metrics(1),
            RewardsAddress::from([0x11; 20]),
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs(),
        )
        .expect("Failed to create candidate node");

        // Corrupt pub_key with invalid data
        node.pub_key = vec![0xFF; 10]; // Too short and invalid format

        // Should fail to derive peer_id
        assert!(
            node.peer_id().is_err(),
            "Should fail to derive peer_id from invalid pub_key"
        );

        // Signature verification should also fail
        assert!(
            !node.verify_signature(),
            "Signature verification should fail with invalid pub_key"
        );
    }

    #[test]
    fn test_node_hash_determinism() {
        let keypair = Keypair::generate_ed25519();
        let quoting_metrics = create_mock_quoting_metrics(42);
        let reward_address = RewardsAddress::from([0x42; 20]);
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create two identical nodes
        let node1 = MerklePaymentCandidateNode::new(
            &keypair,
            quoting_metrics.clone(),
            reward_address,
            timestamp,
        )
        .expect("Failed to create first node");

        let node2 =
            MerklePaymentCandidateNode::new(&keypair, quoting_metrics, reward_address, timestamp)
                .expect("Failed to create second node");

        // to_bytes() should be deterministic
        assert_eq!(
            node1.to_bytes(),
            node2.to_bytes(),
            "Same inputs should produce same byte representation"
        );

        // Hashes of pools containing these nodes should be deterministic
        let addresses = make_test_addresses(10);
        let tree = MerkleTree::from_xornames(addresses).unwrap();
        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
        let reward_pool = &reward_candidates[0];

        let pool1 = MerklePaymentCandidatePool {
            midpoint_proof: reward_pool.clone(),
            candidate_nodes: std::array::from_fn(|_| node1.clone()),
        };

        let pool2 = MerklePaymentCandidatePool {
            midpoint_proof: reward_pool.clone(),
            candidate_nodes: std::array::from_fn(|_| node2.clone()),
        };

        assert_eq!(
            pool1.hash(),
            pool2.hash(),
            "Identical pools should produce identical hashes"
        );
    }

    #[test]
    fn test_corresponding_peer_ids_happy_path() {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create a merkle tree and get a reward pool
        let addresses = make_test_addresses(10);
        let tree = MerkleTree::from_xornames(addresses.clone()).unwrap();
        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
        let reward_pool = &reward_candidates[0];

        // Create candidate nodes array and track their PeerIds
        let (candidate_nodes, peer_ids) = create_test_candidate_nodes_with_peer_ids(timestamp);
        let expected_peer_ids: Vec<_> = peer_ids
            .iter()
            .enumerate()
            .map(|(i, pid)| (RewardsAddress::from([i as u8; 20]), *pid))
            .collect();

        let proof = MerklePaymentProof::new(
            addresses[0],
            tree.generate_address_proof(0, addresses[0]).unwrap(),
            MerklePaymentCandidatePool {
                midpoint_proof: reward_pool.clone(),
                candidate_nodes,
            },
        );

        // Test: Get PeerIds using (address, index) pairs
        let paid_nodes = vec![
            (RewardsAddress::from([0; 20]), 0),
            (RewardsAddress::from([1; 20]), 1),
            (RewardsAddress::from([2; 20]), 2),
        ];

        let result = proof.corresponding_peer_ids(&paid_nodes);
        assert!(
            result.is_ok(),
            "Should succeed when indices and addresses match"
        );

        let peer_ids = result.unwrap();
        assert_eq!(peer_ids.len(), 3, "Should return 3 PeerIds");

        // Verify returned PeerIds match expected (in order)
        for (i, (_addr, expected_peer_id)) in expected_peer_ids.iter().take(3).enumerate() {
            assert_eq!(
                peer_ids[i], *expected_peer_id,
                "Should return PeerId at index {i} in correct order"
            );
        }
    }

    #[test]
    fn test_corresponding_peer_ids_index_out_of_bounds() {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create a merkle tree and get a reward pool
        let addresses = make_test_addresses(10);
        let tree = MerkleTree::from_xornames(addresses.clone()).unwrap();
        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
        let reward_pool = &reward_candidates[0];

        // Create candidate nodes array directly
        let candidate_nodes = create_test_candidate_nodes(timestamp);

        let proof = MerklePaymentProof::new(
            addresses[0],
            tree.generate_address_proof(0, addresses[0]).unwrap(),
            MerklePaymentCandidatePool {
                midpoint_proof: reward_pool.clone(),
                candidate_nodes,
            },
        );

        // Test: Index out of bounds (attack scenario)
        let paid_nodes = vec![
            (RewardsAddress::from([0; 20]), 0),   // valid
            (RewardsAddress::from([99; 20]), 99), // index 99 is out of bounds!
        ];

        let result = proof.corresponding_peer_ids(&paid_nodes);
        assert!(result.is_err(), "Should fail when index is out of bounds");

        match result {
            Err(MerklePaymentVerificationError::PaidNodeIndexOutOfBounds { index, pool_size }) => {
                assert_eq!(index, 99);
                assert_eq!(pool_size, CANDIDATES_PER_POOL);
            }
            _ => panic!("Expected PaidNodeIndexOutOfBounds error"),
        }
    }

    #[test]
    fn test_corresponding_peer_ids_address_mismatch() {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create a merkle tree and get a reward pool
        let addresses = make_test_addresses(10);
        let tree = MerkleTree::from_xornames(addresses.clone()).unwrap();
        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
        let reward_pool = &reward_candidates[0];

        // Create candidate nodes array directly
        let candidate_nodes = create_test_candidate_nodes(timestamp);

        let proof = MerklePaymentProof::new(
            addresses[0],
            tree.generate_address_proof(0, addresses[0]).unwrap(),
            MerklePaymentCandidatePool {
                midpoint_proof: reward_pool.clone(),
                candidate_nodes,
            },
        );

        // Test: Address doesn't match what's at the index (attack scenario)
        let paid_nodes = vec![
            (RewardsAddress::from([99; 20]), 0), // index 0 has address [0;20], not [99;20]!
        ];

        let result = proof.corresponding_peer_ids(&paid_nodes);
        assert!(
            result.is_err(),
            "Should fail when address doesn't match index"
        );

        match result {
            Err(MerklePaymentVerificationError::PaidAddressMismatch {
                index,
                expected,
                actual,
            }) => {
                assert_eq!(index, 0);
                assert_eq!(expected, RewardsAddress::from([99; 20]));
                assert_eq!(actual, RewardsAddress::from([0; 20]));
            }
            _ => panic!("Expected PaidAddressMismatch error"),
        }
    }

    #[test]
    fn test_corresponding_peer_ids_multiple_nodes_same_address() {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create a merkle tree and get a reward pool
        let addresses = make_test_addresses(10);
        let tree = MerkleTree::from_xornames(addresses.clone()).unwrap();
        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
        let reward_pool = &reward_candidates[0];

        // Create candidate nodes where MULTIPLE nodes share the SAME reward address
        let shared_address = RewardsAddress::from([42; 20]);
        let mut candidate_nodes = Vec::new();
        let mut peer_ids_for_shared_address = Vec::new();

        // First 3 nodes share the same address
        for i in 0..3 {
            let keypair = Keypair::generate_ed25519();
            let peer_id = keypair.public().to_peer_id();
            let node = MerklePaymentCandidateNode::new(
                &keypair,
                create_mock_quoting_metrics(i),
                shared_address, // Same address!
                timestamp,
            )
            .expect("Failed to create candidate node");
            candidate_nodes.push(node);
            peer_ids_for_shared_address.push(peer_id);
        }

        // Remaining nodes have unique addresses
        for i in 3..CANDIDATES_PER_POOL {
            let keypair = Keypair::generate_ed25519();
            let node = MerklePaymentCandidateNode::new(
                &keypair,
                create_mock_quoting_metrics(i),
                RewardsAddress::from([i as u8; 20]),
                timestamp,
            )
            .expect("Failed to create candidate node");
            candidate_nodes.push(node);
        }

        let proof = MerklePaymentProof::new(
            addresses[0],
            tree.generate_address_proof(0, addresses[0]).unwrap(),
            MerklePaymentCandidatePool {
                midpoint_proof: reward_pool.clone(),
                candidate_nodes: candidate_nodes
                    .try_into()
                    .expect("Should have exactly CANDIDATES_PER_POOL nodes"),
            },
        );

        // Test: When nodes at specific indices are paid (even with shared address),
        // we can distinguish them by index
        let paid_nodes = vec![
            (shared_address, 0), // First node with shared address
            (shared_address, 1), // Second node with shared address
        ];

        let result = proof.corresponding_peer_ids(&paid_nodes);
        assert!(
            result.is_ok(),
            "Should succeed when indices and addresses match"
        );

        let peer_ids = result.unwrap();
        assert_eq!(
            peer_ids.len(),
            2,
            "Should return exactly 2 PeerIds for the 2 paid indices"
        );

        // Verify the specific PeerIds at indices 0 and 1 are returned (in order)
        assert_eq!(peer_ids[0], peer_ids_for_shared_address[0]);
        assert_eq!(peer_ids[1], peer_ids_for_shared_address[1]);

        // Test: Paying index 2 (third node with same address)
        let paid_nodes = vec![(shared_address, 2)];
        let result = proof.corresponding_peer_ids(&paid_nodes);
        assert!(result.is_ok());
        let peer_ids = result.unwrap();
        assert_eq!(peer_ids[0], peer_ids_for_shared_address[2]);
    }

    #[test]
    fn test_corresponding_peer_ids_invalid_public_key() {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create a merkle tree and get a reward pool
        let addresses = make_test_addresses(10);
        let tree = MerkleTree::from_xornames(addresses.clone()).unwrap();
        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
        let reward_pool = &reward_candidates[0];

        // Create candidate nodes
        let mut candidate_nodes = Vec::new();
        for i in 0..CANDIDATES_PER_POOL {
            let keypair = Keypair::generate_ed25519();
            let node = MerklePaymentCandidateNode::new(
                &keypair,
                create_mock_quoting_metrics(i),
                RewardsAddress::from([i as u8; 20]),
                timestamp,
            )
            .expect("Failed to create candidate node");
            candidate_nodes.push(node);
        }

        // Corrupt the pub_key of one node
        candidate_nodes[5].pub_key = vec![0xFF; 10];

        let proof = MerklePaymentProof::new(
            addresses[0],
            tree.generate_address_proof(0, addresses[0]).unwrap(),
            MerklePaymentCandidatePool {
                midpoint_proof: reward_pool.clone(),
                candidate_nodes: candidate_nodes
                    .try_into()
                    .expect("Should have exactly CANDIDATES_PER_POOL nodes"),
            },
        );

        // Try to get PeerIds for the corrupted node's address
        let paid_nodes = vec![(RewardsAddress::from([5; 20]), 5)];

        let result = proof.corresponding_peer_ids(&paid_nodes);
        assert!(
            result.is_err(),
            "Should fail when candidate has invalid pub_key"
        );

        match result {
            Err(MerklePaymentVerificationError::InvalidNodePeerId { address, index }) => {
                assert_eq!(address, RewardsAddress::from([5; 20]));
                assert_eq!(index, 5);
            }
            _ => panic!("Expected InvalidNodePeerId error"),
        }
    }

    #[test]
    fn test_corresponding_peer_ids_empty_input() {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create a merkle tree and get a reward pool
        let addresses = make_test_addresses(10);
        let tree = MerkleTree::from_xornames(addresses.clone()).unwrap();
        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
        let reward_pool = &reward_candidates[0];

        // Create candidate nodes
        let mut candidate_nodes = Vec::new();
        for i in 0..CANDIDATES_PER_POOL {
            let keypair = Keypair::generate_ed25519();
            let node = MerklePaymentCandidateNode::new(
                &keypair,
                create_mock_quoting_metrics(i),
                RewardsAddress::from([i as u8; 20]),
                timestamp,
            )
            .expect("Failed to create candidate node");
            candidate_nodes.push(node);
        }

        let proof = MerklePaymentProof::new(
            addresses[0],
            tree.generate_address_proof(0, addresses[0]).unwrap(),
            MerklePaymentCandidatePool {
                midpoint_proof: reward_pool.clone(),
                candidate_nodes: candidate_nodes
                    .try_into()
                    .expect("Should have exactly CANDIDATES_PER_POOL nodes"),
            },
        );

        // Test: Empty paid nodes
        let paid_nodes: Vec<(RewardsAddress, usize)> = vec![];

        let result = proof.corresponding_peer_ids(&paid_nodes);
        assert!(result.is_ok(), "Should succeed with empty input");

        let peer_ids = result.unwrap();
        assert_eq!(peer_ids.len(), 0, "Should return empty Vec for empty input");
    }

    #[test]
    fn test_corresponding_peer_ids_partial_payment() {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create a merkle tree and get a reward pool
        let addresses = make_test_addresses(10);
        let tree = MerkleTree::from_xornames(addresses.clone()).unwrap();
        let reward_candidates = tree.reward_candidates(timestamp).unwrap();
        let reward_pool = &reward_candidates[0];

        // Create 20 candidate nodes
        let mut candidate_nodes = Vec::new();
        let mut all_peer_ids = Vec::new();
        for i in 0..CANDIDATES_PER_POOL {
            let keypair = Keypair::generate_ed25519();
            let peer_id = keypair.public().to_peer_id();
            let node = MerklePaymentCandidateNode::new(
                &keypair,
                create_mock_quoting_metrics(i),
                RewardsAddress::from([i as u8; 20]),
                timestamp,
            )
            .expect("Failed to create candidate node");
            candidate_nodes.push(node);
            all_peer_ids.push(peer_id);
        }

        let proof = MerklePaymentProof::new(
            addresses[0],
            tree.generate_address_proof(0, addresses[0]).unwrap(),
            MerklePaymentCandidatePool {
                midpoint_proof: reward_pool.clone(),
                candidate_nodes: candidate_nodes
                    .try_into()
                    .expect("Should have exactly CANDIDATES_PER_POOL nodes"),
            },
        );

        // Test: Only subset of candidates were paid (depth=7, so only 7 out of 20 paid)
        let paid_nodes = vec![
            (RewardsAddress::from([0; 20]), 0),
            (RewardsAddress::from([1; 20]), 1),
            (RewardsAddress::from([2; 20]), 2),
            (RewardsAddress::from([3; 20]), 3),
            (RewardsAddress::from([4; 20]), 4),
            (RewardsAddress::from([5; 20]), 5),
            (RewardsAddress::from([6; 20]), 6),
        ];

        let result = proof.corresponding_peer_ids(&paid_nodes);
        assert!(
            result.is_ok(),
            "Should succeed when indices and addresses match"
        );

        let peer_ids = result.unwrap();
        assert_eq!(
            peer_ids.len(),
            7,
            "Should return only 7 PeerIds for the 7 paid nodes"
        );

        // Verify only the paid nodes' PeerIds are returned (in order)
        for i in 0..7 {
            assert_eq!(
                peer_ids[i], all_peer_ids[i],
                "Should return PeerId at index {i} in correct order"
            );
        }
    }

    #[test]
    fn test_complete_merkle_batch_payment_flow() {
        // Phase 1: Client prepares addresses and tree
        let address_count = 100;
        let addresses = make_test_addresses(address_count);
        let tree = MerkleTree::from_xornames(addresses.clone()).unwrap();
        let _root = tree.root();
        let depth = tree.depth();
        assert_eq!(depth, 7); // ceil(log2(100)) = 7

        // Phase 2: Client queries candidate pools
        let merkle_payment_timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let reward_candidates = tree.reward_candidates(merkle_payment_timestamp).unwrap();
        let expected_pools = crate::merkle_payments::expected_reward_pools(depth);
        assert_eq!(reward_candidates.len(), expected_pools);

        // Simulate querying 20 nodes for each pool with properly signed commitments
        let mut all_candidate_pools = Vec::new();
        for (pool_idx, reward_pool) in reward_candidates.iter().enumerate() {
            let mut candidate_nodes = Vec::new();
            for node_id in 0..CANDIDATES_PER_POOL {
                let keypair = Keypair::generate_ed25519();

                // Nodes verify the merkle payment timestamp is not too old (or in the future)
                let current_time = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs();
                assert!(
                    merkle_payment_timestamp <= current_time,
                    "Timestamp should not be in the future"
                );
                assert!(
                    current_time - merkle_payment_timestamp
                        < crate::merkle_payments::merkle_tree::MERKLE_PAYMENT_EXPIRATION,
                    "Timestamp should not be expired"
                );

                // Nodes generate their MerklePaymentCandidateNode and return it to the client
                let node = MerklePaymentCandidateNode::new(
                    &keypair,
                    create_mock_quoting_metrics(node_id),
                    RewardsAddress::from([(pool_idx * CANDIDATES_PER_POOL + node_id) as u8; 20]),
                    merkle_payment_timestamp,
                )
                .expect("Failed to create candidate node");

                // client verifies the node's signature
                assert!(node.verify_signature());

                // client verifies the node's MerklePaymentCandidateNode is the same as the one provided
                assert_eq!(
                    node.merkle_payment_timestamp, merkle_payment_timestamp,
                    "Honest nodes should return the same merkle payment timestamp"
                );

                // client adds the node to the pool
                candidate_nodes.push(node);
            }

            let pool = MerklePaymentCandidatePool {
                midpoint_proof: reward_pool.clone(),
                candidate_nodes: candidate_nodes
                    .try_into()
                    .expect("Should have exactly CANDIDATES_PER_POOL nodes"),
            };
            all_candidate_pools.push(pool);
        }

        // Phase 3: Client submits payment to contract
        let pool_commitments: Vec<PoolCommitment> = all_candidate_pools
            .iter()
            .map(|pool| pool.to_commitment())
            .collect();

        let temp_dir = TempDir::new().unwrap();
        let contract = evmlib::merkle_batch_payment::DiskMerklePaymentContract::new_with_path(
            temp_dir.path().to_path_buf(),
        )
        .unwrap();

        let (winner_pool_hash, _amount) = contract
            .pay_for_merkle_tree(depth, pool_commitments.clone(), merkle_payment_timestamp)
            .unwrap();

        // Verify payment info stored correctly
        let payment_info = contract.get_payment_info(winner_pool_hash).unwrap();
        assert_eq!(payment_info.depth, depth);
        assert_eq!(
            payment_info.merkle_payment_timestamp,
            merkle_payment_timestamp
        );
        assert_eq!(payment_info.paid_node_addresses.len(), depth as usize);

        // Find winner pool and verify commitment
        let (winner_pool, winner_commitment) = all_candidate_pools
            .iter()
            .zip(pool_commitments.iter())
            .find(|(pool, _)| pool.hash() == winner_pool_hash)
            .expect("Winner pool should be found");

        assert!(
            winner_pool
                .verify_commitment(winner_commitment, merkle_payment_timestamp)
                .is_ok(),
            "Winner commitment should verify against full pool data"
        );

        // Phase 4: Generate payment proofs for upload
        // Client creates a MerklePaymentProof for each address to send to nodes
        let payment_proofs: Vec<MerklePaymentProof> = addresses
            .iter()
            .enumerate()
            .map(|(i, address_hash)| {
                let address_proof = tree.generate_address_proof(i, *address_hash).unwrap();
                MerklePaymentProof::new(*address_hash, address_proof, winner_pool.clone())
            })
            .collect();

        // Phase 5: Nodes verify payment proofs
        for payment_proof in &payment_proofs {
            // Node queries smart contract using the winner_pool_hash
            let winner_to_fetch = payment_proof.winner_pool_hash();
            let payment = contract
                .get_payment_info(winner_to_fetch)
                .expect("Payment should be found");

            // Node verifies the payment proof using the smart contract data
            let verification_result = payment_proof.verify(
                payment.depth,
                payment.merkle_payment_timestamp,
                &winner_to_fetch,
                &payment.paid_node_addresses,
            );
            if let Err(e) = &verification_result {
                eprintln!("Verification failed: {e:?}");
            }
            assert!(
                verification_result.is_ok(),
                "Payment proof should verify against smart contract data: {verification_result:?}"
            );

            // Node verifies the closest nodes to winner pool include majority of paid nodes (this is done node side)
        }
    }
}