Repository navigation
Expand file tree
/
Copy pathbls_tests.cpp
More file actions
1206 lines (1024 loc) · 46.6 KB
/
Copy pathbls_tests.cpp
File metadata and controls
1206 lines (1024 loc) · 46.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019-2025 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bls/bls.h>
#include <bls/bls_batchverifier.h>
#include <bls/bls_worker.h>
#include <chainparams.h>
#include <clientversion.h>
#include <consensus/validation.h>
#include <crypto/common.h>
#include <deploymentstatus.h>
#include <random.h>
#include <script/solver.h>
#include <streams.h>
#include <test/util/bls.h>
#include <test/util/setup_common.h>
#include <util/helpers.h>
#include <util/strencodings.h>
#include <validation.h>
#include <boost/test/unit_test.hpp>
#include <type_traits>
BOOST_AUTO_TEST_SUITE(bls_tests)
void FuncSign(const BLSScheme scheme)
{
CBLSSecretKey sk1, sk2;
sk1.MakeNewKey();
sk2.MakeNewKey();
uint256 msgHash1 = uint256::ONE;
uint256 msgHash2 = uint256::TWO;
auto sig1 = SignBLS(sk1, msgHash1, scheme);
auto sig2 = SignBLS(sk2, msgHash1, scheme);
BOOST_CHECK(sig1.VerifyInsecure(sk1.GetPublicKey(), msgHash1, scheme));
BOOST_CHECK(!sig1.VerifyInsecure(sk1.GetPublicKey(), msgHash2, scheme));
BOOST_CHECK(!sig2.VerifyInsecure(sk1.GetPublicKey(), msgHash1, scheme));
BOOST_CHECK(!sig2.VerifyInsecure(sk2.GetPublicKey(), msgHash2, scheme));
BOOST_CHECK(sig2.VerifyInsecure(sk2.GetPublicKey(), msgHash1, scheme));
return;
}
void FuncSerialize(const BLSScheme scheme)
{
CBLSSecretKey sk;
DataStream ds2{}, ds3{};
uint256 msgHash = uint256::ONE;
sk.MakeNewKey();
CBLSSignature sig1 = SignBLS(sk, msgHash, scheme);
const BLSScheme opposite{scheme == BLSScheme::Legacy ? BLSScheme::Basic : BLSScheme::Legacy};
ds2 << BLSEncoded(sig1, scheme);
ds3 << BLSEncoded(sig1, opposite);
CBLSSignature sig2;
ds2 >> BLSEncoded(sig2, scheme);
BOOST_CHECK(sig1 == sig2);
CBLSSignature sig3;
ds3 >> BLSEncoded(sig3, opposite);
BOOST_CHECK(sig1 == sig3);
}
void FuncSetHexStr()
{
// Secret keys are not scheme-dependent. SetHexStr rejects a scalar that does not decode.
CBLSSecretKey sk;
std::string strValidSecret = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
// Note: invalid string passed to SetHexStr() should cause it to fail and reset key internal data
BOOST_CHECK(sk.SetHexStr(strValidSecret));
BOOST_CHECK(!sk.SetHexStr("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1g")); // non-hex
BOOST_CHECK(!sk.IsValid());
BOOST_CHECK(sk == CBLSSecretKey());
// Try few more invalid strings
BOOST_CHECK(sk.SetHexStr(strValidSecret));
BOOST_CHECK(!sk.SetHexStr("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e")); // hex but too short
BOOST_CHECK(!sk.IsValid());
BOOST_CHECK(sk.SetHexStr(strValidSecret));
BOOST_CHECK(!sk.SetHexStr("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20")); // hex but too long
BOOST_CHECK(!sk.IsValid());
}
void FuncKeyAgg(const BLSScheme scheme)
{
CBLSSecretKey sk1, sk2;
sk1.MakeNewKey();
sk2.MakeNewKey();
CBLSPublicKey ag_pk = sk1.GetPublicKey();
ag_pk.AggregateInsecure(sk2.GetPublicKey());
CBLSSecretKey ag_sk = sk1;
ag_sk.AggregateInsecure(sk2);
BOOST_CHECK(ag_pk == ag_sk.GetPublicKey());
uint256 msgHash1 = uint256::ONE;
uint256 msgHash2 = uint256::TWO;
auto sig = SignBLS(ag_sk, msgHash1, scheme);
BOOST_CHECK(sig.VerifyInsecure(ag_pk, msgHash1, scheme));
BOOST_CHECK(!sig.VerifyInsecure(ag_pk, msgHash2, scheme));
}
void FuncKeyAggVec(const BLSScheme scheme)
{
std::vector<CBLSSecretKey> vec_sk;
std::vector<CBLSPublicKey> vec_pk;
{
auto ret = CBLSSecretKey::AggregateInsecure(vec_sk);
BOOST_CHECK(ret == CBLSSecretKey());
}
{
auto ret = CBLSPublicKey::AggregateInsecure(vec_pk);
BOOST_CHECK(ret == CBLSPublicKey());
}
// In practice, we only aggregate 400 key shares at any given time, something substantially larger than that should
// be good. Plus this is very very fast, so who cares!
int key_count = 10000;
vec_sk.reserve(key_count);
vec_pk.reserve(key_count);
CBLSSecretKey sk;
for (int i = 0; i < key_count; i++) {
sk.MakeNewKey();
vec_sk.push_back(sk);
vec_pk.push_back(sk.GetPublicKey());
}
CBLSSecretKey ag_sk = CBLSSecretKey::AggregateInsecure(vec_sk);
CBLSPublicKey ag_pk = CBLSPublicKey::AggregateInsecure(vec_pk);
BOOST_CHECK(ag_sk.IsValid());
BOOST_CHECK(ag_pk.IsValid());
uint256 msgHash1 = uint256::ONE;
uint256 msgHash2 = uint256::TWO;
auto sig = SignBLS(ag_sk, msgHash1, scheme);
BOOST_CHECK(sig.VerifyInsecure(ag_pk, msgHash1, scheme));
BOOST_CHECK(!sig.VerifyInsecure(ag_pk, msgHash2, scheme));
}
void FuncSigAggSub()
{
int count = 20;
std::vector<CBLSPublicKey> vec_pks;
std::vector<uint256> vec_hashes;
std::vector<CBLSSignature> vec_sigs;
vec_pks.reserve(count);
vec_hashes.reserve(count);
vec_sigs.reserve(count);
CBLSSignature sig;
auto sk = CBLSSecretKey();
uint256 hash;
for (int i = 0; i < count; i++) {
sk.MakeNewKey();
vec_pks.push_back(sk.GetPublicKey());
hash = GetRandHash();
vec_hashes.push_back(hash);
CBLSSignature sig_i = sk.Sign(hash);
vec_sigs.push_back(sig_i);
if (i == 0) {
// first sig is assigned directly
sig = sig_i;
} else {
// all other sigs are aggregated into the previously computed/stored sig
sig.AggregateInsecure(sig_i);
}
BOOST_CHECK(sig.VerifyInsecureAggregated(vec_pks, vec_hashes));
}
// Create an aggregated signature from the vector of individual signatures
auto vecSig = CBLSSignature::AggregateInsecure(vec_sigs);
BOOST_CHECK(vecSig.VerifyInsecureAggregated(vec_pks, vec_hashes));
// Check that these two signatures are equal
BOOST_CHECK(sig == vecSig);
// Test that the sig continues to be valid when subtracting sigs via `SubInsecure`
for (int i = 0; i < count - 1; i++) {
auto top_sig = vec_sigs.back();
vec_pks.pop_back();
vec_hashes.pop_back();
BOOST_CHECK(!sig.VerifyInsecureAggregated(vec_pks, vec_hashes));
sig.SubInsecure(top_sig);
BOOST_CHECK(sig.VerifyInsecureAggregated(vec_pks, vec_hashes));
vec_sigs.pop_back();
}
// Check that the final left-over sig validates
BOOST_CHECK_EQUAL(vec_sigs.size(), 1);
BOOST_CHECK_EQUAL(vec_pks.size(), 1);
BOOST_CHECK_EQUAL(vec_hashes.size(), 1);
BOOST_CHECK(vec_sigs[0].VerifyInsecure(vec_pks[0], vec_hashes[0]));
}
void FuncSigAggSecure(const BLSScheme scheme)
{
int count = 10;
uint256 hash = GetRandHash();
std::vector<CBLSSignature> vec_sigs;
std::vector<CBLSPublicKey> vec_pks;
CBLSSecretKey sk;
for (int i = 0; i < count; i++) {
sk.MakeNewKey();
vec_pks.push_back(sk.GetPublicKey());
vec_sigs.push_back(SignBLS(sk, hash, scheme));
}
auto sec_agg_sig = AggregateSecureBLS(vec_sigs, vec_pks, hash, scheme);
BOOST_CHECK(sec_agg_sig.IsValid());
BOOST_CHECK(sec_agg_sig.VerifySecureAggregated(vec_pks, hash, scheme));
const BLSScheme other{scheme == BLSScheme::Legacy ? BLSScheme::Basic : BLSScheme::Legacy};
BOOST_CHECK(!sec_agg_sig.VerifySecureAggregated(vec_pks, hash, other));
if (scheme == BLSScheme::Basic) {
BOOST_CHECK(sec_agg_sig == CBLSSignature::AggregateSecure(vec_sigs, vec_pks, hash));
}
}
void FuncDHExchange()
{
CBLSSecretKey sk1, sk2;
sk1.MakeNewKey();
sk2.MakeNewKey();
CBLSPublicKey pk1, pk2;
pk1 = sk1.GetPublicKey();
pk2 = sk2.GetPublicKey();
// Perform diffie-helman exchange
CBLSPublicKey pke1, pke2;
pke1.DHKeyExchange(sk1, pk2);
pke2.DHKeyExchange(sk2, pk1);
BOOST_CHECK(pke1.IsValid());
BOOST_CHECK(pke2.IsValid());
BOOST_CHECK(pke1 == pke2);
}
struct Message
{
uint32_t sourceId;
uint32_t msgId;
uint256 msgHash;
CBLSSecretKey sk;
CBLSPublicKey pk;
CBLSSignature sig;
bool valid;
};
static void AddMessage(std::vector<Message>& vec, uint32_t sourceId, uint32_t msgId, uint8_t msgHash, bool valid)
{
Message m;
m.sourceId = sourceId;
m.msgId = msgId;
m.msgHash = uint256(msgHash);
m.sk.MakeNewKey();
m.pk = m.sk.GetPublicKey();
m.sig = m.sk.Sign(m.msgHash);
m.valid = valid;
if (!valid) {
CBLSSecretKey tmp;
tmp.MakeNewKey();
m.sig = tmp.Sign(m.msgHash);
}
vec.emplace_back(m);
}
// Adds two wrong signatures whose errors cancel out when both are aggregated unweighted
static void AddCancellingMessages(std::vector<Message>& vec, uint32_t sourceId1, uint32_t msgId1, uint8_t msgHash1,
uint32_t sourceId2, uint32_t msgId2, uint8_t msgHash2, bool sameKey)
{
AddMessage(vec, sourceId1, msgId1, msgHash1, true);
AddMessage(vec, sourceId2, msgId2, msgHash2, true);
auto& m1 = vec[vec.size() - 2];
auto& m2 = vec[vec.size() - 1];
if (sameKey) {
m2.sk = m1.sk;
m2.pk = m1.pk;
m2.sig = m2.sk.Sign(m2.msgHash);
}
CBLSSecretKey sk_error;
sk_error.MakeNewKey();
const CBLSSignature error{sk_error.Sign(uint256::ONE)};
m1.sig.AggregateInsecure(error);
m2.sig.SubInsecure(error);
m1.valid = false;
m2.valid = false;
}
static void Verify(std::vector<Message>& vec, bool secureVerification, bool perMessageFallback)
{
CBLSBatchVerifier<uint32_t, uint32_t> batchVerifier(secureVerification, perMessageFallback);
std::set<uint32_t> expectedBadMessages;
std::set<uint32_t> expectedBadSources;
for (auto& m : vec) {
if (!m.valid) {
expectedBadMessages.emplace(m.msgId);
expectedBadSources.emplace(m.sourceId);
}
batchVerifier.PushMessage(m.sourceId, m.msgId, m.msgHash, m.sig, m.pk);
}
batchVerifier.Verify();
BOOST_CHECK(batchVerifier.badSources == expectedBadSources);
if (perMessageFallback) {
BOOST_CHECK(batchVerifier.badMessages == expectedBadMessages);
} else {
BOOST_CHECK(batchVerifier.badMessages.empty());
}
}
static void Verify(std::vector<Message>& vec)
{
Verify(vec, false, false);
Verify(vec, true, false);
Verify(vec, false, true);
Verify(vec, true, true);
}
void FuncBatchVerifier()
{
std::vector<Message> msgs;
// distinct messages from distinct sources
AddMessage(msgs, 1, 1, 1, true);
AddMessage(msgs, 2, 2, 2, true);
AddMessage(msgs, 3, 3, 3, true);
Verify(msgs);
// distinct messages from same source
AddMessage(msgs, 4, 4, 4, true);
AddMessage(msgs, 4, 5, 5, true);
AddMessage(msgs, 4, 6, 6, true);
Verify(msgs);
// invalid sig
AddMessage(msgs, 7, 7, 7, false);
Verify(msgs);
// same message as before, but from another source and with valid sig
AddMessage(msgs, 8, 8, 7, true);
Verify(msgs);
// same message as before, but from another source and signed with another key
AddMessage(msgs, 9, 9, 7, true);
Verify(msgs);
msgs.clear();
// same message, signed by multiple keys
AddMessage(msgs, 1, 1, 1, true);
AddMessage(msgs, 1, 2, 1, true);
AddMessage(msgs, 1, 3, 1, true);
AddMessage(msgs, 2, 4, 1, true);
AddMessage(msgs, 2, 5, 1, true);
AddMessage(msgs, 2, 6, 1, true);
Verify(msgs);
// last message invalid from one source
AddMessage(msgs, 1, 7, 1, false);
Verify(msgs);
msgs.clear();
// errors cancelling out between distinct messages from one source
AddMessage(msgs, 1, 1, 1, true);
AddCancellingMessages(msgs, 2, 2, 2, 2, 3, 3, /*sameKey=*/false);
Verify(msgs);
// errors cancelling out between distinct sources signing the same message with the same key
msgs.clear();
AddMessage(msgs, 1, 1, 1, true);
AddCancellingMessages(msgs, 2, 2, 2, 3, 3, 2, /*sameKey=*/true);
Verify(msgs);
}
void FuncThresholdSignature(const BLSScheme scheme)
{
[[maybe_unused]] const uint256 hash = GetRandHash();
constexpr size_t m_size = 20;
constexpr size_t m_threshold = 15;
std::vector<CBLSSecretKey> v_threshold_sks;
std::vector<CBLSPublicKey> v_threshold_pks;
for ([[maybe_unused]] const auto i : util::irange(m_threshold)) {
CBLSSecretKey sk;
sk.MakeNewKey();
v_threshold_sks.push_back(sk);
v_threshold_pks.emplace_back(sk.GetPublicKey());
}
CBLSSecretKey thr_sk = v_threshold_sks[0];
CBLSPublicKey thr_pk = v_threshold_pks[0];
CBLSSignature thr_sig = SignBLS(thr_sk, hash, scheme);
std::vector<CBLSId> v_size_ids;
std::vector<CBLSSecretKey> v_size_sk_shares;
std::vector<CBLSPublicKey> v_size_pk_shares;
for ([[maybe_unused]] const auto m_shares : util::irange(m_size)) {
v_size_ids.emplace_back(GetRandHash());
CBLSSecretKey sk;
BOOST_CHECK(sk.SecretKeyShare(v_threshold_sks, v_size_ids[m_shares]));
v_size_sk_shares.push_back(sk);
CBLSPublicKey pk;
BOOST_CHECK(pk.PublicKeyShare(v_threshold_pks, v_size_ids[m_shares]));
v_size_pk_shares.push_back(pk);
std::vector<CBLSSignature> v_share_sigs;
std::vector<CBLSId> v_share_ids;
for ([[maybe_unused]] const auto j : util::irange(m_shares)) {
v_share_sigs.emplace_back(SignBLS(v_size_sk_shares[j], hash, scheme));
BOOST_CHECK(v_share_sigs.back().VerifyInsecure(v_size_pk_shares[j], hash, scheme));
v_share_ids.push_back(v_size_ids[j]);
}
CBLSSignature rec_share_sig;
BOOST_CHECK_EQUAL(rec_share_sig.Recover(v_share_sigs, v_share_ids), m_shares >= 2);
BOOST_CHECK_EQUAL(rec_share_sig.IsValid(), m_shares >= 2);
BOOST_CHECK_EQUAL(rec_share_sig == thr_sig, m_shares >= m_threshold);
BOOST_CHECK_EQUAL(rec_share_sig.VerifyInsecure(thr_pk, hash, scheme), m_shares >= m_threshold);
}
}
BOOST_AUTO_TEST_CASE(bls_sethexstr_tests) { FuncSetHexStr(); }
BOOST_AUTO_TEST_CASE(bls_serialize_tests)
{
FuncSerialize(BLSScheme::Legacy);
FuncSerialize(BLSScheme::Basic);
}
BOOST_AUTO_TEST_CASE(bls_sig_tests)
{
FuncSign(BLSScheme::Legacy);
FuncSign(BLSScheme::Basic);
}
BOOST_AUTO_TEST_CASE(bls_key_agg_tests)
{
FuncKeyAgg(BLSScheme::Legacy);
FuncKeyAgg(BLSScheme::Basic);
}
BOOST_AUTO_TEST_CASE(bls_key_agg_vec_tests)
{
FuncKeyAggVec(BLSScheme::Legacy);
FuncKeyAggVec(BLSScheme::Basic);
}
BOOST_AUTO_TEST_CASE(bls_sig_agg_sub_tests) { FuncSigAggSub(); }
BOOST_AUTO_TEST_CASE(bls_sig_agg_secure_tests)
{
FuncSigAggSecure(BLSScheme::Legacy);
FuncSigAggSecure(BLSScheme::Basic);
}
BOOST_AUTO_TEST_CASE(bls_dh_exchange_tests) { FuncDHExchange(); }
BOOST_AUTO_TEST_CASE(batch_verifier_tests) { FuncBatchVerifier(); }
BOOST_AUTO_TEST_CASE(bls_threshold_signature_tests)
{
FuncThresholdSignature(BLSScheme::Legacy);
FuncThresholdSignature(BLSScheme::Basic);
}
// Regression test: a DKG justification path can reach
// CBLSWorker::AsyncVerifyContributionShare() with a null verification vector when
// the corresponding member's contribution was never received (e.g. on a non-member
// observer). The singular overload dereferenced *vvec with no null check and aborted
// the process; it must instead treat a missing vvec as a failed verification, like
// the plural VerifyVerificationVectors() path. A *valid* id is required so the guard
// does not short-circuit before reaching the (previously) unguarded dereference.
void FuncVerifyContributionShareNullVvec()
{
CBLSWorker worker;
worker.Start(1);
const CBLSId id{uint256::ONE};
BOOST_REQUIRE(id.IsValid());
CBLSSecretKey sk;
sk.MakeNewKey();
const BLSVerificationVectorPtr null_vvec; // default-constructed null shared_ptr
BOOST_REQUIRE(null_vvec == nullptr);
// Must return false (verification failed) instead of dereferencing the null vvec.
BOOST_CHECK(worker.AsyncVerifyContributionShare(id, null_vvec, sk).get() == false);
worker.Stop();
}
BOOST_AUTO_TEST_CASE(bls_verify_contribution_share_null_vvec_tests) { FuncVerifyContributionShareNullVvec(); }
// Regression: an empty verification-vector set schedules no work at all, so
// before the guard nothing ever invoked doneCallback and .get() threw
// std::future_error(broken_promise). In production that throw escapes
// VerifyPendingContributions on the DKG phase-handler thread, which only catches
// AbortPhaseException, and std::terminate aborts dashd.
// Contract: return an empty result vector, on both the aggregated and the
// one-by-one path.
void FuncVerifyContributionSharesEmptyVvecs()
{
CBLSWorker worker;
worker.Start(1);
const CBLSId id{uint256::ONE};
BOOST_REQUIRE(id.IsValid());
std::vector<BLSVerificationVectorPtr> vvecs; // empty
std::vector<CBLSSecretKey> skShares; // empty
// Must return gracefully (empty result) instead of destroying the promise.
const auto result = worker.VerifyContributionShares(id, vvecs, skShares);
BOOST_CHECK(result.empty());
const auto result_no_agg = worker.VerifyContributionShares(id, vvecs, skShares,
/*parallel=*/true,
/*aggregated=*/false);
BOOST_CHECK(result_no_agg.empty());
worker.Stop();
}
BOOST_AUTO_TEST_CASE(bls_verify_contribution_shares_empty_vvecs_tests) { FuncVerifyContributionSharesEmptyVvecs(); }
// Positive control for the empty-input guard: it must not change which
// contributions are accepted. Accepting an invalid share would corrupt the
// recovered quorum key; rejecting an honest one would stall DKG. This property
// was previously only covered by src/bench/bls_dkg.cpp, which does not run under
// ctest.
//
// QUORUM_SIZE exceeds CONTRIBUTION_VERIFY_BATCH_SIZE so the aggregated path
// builds more than one batch. Corrupting a share in the first batch must then
// fail that batch, fall back to per-contribution verification, blame exactly the
// corrupted index, and leave the second batch accepted wholesale - an invalid
// share must never be masked by the valid shares it is aggregated with.
void FuncVerifyContributionSharesHonest()
{
constexpr size_t QUORUM_SIZE{CBLSWorker::CONTRIBUTION_VERIFY_BATCH_SIZE + 2};
constexpr int THRESHOLD{6};
CBLSWorker worker;
worker.Start(4);
std::vector<CBLSId> ids;
ids.reserve(QUORUM_SIZE);
for (const size_t i : util::irange(QUORUM_SIZE)) {
uint256 id;
WriteLE64(id.begin(), i + 1);
ids.emplace_back(id);
}
// Every member runs GenerateContributions and broadcasts its vvec; member i's
// share for us (member 0) is skShares[i][0].
std::vector<BLSVerificationVectorPtr> vvecs;
std::vector<CBLSSecretKey> skContributions;
vvecs.reserve(QUORUM_SIZE);
skContributions.reserve(QUORUM_SIZE);
for ([[maybe_unused]] const size_t i : util::irange(QUORUM_SIZE)) {
BLSVerificationVectorPtr vvec;
std::vector<CBLSSecretKey> skShares;
BOOST_REQUIRE(worker.GenerateContributions(THRESHOLD, ids, vvec, skShares));
BOOST_REQUIRE(vvec != nullptr);
BOOST_REQUIRE_EQUAL(vvec->size(), size_t(THRESHOLD));
BOOST_REQUIRE_EQUAL(skShares.size(), QUORUM_SIZE);
vvecs.emplace_back(std::move(vvec));
skContributions.emplace_back(skShares[0]); // the share addressed to ids[0]
}
const CBLSId& myId = ids[0];
// 1. All-honest input must be accepted in full, on both code paths.
for (const bool aggregated : {true, false}) {
const auto result = worker.VerifyContributionShares(myId, vvecs, skContributions,
/*parallel=*/true, aggregated);
BOOST_REQUIRE_EQUAL(result.size(), QUORUM_SIZE);
for (const size_t i : util::irange(QUORUM_SIZE)) {
BOOST_CHECK_MESSAGE(result[i], "honest contribution " << i << " rejected (aggregated="
<< aggregated << ")");
}
}
// 2. Corrupt one share and expect exactly that index to be blamed, nobody else.
// With aggregated=true the corrupted index sits in the first batch, so that
// batch must fail and fall back to per-contribution verification while the
// second batch stays accepted wholesale. With aggregated=false there is a
// single batch verified one-by-one, so only the blame-exactness holds.
constexpr size_t BAD_IDX{3};
static_assert(BAD_IDX < CBLSWorker::CONTRIBUTION_VERIFY_BATCH_SIZE,
"corrupted index must land in the first batch");
auto corrupted = skContributions;
corrupted[BAD_IDX].MakeNewKey(); // valid key, wrong value -> pk mismatch
for (const bool aggregated : {true, false}) {
const auto result = worker.VerifyContributionShares(myId, vvecs, corrupted,
/*parallel=*/true, aggregated);
BOOST_REQUIRE_EQUAL(result.size(), QUORUM_SIZE);
for (const size_t i : util::irange(QUORUM_SIZE)) {
const bool expected{i != BAD_IDX};
BOOST_CHECK_MESSAGE(result[i] == expected,
"index " << i << " expected " << expected << " got " << result[i]
<< " (aggregated=" << aggregated << ")");
}
}
// 3. With the defaults the DKG uses, only the dealers of wrong shares are blamed:
// - two colluding dealers in the same batch swap their shares: each one is wrong, but their sum is not, so the
// errors cancel in an unweighted aggregate;
// - a missing (invalid) share fails its batch and is blamed alone.
auto swapped = skContributions;
std::swap(swapped[1], swapped[2]);
auto missing = skContributions;
missing[5] = CBLSSecretKey{};
std::vector<std::pair<std::vector<CBLSSecretKey>, std::set<size_t>>> cases{
{swapped, {1, 2}},
{missing, {5}},
};
for (auto& [shares, bad] : cases) {
for (const bool parallel : {true, false}) {
const auto result = worker.VerifyContributionShares(myId, vvecs, shares, parallel);
BOOST_REQUIRE_EQUAL(result.size(), QUORUM_SIZE);
for (const size_t i : util::irange(QUORUM_SIZE)) {
const bool expected{bad.count(i) == 0};
BOOST_CHECK_MESSAGE(result[i] == expected, "index " << i << " expected " << expected << " got "
<< result[i] << " (parallel=" << parallel << ")");
}
}
}
worker.Stop();
}
BOOST_AUTO_TEST_CASE(bls_verify_contribution_shares_honest_tests) { FuncVerifyContributionSharesHonest(); }
// A duplicate coefficient point between two members' verification vectors must not fail the
// other members' contributions. CBLSWorker::VerifyContributionShares() batches the members'
// vvecs, and the batched VerifyVerificationVectors() check rejects a coefficient shared
// between two vvecs. Failing the whole batch on that let one member, by copying another
// member's coefficient into its own vvec, mark every honest member in the batch invalid.
// The fix verifies each contribution against its own vvec, so only the member whose share no
// longer matches its own vvec fails. Regression: on the old all-or-nothing code every entry
// came back false, so the honest members verifying true is what distinguishes fixed from broken.
void FuncVerifyContributionSharesDuplicateCoefficient()
{
CBLSWorker worker;
worker.Start(4);
const int threshold = 2;
std::vector<CBLSId> ids;
for (int i = 0; i < 4; i++) {
uint256 id;
WriteLE64(id.begin(), i + 1);
ids.emplace_back(id);
}
// Three dealers each generate a verification vector and their secret-key shares to each id.
std::vector<BLSVerificationVectorPtr> vvecs(3);
std::vector<std::vector<CBLSSecretKey>> skShares(3);
for (int d = 0; d < 3; d++) {
BOOST_REQUIRE(worker.GenerateContributions(threshold, ids, vvecs[d], skShares[d]));
}
// Receiver R collects each dealer's share to it.
const size_t R = 0;
const CBLSId& recvId = ids[R];
std::vector<CBLSSecretKey> recvShares{skShares[0][R], skShares[1][R], skShares[2][R]};
// All honest: every contribution verifies.
std::vector<bool> ok = worker.VerifyContributionShares(recvId, vvecs, recvShares);
BOOST_REQUIRE_EQUAL(ok.size(), 3U);
BOOST_CHECK(ok[0] && ok[1] && ok[2]);
// Dealer 0 copies dealer 1's leading coefficient into its own vvec (a cross-member
// duplicate) without touching its share, making the batch vvec check fail.
vvecs[0]->at(0) = vvecs[1]->at(0);
std::vector<bool> res = worker.VerifyContributionShares(recvId, vvecs, recvShares);
BOOST_REQUIRE_EQUAL(res.size(), 3U);
BOOST_CHECK(!res[0]); // the member that planted the duplicate is caught alone
BOOST_CHECK(res[1]); // the honest member whose coefficient was copied is unaffected
BOOST_CHECK(res[2]); // the other honest member is unaffected
BOOST_CHECK(CBLSWorker::FindVerificationVectorsWithSharedCoefficients(vvecs) == (std::set<size_t>{0, 1}));
// Dealer 0 copies dealer 1's whole contribution, vvec and share alike: every share verifies,
// but the quorum verification vector can't be built until both copies are dropped.
vvecs[0] = std::make_shared<std::vector<CBLSPublicKey>>(*vvecs[1]);
recvShares[0] = skShares[1][R];
res = worker.VerifyContributionShares(recvId, vvecs, recvShares);
BOOST_REQUIRE_EQUAL(res.size(), 3U);
BOOST_CHECK(res[0] && res[1] && res[2]);
BOOST_CHECK(worker.BuildQuorumVerificationVector(vvecs) == nullptr);
BOOST_CHECK(CBLSWorker::FindVerificationVectorsWithSharedCoefficients(vvecs) == (std::set<size_t>{0, 1}));
std::vector<BLSVerificationVectorPtr> remaining{vvecs[2]};
BOOST_CHECK(worker.BuildQuorumVerificationVector(remaining) != nullptr);
// Distinct vvecs share nothing, and a missing vvec is skipped.
std::vector<BLSVerificationVectorPtr> distinct{vvecs[1], nullptr, vvecs[2]};
BOOST_CHECK(CBLSWorker::FindVerificationVectorsWithSharedCoefficients(distinct).empty());
worker.Stop();
}
BOOST_AUTO_TEST_CASE(bls_verify_contribution_shares_duplicate_coefficient_tests)
{
FuncVerifyContributionSharesDuplicateCoefficient();
}
void FuncAggregateCollidingContributionShares()
{
CBLSWorker worker;
worker.Start(4);
// The receiver's id is -1 mod the group order, so a degree-1 polynomial b0 + b1 * x takes the value b0 - b1 there
uint256 recvIdHash;
const auto minusOne{ParseHex("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000")};
std::copy(minusOne.begin(), minusOne.end(), recvIdHash.begin());
const CBLSId recvId{recvIdHash};
// Dealer 0 is honest. Dealers 1 and 2 collude: their polynomials differ, but agree at the receiver's id
const auto makeKey = [] { CBLSSecretKey sk; sk.MakeNewKey(); return sk; };
std::vector<std::vector<CBLSSecretKey>> polys{{makeKey(), makeKey()}, {makeKey(), makeKey()}, {}};
CBLSSecretKey share1;
BOOST_REQUIRE(share1.SecretKeyShare(polys[1], recvId));
const CBLSSecretKey b1{makeKey()};
CBLSSecretKey b0{share1};
b0.AggregateInsecure(b1);
polys[2] = {b0, b1};
std::vector<BLSVerificationVectorPtr> vvecs;
std::vector<CBLSSecretKey> recvShares;
for (auto& poly : polys) {
auto vvec = std::make_shared<std::vector<CBLSPublicKey>>();
for (const auto& coefficient : poly) {
vvec->emplace_back(coefficient.GetPublicKey());
}
vvecs.emplace_back(vvec);
BOOST_REQUIRE(recvShares.emplace_back().SecretKeyShare(poly, recvId));
}
BOOST_REQUIRE(recvShares[1] == recvShares[2]);
// Every contribution verifies and nothing in the vvecs collides
const std::vector<bool> ok{worker.VerifyContributionShares(recvId, vvecs, recvShares)};
BOOST_CHECK(ok == std::vector<bool>(3, true));
const BLSVerificationVectorPtr quorumVvec{worker.BuildQuorumVerificationVector(vvecs)};
BOOST_REQUIRE(quorumVvec != nullptr);
// so the receiver must still get the quorum secret key share matching the quorum vvec
const CBLSSecretKey skShare{worker.AggregateSecretKeys(recvShares)};
BOOST_REQUIRE(skShare.IsValid());
BOOST_CHECK(skShare.GetPublicKey() == CBLSWorker::BuildPubKeyShare(quorumVvec, recvId));
worker.Stop();
}
BOOST_AUTO_TEST_CASE(bls_aggregate_colliding_contribution_shares_tests) { FuncAggregateCollidingContributionShares(); }
// A dummy BLS object that satisfies the minimal interface expected by CBLSLazyWrapper.
class DummyBLS
{
public:
// Define a fixed serialization size (for testing purposes).
static const size_t SerSize = 4;
std::array<uint8_t, SerSize> data{};
DummyBLS() { data.fill(0); }
// A dummy validity check: valid if any byte is non-zero.
bool IsValid() const
{
return std::any_of(data.begin(), data.end(), [](uint8_t c) { return c != 0; });
}
// The dummy object has one encoding; the scheme argument is unused.
std::array<uint8_t, SerSize> ToBytes(BLSScheme /*scheme*/) const { return data; }
void SetBytes(const std::array<uint8_t, SerSize>& bytes, BLSScheme /*scheme*/) { data = bytes; }
// A dummy malleability check: simply compares the stored data to the given bytes.
bool CheckMalleable(const std::array<uint8_t, SerSize>& bytes, BLSScheme /*scheme*/) const { return data == bytes; }
// Reset the object to an "empty" state.
void Reset() { data.fill(0); }
// Produce a string representation.
std::string ToString(BLSScheme /*scheme*/) const { return HexStr(data); }
// Equality operator.
bool operator==(const DummyBLS& other) const { return data == other.data; }
};
// The scheme-taking operations of the lazy wrapper are protected; the production
// subclasses publish the ones they allow. This test subclass publishes all of them.
class LazyDummyBLS : public CBLSLazyWrapper<DummyBLS>
{
public:
using CBLSLazyWrapper<DummyBLS>::SerializeAs;
using CBLSLazyWrapper<DummyBLS>::UnserializeAs;
using CBLSLazyWrapper<DummyBLS>::GetHashAs;
};
// Unset wrappers compare equal, a set wrapper differs from unset and from a
// different value, and two wrappers set to the same value compare equal.
BOOST_AUTO_TEST_CASE(test_equality_same_value)
{
LazyDummyBLS lazy1;
LazyDummyBLS lazy2;
BOOST_CHECK(lazy1 == lazy2);
DummyBLS obj;
obj.data = {5, 6, 7, 8};
lazy1.Set(obj);
BOOST_CHECK(lazy1 != lazy2);
BOOST_CHECK(!(lazy1 == lazy2));
lazy2.Set(obj);
BOOST_CHECK(lazy1 == lazy2);
obj.data = {2, 2, 3, 4};
LazyDummyBLS lazy_other;
lazy_other.Set(obj);
BOOST_CHECK(lazy1 != lazy_other);
}
// Test 4: Serialization and unserialization preserve the wrapped value.
BOOST_AUTO_TEST_CASE(test_serialization_unserialization)
{
LazyDummyBLS lazy1;
DummyBLS obj;
obj.data = {9, 10, 11, 12};
lazy1.Set(obj);
// Serialize the lazy object into a data stream.
DataStream ds{};
lazy1.SerializeAs(ds, BLSScheme::Legacy);
// Create a new instance and unserialize the data into it.
LazyDummyBLS lazy2;
lazy2.UnserializeAs(ds, BLSScheme::Legacy);
BOOST_CHECK(lazy1 == lazy2);
BOOST_CHECK(lazy2.Get() == obj);
}
// Test 5: Two wrappers wrapping the same object should have the same hash.
BOOST_AUTO_TEST_CASE(test_get_hash_consistency)
{
LazyDummyBLS lazy1;
LazyDummyBLS lazy2;
DummyBLS obj;
obj.data = {13, 14, 15, 16};
lazy1.Set(obj);
lazy2.Set(obj);
uint256 hash1 = lazy1.GetHashAs(BLSScheme::Basic);
uint256 hash2 = lazy2.GetHashAs(BLSScheme::Basic);
BOOST_CHECK(hash1 == hash2);
}
namespace {
enum class DecodeKind {
Invalid,
Throws,
Valid
};
struct DecodeRow {
const char* name;
const char* hex;
BLSScheme scheme;
DecodeKind kind;
// Re-encodings of the decoded point. Null unless kind == Valid.
const char* point_legacy;
const char* point_basic;
};
std::string RepeatByteHex(uint8_t byte, size_t size) { return HexStr(std::vector<uint8_t>(size, byte)); }
// Both schemes serialize the identity as 0xc0 followed by zeros.
std::string InfinityHex(size_t size)
{
std::vector<uint8_t> bytes(size, 0);
bytes[0] = 0xc0;
return HexStr(bytes);
}
template <typename T>
void CheckDecode(const DecodeRow& row)
{
const auto bytes = ParseHex(row.hex);
BOOST_REQUIRE_EQUAL(bytes.size(), T::SerSize);
T obj;
DataStream ds{bytes};
bool threw = false;
std::string what;
try {
obj.Unserialize(ds, row.scheme);
} catch (const std::ios_base::failure& e) {
threw = true;
what = e.what();
}
if (row.kind == DecodeKind::Throws) {
BOOST_CHECK(threw);
BOOST_CHECK(what.find("malleable BLS object") != std::string::npos);
return;
}
BOOST_CHECK(!threw);
if (row.kind == DecodeKind::Invalid) {
BOOST_CHECK(!obj.IsValid());
return;
}
BOOST_REQUIRE(obj.IsValid());
BOOST_CHECK_EQUAL(obj.ToString(BLSScheme::Legacy), row.point_legacy);
BOOST_CHECK_EQUAL(obj.ToString(BLSScheme::Basic), row.point_basic);
}
// The different point PK1's basic encoding decodes to under legacy.
const char* PK1_BAS_AS_LEG_BAS = "b7f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af"
"00adb22c6bb";
// Public key of secret scalar 2, and the different point its legacy encoding decodes to under basic.
const char* PK2_LEG = "8572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8c5529bf0f4"
"e";
const char* PK2_BAS = "a572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8c5529bf0f4"
"e";
const char* PK2_LEG_AS_BAS_LEG = "0572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8"
"c5529bf0f4e";
// Legacy signature of scalar 1 over uint256::ONE. Its legacy encoding is not canonical under basic, and its basic encoding is not canonical under legacy.
const char* SIG1_LEG = "8f8cde907769bb0b753efe4dd1cfddd85d8ac1878dc724884347acea5dd5d8f92bbd42a8bd34ecc134951435231d6c1"
"9184450feca2ff2fb723308f7d5c64d3234e64bf508158f99144bed1ed20d34b2db63baaef121b29143102882b6d13a"
"97";
const char* SIG1_BAS = "b84450feca2ff2fb723308f7d5c64d3234e64bf508158f99144bed1ed20d34b2db63baaef121b29143102882b6d13a9"
"70f8cde907769bb0b753efe4dd1cfddd85d8ac1878dc724884347acea5dd5d8f92bbd42a8bd34ecc134951435231d6c"
"19";
// Legacy signature of scalar 6 over uint256::ONE. Its basic encoding is canonical under both schemes and decodes to two different points.
const char* SIG6_LEG = "029305a30c9830695358432443b30d29ac40cc60aba2df4df195c4144521613840b984e0ebd5e934d2b00d13b07e813"
"212d170dd5a79b4b1a30b5e345f8a1d14472d40d885c8e55c9406159f5de8909e0b85f923b6290dac61bd6cafcc7f9d"
"ba";
const char* SIG6_BAS = "92d170dd5a79b4b1a30b5e345f8a1d14472d40d885c8e55c9406159f5de8909e0b85f923b6290dac61bd6cafcc7f9db"
"a029305a30c9830695358432443b30d29ac40cc60aba2df4df195c4144521613840b984e0ebd5e934d2b00d13b07e81"
"32";
const char* SIG6_BAS_AS_LEG_BAS = "a29305a30c9830695358432443b30d29ac40cc60aba2df4df195c4144521613840b984e0ebd5e934d2b0"
"0d13b07e813212d170dd5a79b4b1a30b5e345f8a1d14472d40d885c8e55c9406159f5de8909e0b85f923"
"b6290dac61bd6cafcc7f9dba";
template <typename Lazy, typename Object>
void CheckLazy(const Object& point, const Object& other)
{
constexpr bool is_pubkey = std::is_same_v<Lazy, CBLSLazyPublicKey>;
const auto legacy_arr = point.ToBytes(BLSScheme::Legacy);
const auto basic_arr = point.ToBytes(BLSScheme::Basic);
const auto other_arr = other.ToBytes(is_pubkey ? BLSScheme::Legacy : BLSScheme::Basic);
const std::vector<uint8_t> legacy_bytes(legacy_arr.begin(), legacy_arr.end());
const std::vector<uint8_t> basic_bytes(basic_arr.begin(), basic_arr.end());
const std::vector<uint8_t> other_bytes(other_arr.begin(), other_arr.end());
const std::vector<uint8_t> garbage(Object::SerSize, 0xff);
auto hash_of = [](const std::vector<uint8_t>& bytes) {
HashWriter ss{};
ss.write(MakeByteSpan(bytes));
return ss.GetHash();
};
if constexpr (is_pubkey) {
for (const BLSScheme scheme : {BLSScheme::Legacy, BLSScheme::Basic}) {
Lazy lazy;
DataStream in{garbage};
lazy.Unserialize(in, scheme);
std::vector<unsigned char> out;
VectorWriter writer{out, 0};
BOOST_CHECK_NO_THROW(lazy.Serialize(writer, scheme));
BOOST_CHECK(out == garbage);
Lazy invalid;