forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 720
Expand file tree
/
Copy pathquorums_signing.cpp
More file actions
879 lines (710 loc) · 28.6 KB
/
Copy pathquorums_signing.cpp
File metadata and controls
879 lines (710 loc) · 28.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
// Copyright (c) 2018-2022 The Dash Core developers
// Copyright (c) 2023 The PIVX Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "quorums_signing.h"
#include "clientversion.h"
#include "netaddress.h"
#include "quorums_signing_shares.h"
#include "quorums_utils.h"
#include "activemasternode.h"
#include "bls/bls_batchverifier.h"
#include "cxxtimer.h"
#include "net_processing.h"
#include "validation.h"
#include <algorithm>
#include <limits>
#include <unordered_set>
namespace llmq
{
std::unique_ptr<CSigningManager> quorumSigningManager{nullptr};
CRecoveredSigsDb::CRecoveredSigsDb(CDBWrapper& _db) : db(_db)
{
if (Params().NetworkIDString() == CBaseChainParams::TESTNET) {
// TODO this can be completely removed after some time (when we're pretty sure the conversion has been run on most testnet MNs)
if (db.Exists(std::string("rs_upgraded"))) {
return;
}
ConvertInvalidTimeKeys();
AddVoteTimeKeys();
db.Write(std::string("rs_upgraded"), (uint8_t)1);
}
}
// This converts time values in "rs_t" from host endiannes to big endiannes, which is required to have proper ordering of the keys
void CRecoveredSigsDb::ConvertInvalidTimeKeys()
{
LogPrintf("CRecoveredSigsDb::%s -- converting invalid rs_t keys\n", __func__);
std::unique_ptr<CDBIterator> pcursor(db.NewIterator());
auto start = std::make_tuple(std::string("rs_t"), (uint32_t)0, (uint8_t)0, uint256());
pcursor->Seek(start);
CDBBatch batch(CLIENT_VERSION | ADDRV2_FORMAT);
size_t cnt = 0;
while (pcursor->Valid()) {
decltype(start) k;
if (!pcursor->GetKey(k) || std::get<0>(k) != "rs_t") {
break;
}
batch.Erase(k);
std::get<1>(k) = htobe32(std::get<1>(k));
batch.Write(k, (uint8_t)1);
cnt++;
pcursor->Next();
}
pcursor.reset();
db.WriteBatch(batch);
LogPrintf("CRecoveredSigsDb::%s -- converted %d invalid rs_t keys\n", __func__, cnt);
}
// This adds rs_vt keys for every rs_v entry to the DB. The time in the key is set to the current time.
// This causes cleanup of all these votes a week later.
void CRecoveredSigsDb::AddVoteTimeKeys()
{
LogPrintf("CRecoveredSigsDb::%s -- adding rs_vt keys with current time\n", __func__);
auto curTime = GetAdjustedTime();
std::unique_ptr<CDBIterator> pcursor(db.NewIterator());
auto start = std::make_tuple(std::string("rs_v"), (uint8_t)0, uint256());
pcursor->Seek(start);
CDBBatch batch(CLIENT_VERSION | ADDRV2_FORMAT);
size_t cnt = 0;
while (pcursor->Valid()) {
decltype(start) k;
if (!pcursor->GetKey(k) || std::get<0>(k) != "rs_v") {
break;
}
uint8_t llmqType = std::get<1>(k);
const uint256& id = std::get<2>(k);
auto k2 = std::make_tuple(std::string("rs_vt"), (uint32_t)htobe32(curTime), llmqType, id);
batch.Write(k2, (uint8_t)1);
cnt++;
pcursor->Next();
}
pcursor.reset();
db.WriteBatch(batch);
LogPrintf("CRecoveredSigsDb::%s -- added %d rs_vt entries\n", __func__, cnt);
}
bool CRecoveredSigsDb::HasRecoveredSig(Consensus::LLMQType llmqType, const uint256& id, const uint256& msgHash)
{
auto k = std::make_tuple(std::string("rs_r"), (uint8_t)llmqType, id, msgHash);
return db.Exists(k);
}
bool CRecoveredSigsDb::HasRecoveredSigForId(Consensus::LLMQType llmqType, const uint256& id)
{
auto cacheKey = std::make_pair(llmqType, id);
bool ret;
{
LOCK(cs);
if (hasSigForIdCache.get(cacheKey, ret)) {
return ret;
}
}
auto k = std::make_tuple(std::string("rs_r"), (uint8_t)llmqType, id);
ret = db.Exists(k);
LOCK(cs);
hasSigForIdCache.insert(cacheKey, ret);
return ret;
}
bool CRecoveredSigsDb::HasRecoveredSigForSession(const uint256& signHash)
{
bool ret;
{
LOCK(cs);
if (hasSigForSessionCache.get(signHash, ret)) {
return ret;
}
}
auto k = std::make_tuple(std::string("rs_s"), signHash);
ret = db.Exists(k);
LOCK(cs);
hasSigForSessionCache.insert(signHash, ret);
return ret;
}
bool CRecoveredSigsDb::HasRecoveredSigForHash(const uint256& hash)
{
bool ret;
{
LOCK(cs);
if (hasSigForHashCache.get(hash, ret)) {
return ret;
}
}
auto k = std::make_tuple(std::string("rs_h"), hash);
ret = db.Exists(k);
LOCK(cs);
hasSigForHashCache.insert(hash, ret);
return ret;
}
bool CRecoveredSigsDb::ReadRecoveredSig(Consensus::LLMQType llmqType, const uint256& id, CRecoveredSig& ret)
{
auto k = std::make_tuple(std::string("rs_r"), (uint8_t)llmqType, id);
CDataStream ds(SER_DISK, CLIENT_VERSION);
if (!db.ReadDataStream(k, ds)) {
return false;
}
try {
ret.Unserialize(ds);
return true;
} catch (std::exception&) {
return false;
}
}
bool CRecoveredSigsDb::GetRecoveredSigByHash(const uint256& hash, CRecoveredSig& ret)
{
auto k1 = std::make_tuple(std::string("rs_h"), hash);
std::pair<uint8_t, uint256> k2;
if (!db.Read(k1, k2)) {
return false;
}
return ReadRecoveredSig((Consensus::LLMQType)k2.first, k2.second, ret);
}
bool CRecoveredSigsDb::GetRecoveredSigById(Consensus::LLMQType llmqType, const uint256& id, CRecoveredSig& ret)
{
return ReadRecoveredSig(llmqType, id, ret);
}
void CRecoveredSigsDb::WriteRecoveredSig(const llmq::CRecoveredSig& recSig)
{
CDBBatch batch(CLIENT_VERSION | ADDRV2_FORMAT);
uint32_t curTime = GetAdjustedTime();
// we put these close to each other to leverage leveldb's key compaction
// this way, the second key can be used for fast HasRecoveredSig checks while the first key stores the recSig
auto k1 = std::make_tuple(std::string("rs_r"), recSig.llmqType, recSig.id);
auto k2 = std::make_tuple(std::string("rs_r"), recSig.llmqType, recSig.id, recSig.msgHash);
batch.Write(k1, recSig);
// this key is also used to store the current time, so that we can easily get to the "rs_t" key when we have the id
batch.Write(k2, curTime);
// store by object hash
auto k3 = std::make_tuple(std::string("rs_h"), recSig.GetHash());
batch.Write(k3, std::make_pair(recSig.llmqType, recSig.id));
// store by signHash
auto signHash = llmq::utils::BuildSignHash(recSig);
auto k4 = std::make_tuple(std::string("rs_s"), signHash);
batch.Write(k4, (uint8_t)1);
// store by current time. Allows fast cleanup of old recSigs
auto k5 = std::make_tuple(std::string("rs_t"), (uint32_t)htobe32(curTime), recSig.llmqType, recSig.id);
batch.Write(k5, (uint8_t)1);
db.WriteBatch(batch);
{
int64_t t = GetTimeMillis();
LOCK(cs);
hasSigForIdCache.insert(std::make_pair((Consensus::LLMQType)recSig.llmqType, recSig.id), true);
hasSigForSessionCache.insert(signHash, true);
hasSigForHashCache.insert(recSig.GetHash(), true);
}
}
void CRecoveredSigsDb::RemoveRecoveredSig(CDBBatch& batch, Consensus::LLMQType llmqType, const uint256& id, bool deleteHashKey, bool deleteTimeKey)
{
AssertLockHeld(cs);
CRecoveredSig recSig;
if (!ReadRecoveredSig(llmqType, id, recSig)) {
return;
}
auto signHash = llmq::utils::BuildSignHash(recSig);
auto k1 = std::make_tuple(std::string("rs_r"), recSig.llmqType, recSig.id);
auto k2 = std::make_tuple(std::string("rs_r"), recSig.llmqType, recSig.id, recSig.msgHash);
auto k3 = std::make_tuple(std::string("rs_h"), recSig.GetHash());
auto k4 = std::make_tuple(std::string("rs_s"), signHash);
batch.Erase(k1);
batch.Erase(k2);
if (deleteHashKey) {
batch.Erase(k3);
}
batch.Erase(k4);
if (deleteTimeKey) {
CDataStream writeTimeDs(SER_DISK, CLIENT_VERSION);
// TODO remove the size() == sizeof(uint32_t) in a future version (when we stop supporting upgrades from < 0.14.1)
if (db.ReadDataStream(k2, writeTimeDs) && writeTimeDs.size() == sizeof(uint32_t)) {
uint32_t writeTime;
writeTimeDs >> writeTime;
auto k5 = std::make_tuple(std::string("rs_t"), (uint32_t)htobe32(writeTime), recSig.llmqType, recSig.id);
batch.Erase(k5);
}
}
hasSigForIdCache.erase(std::make_pair((Consensus::LLMQType)recSig.llmqType, recSig.id));
hasSigForSessionCache.erase(signHash);
if (deleteHashKey) {
hasSigForHashCache.erase(recSig.GetHash());
}
}
// Completely remove any traces of the recovered sig
void CRecoveredSigsDb::RemoveRecoveredSig(Consensus::LLMQType llmqType, const uint256& id)
{
LOCK(cs);
CDBBatch batch(CLIENT_VERSION | ADDRV2_FORMAT);
RemoveRecoveredSig(batch, llmqType, id, true, true);
db.WriteBatch(batch);
}
// Remove the recovered sig itself and all keys required to get from id -> recSig
// This will leave the byHash key in-place so that HasRecoveredSigForHash still returns true
void CRecoveredSigsDb::TruncateRecoveredSig(Consensus::LLMQType llmqType, const uint256& id)
{
LOCK(cs);
CDBBatch batch(CLIENT_VERSION | ADDRV2_FORMAT);
RemoveRecoveredSig(batch, llmqType, id, false, false);
db.WriteBatch(batch);
}
void CRecoveredSigsDb::CleanupOldRecoveredSigs(int64_t maxAge)
{
std::unique_ptr<CDBIterator> pcursor(db.NewIterator());
auto start = std::make_tuple(std::string("rs_t"), (uint32_t)0, (uint8_t)0, uint256());
uint32_t endTime = (uint32_t)(GetAdjustedTime() - maxAge);
pcursor->Seek(start);
std::vector<std::pair<Consensus::LLMQType, uint256>> toDelete;
std::vector<decltype(start)> toDelete2;
while (pcursor->Valid()) {
decltype(start) k;
if (!pcursor->GetKey(k) || std::get<0>(k) != "rs_t") {
break;
}
if (be32toh(std::get<1>(k)) >= endTime) {
break;
}
toDelete.emplace_back((Consensus::LLMQType)std::get<2>(k), std::get<3>(k));
toDelete2.emplace_back(k);
pcursor->Next();
}
pcursor.reset();
if (toDelete.empty()) {
return;
}
CDBBatch batch(CLIENT_VERSION | ADDRV2_FORMAT);
{
LOCK(cs);
for (auto& e : toDelete) {
RemoveRecoveredSig(batch, e.first, e.second, true, false);
if (batch.SizeEstimate() >= (1 << 24)) {
db.WriteBatch(batch);
batch.Clear();
}
}
}
for (auto& e : toDelete2) {
batch.Erase(e);
}
db.WriteBatch(batch);
LogPrint(BCLog::LLMQ, "CRecoveredSigsDb::%d -- deleted %d entries\n", __func__, toDelete.size());
}
bool CRecoveredSigsDb::HasVotedOnId(Consensus::LLMQType llmqType, const uint256& id)
{
auto k = std::make_tuple(std::string("rs_v"), (uint8_t)llmqType, id);
return db.Exists(k);
}
bool CRecoveredSigsDb::GetVoteForId(Consensus::LLMQType llmqType, const uint256& id, uint256& msgHashRet)
{
auto k = std::make_tuple(std::string("rs_v"), (uint8_t)llmqType, id);
return db.Read(k, msgHashRet);
}
void CRecoveredSigsDb::WriteVoteForId(Consensus::LLMQType llmqType, const uint256& id, const uint256& msgHash)
{
auto k1 = std::make_tuple(std::string("rs_v"), (uint8_t)llmqType, id);
auto k2 = std::make_tuple(std::string("rs_vt"), (uint32_t)htobe32(GetAdjustedTime()), (uint8_t)llmqType, id);
CDBBatch batch(CLIENT_VERSION | ADDRV2_FORMAT);
batch.Write(k1, msgHash);
batch.Write(k2, (uint8_t)1);
db.WriteBatch(batch);
}
void CRecoveredSigsDb::CleanupOldVotes(int64_t maxAge)
{
std::unique_ptr<CDBIterator> pcursor(db.NewIterator());
auto start = std::make_tuple(std::string("rs_vt"), (uint32_t)0, (uint8_t)0, uint256());
uint32_t endTime = (uint32_t)(GetAdjustedTime() - maxAge);
pcursor->Seek(start);
CDBBatch batch(CLIENT_VERSION | ADDRV2_FORMAT);
size_t cnt = 0;
while (pcursor->Valid()) {
decltype(start) k;
if (!pcursor->GetKey(k) || std::get<0>(k) != "rs_vt") {
break;
}
if (be32toh(std::get<1>(k)) >= endTime) {
break;
}
uint8_t llmqType = std::get<2>(k);
const uint256& id = std::get<3>(k);
batch.Erase(k);
batch.Erase(std::make_tuple(std::string("rs_v"), llmqType, id));
cnt++;
pcursor->Next();
}
pcursor.reset();
if (cnt == 0) {
return;
}
db.WriteBatch(batch);
LogPrint(BCLog::LLMQ, "CRecoveredSigsDb::%d -- deleted %d entries\n", __func__, cnt);
}
//////////////////
CSigningManager::CSigningManager(CDBWrapper& llmqDb, bool fMemory) : db(llmqDb)
{
}
bool CSigningManager::AlreadyHave(const CInv& inv)
{
if (inv.type != MSG_QUORUM_RECOVERED_SIG) {
return false;
}
return db.HasRecoveredSigForHash(inv.hash);
}
bool CSigningManager::GetRecoveredSigForGetData(const uint256& hash, CRecoveredSig& ret)
{
if (!db.GetRecoveredSigByHash(hash, ret)) {
return false;
}
if (!llmq::utils::IsQuorumActive((Consensus::LLMQType)(ret.llmqType), ret.quorumHash)) {
// we don't want to propagate sigs from inactive quorums
return false;
}
return true;
}
void CSigningManager::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman)
{
if (strCommand == NetMsgType::QSIGREC) {
CRecoveredSig recoveredSig;
vRecv >> recoveredSig;
ProcessMessageRecoveredSig(pfrom, recoveredSig, connman);
}
}
void CSigningManager::ProcessMessageRecoveredSig(CNode* pfrom, const CRecoveredSig& recoveredSig, CConnman& connman)
{
bool ban = false;
if (!PreVerifyRecoveredSig(pfrom->GetId(), recoveredSig, ban)) {
if (ban) {
LOCK(cs_main);
Misbehaving(pfrom->GetId(), 100);
}
return;
}
// It's important to only skip seen *valid* sig shares here. See comment for CBatchedSigShare
// We don't receive recovered sigs in batches, but we do batched verification per node on these
if (db.HasRecoveredSigForHash(recoveredSig.GetHash())) {
return;
}
LogPrint(BCLog::LLMQ, "CSigningManager::%s -- signHash=%s, id=%s, msgHash=%s, node=%d\n", __func__,
llmq::utils::BuildSignHash(recoveredSig).ToString(), recoveredSig.id.ToString(), recoveredSig.msgHash.ToString(), pfrom->GetId());
LOCK(cs);
pendingRecoveredSigs[pfrom->GetId()].emplace_back(recoveredSig);
}
bool CSigningManager::PreVerifyRecoveredSig(NodeId nodeId, const CRecoveredSig& recoveredSig, bool& retBan)
{
retBan = false;
auto llmqType = (Consensus::LLMQType)recoveredSig.llmqType;
if (!Params().GetConsensus().llmqs.count(llmqType)) {
retBan = true;
return false;
}
CQuorumCPtr quorum = quorumManager->GetQuorum(llmqType, recoveredSig.quorumHash);
if (!quorum) {
LogPrint(BCLog::LLMQ, "CSigningManager::%s -- quorum %s not found, node=%d\n", __func__,
recoveredSig.quorumHash.ToString(), nodeId);
return false;
}
if (!llmq::utils::IsQuorumActive(llmqType, quorum->qc.quorumHash)) {
return false;
}
return true;
}
void CSigningManager::CollectPendingRecoveredSigsToVerify(
size_t maxUniqueSessions,
std::unordered_map<NodeId, std::list<CRecoveredSig>>& retSigShares,
std::unordered_map<std::pair<Consensus::LLMQType, uint256>, CQuorumCPtr, StaticSaltedHasher>& retQuorums)
{
{
LOCK(cs);
if (pendingRecoveredSigs.empty()) {
return;
}
std::unordered_set<std::pair<NodeId, uint256>, StaticSaltedHasher> uniqueSignHashes;
llmq::utils::IterateNodesRandom(pendingRecoveredSigs, [&]() { return uniqueSignHashes.size() < maxUniqueSessions; }, [&](NodeId nodeId, std::list<CRecoveredSig>& ns) {
if (ns.empty()) {
return false;
}
auto& recSig = *ns.begin();
bool alreadyHave = db.HasRecoveredSigForHash(recSig.GetHash());
if (!alreadyHave) {
uniqueSignHashes.emplace(nodeId, llmq::utils::BuildSignHash(recSig));
retSigShares[nodeId].emplace_back(recSig);
}
ns.erase(ns.begin());
return !ns.empty(); }, rnd);
if (retSigShares.empty()) {
return;
}
}
for (auto& p : retSigShares) {
NodeId nodeId = p.first;
auto& v = p.second;
for (auto it = v.begin(); it != v.end();) {
auto& recSig = *it;
Consensus::LLMQType llmqType = (Consensus::LLMQType)recSig.llmqType;
auto quorumKey = std::make_pair((Consensus::LLMQType)recSig.llmqType, recSig.quorumHash);
if (!retQuorums.count(quorumKey)) {
CQuorumCPtr quorum = quorumManager->GetQuorum(llmqType, recSig.quorumHash);
if (!quorum) {
LogPrint(BCLog::LLMQ, "CSigningManager::%s -- quorum %s not found, node=%d\n", __func__,
recSig.quorumHash.ToString(), nodeId);
it = v.erase(it);
continue;
}
if (!llmq::utils::IsQuorumActive(llmqType, quorum->qc.quorumHash)) {
LogPrint(BCLog::LLMQ, "CSigningManager::%s -- quorum %s not active anymore, node=%d\n", __func__,
recSig.quorumHash.ToString(), nodeId);
it = v.erase(it);
continue;
}
retQuorums.emplace(quorumKey, quorum);
}
++it;
}
}
}
bool CSigningManager::ProcessPendingRecoveredSigs(CConnman& connman)
{
std::unordered_map<NodeId, std::list<CRecoveredSig>> recSigsByNode;
std::unordered_map<std::pair<Consensus::LLMQType, uint256>, CQuorumCPtr, StaticSaltedHasher> quorums;
CollectPendingRecoveredSigsToVerify(32, recSigsByNode, quorums);
if (recSigsByNode.empty()) {
return false;
}
// It's ok to perform insecure batched verification here as we verify against the quorum public keys, which are not
// craftable by individual entities, making the rogue public key attack impossible
CBLSBatchVerifier<NodeId, uint256> batchVerifier(false, false);
size_t verifyCount = 0;
for (auto& p : recSigsByNode) {
NodeId nodeId = p.first;
auto& v = p.second;
for (auto& recSig : v) {
// we didn't verify the lazy signature until now
if (!recSig.sig.Get().IsValid()) {
batchVerifier.badSources.emplace(nodeId);
break;
}
const auto& quorum = quorums.at(std::make_pair((Consensus::LLMQType)recSig.llmqType, recSig.quorumHash));
batchVerifier.PushMessage(nodeId, recSig.GetHash(), llmq::utils::BuildSignHash(recSig), recSig.sig.Get(), quorum->qc.quorumPublicKey);
verifyCount++;
}
}
cxxtimer::Timer verifyTimer(true);
batchVerifier.Verify();
verifyTimer.stop();
LogPrint(BCLog::LLMQ, "CSigningManager::%s -- verified recovered sig(s). count=%d, vt=%d, nodes=%d\n", __func__, verifyCount, verifyTimer.count(), recSigsByNode.size());
std::unordered_set<uint256, StaticSaltedHasher> processed;
for (auto& p : recSigsByNode) {
NodeId nodeId = p.first;
auto& v = p.second;
if (batchVerifier.badSources.count(nodeId)) {
LOCK(cs_main);
LogPrintf("CSigningManager::%s -- invalid recSig from other node, banning peer=%d\n", __func__, nodeId);
Misbehaving(nodeId, 100);
continue;
}
for (auto& recSig : v) {
if (!processed.emplace(recSig.GetHash()).second) {
continue;
}
const auto& quorum = quorums.at(std::make_pair((Consensus::LLMQType)recSig.llmqType, recSig.quorumHash));
ProcessRecoveredSig(nodeId, recSig, quorum, connman);
}
}
return true;
}
// signature must be verified already
void CSigningManager::ProcessRecoveredSig(NodeId nodeId, const CRecoveredSig& recoveredSig, const CQuorumCPtr& quorum, CConnman& connman)
{
auto llmqType = (Consensus::LLMQType)recoveredSig.llmqType;
{
LOCK(cs_main);
connman.RemoveAskFor(recoveredSig.GetHash(), MSG_QUORUM_RECOVERED_SIG);
}
if (db.HasRecoveredSigForHash(recoveredSig.GetHash())) {
return;
}
std::vector<CRecoveredSigsListener*> listeners;
{
LOCK(cs);
listeners = recoveredSigsListeners;
auto signHash = llmq::utils::BuildSignHash(recoveredSig);
LogPrint(BCLog::LLMQ, "CSigningManager::%s -- valid recSig. signHash=%s, id=%s, msgHash=%s, node=%d\n", __func__,
signHash.ToString(), recoveredSig.id.ToString(), recoveredSig.msgHash.ToString(), nodeId);
if (db.HasRecoveredSigForId(llmqType, recoveredSig.id)) {
CRecoveredSig otherRecoveredSig;
if (db.GetRecoveredSigById(llmqType, recoveredSig.id, otherRecoveredSig)) {
auto otherSignHash = llmq::utils::BuildSignHash(recoveredSig);
if (signHash != otherSignHash) {
// this should really not happen, as each masternode is participating in only one vote,
// even if it's a member of multiple quorums. so a majority is only possible on one quorum and one msgHash per id
LogPrintf("CSigningManager::%s -- conflicting recoveredSig for signHash=%s, id=%s, msgHash=%s, otherSignHash=%s\n", __func__,
signHash.ToString(), recoveredSig.id.ToString(), recoveredSig.msgHash.ToString(), otherSignHash.ToString());
} else {
// Looks like we're trying to process a recSig that is already known. This might happen if the same
// recSig comes in through regular QRECSIG messages and at the same time through some other message
// which allowed to reconstruct a recSig (e.g. IXLOCK). In this case, just bail out.
}
return;
} else {
// This case is very unlikely. It can only happen when cleanup caused this specific recSig to vanish
// between the HasRecoveredSigForId and GetRecoveredSigById call. If that happens, treat it as if we
// never had that recSig
}
}
db.WriteRecoveredSig(recoveredSig);
}
CInv inv(MSG_QUORUM_RECOVERED_SIG, recoveredSig.GetHash());
g_connman->ForEachNode([&](CNode* pnode) {
if (pnode->nVersion >= LLMQS_PROTO_VERSION && pnode->m_wants_recsigs && pnode->CanRelay()) {
pnode->PushInventory(inv);
}
});
for (auto& l : listeners) {
l->HandleNewRecoveredSig(recoveredSig);
}
}
void CSigningManager::TruncateRecoveredSig(Consensus::LLMQType llmqType, const uint256& id)
{
db.TruncateRecoveredSig(llmqType, id);
}
void CSigningManager::Cleanup()
{
int64_t now = GetTimeMillis();
if (now - lastCleanupTime < 5000) {
return;
}
int64_t maxAge = DEFAULT_MAX_RECOVERED_SIGS_AGE;
db.CleanupOldRecoveredSigs(maxAge);
db.CleanupOldVotes(maxAge);
lastCleanupTime = GetTimeMillis();
}
void CSigningManager::RegisterRecoveredSigsListener(CRecoveredSigsListener* l)
{
LOCK(cs);
recoveredSigsListeners.emplace_back(l);
}
void CSigningManager::UnregisterRecoveredSigsListener(CRecoveredSigsListener* l)
{
LOCK(cs);
auto itRem = std::remove(recoveredSigsListeners.begin(), recoveredSigsListeners.end(), l);
recoveredSigsListeners.erase(itRem, recoveredSigsListeners.end());
}
bool CSigningManager::AsyncSignIfMember(Consensus::LLMQType llmqType, const uint256& id, const uint256& msgHash, bool allowReSign)
{
auto& params = Params().GetConsensus().llmqs.at(llmqType);
if (!activeMasternodeManager) {
return false;
}
{
LOCK(cs);
bool hasVoted = db.HasVotedOnId(llmqType, id);
if (hasVoted) {
uint256 prevMsgHash;
db.GetVoteForId(llmqType, id, prevMsgHash);
if (msgHash != prevMsgHash) {
LogPrintf("CSigningManager::%s -- already voted for id=%s and msgHash=%s. Not voting on conflicting msgHash=%s\n", __func__,
id.ToString(), prevMsgHash.ToString(), msgHash.ToString());
return false;
} else if (allowReSign) {
LogPrint(BCLog::LLMQ, "CSigningManager::%s -- already voted for id=%s and msgHash=%s. Resigning!\n", __func__,
id.ToString(), prevMsgHash.ToString());
} else {
LogPrint(BCLog::LLMQ, "CSigningManager::%s -- already voted for id=%s and msgHash=%s. Not voting again.\n", __func__,
id.ToString(), prevMsgHash.ToString());
return false;
}
}
if (db.HasRecoveredSigForId(llmqType, id)) {
// no need to sign it if we already have a recovered sig
return true;
}
if (!hasVoted) {
db.WriteVoteForId(llmqType, id, msgHash);
}
}
// This might end up giving different results on different members
// This might happen when we are on the brink of confirming a new quorum
// This gives a slight risk of not getting enough shares to recover a signature
// But at least it shouldn't be possible to get conflicting recovered signatures
// TODO fix this by re-signing when the next block arrives, but only when that block results in a change of the quorum list and no recovered signature has been created in the mean time
CQuorumCPtr quorum = SelectQuorumForSigning(llmqType, id);
if (!quorum) {
LogPrint(BCLog::LLMQ, "CSigningManager::%s -- failed to select quorum. id=%s, msgHash=%s\n", __func__, id.ToString(), msgHash.ToString());
return false;
}
if (!quorum->IsValidMember(activeMasternodeManager->GetProTx())) {
return false;
}
if (allowReSign) {
// make us re-announce all known shares (other nodes might have run into a timeout)
quorumSigSharesManager->ForceReAnnouncement(quorum, llmqType, id, msgHash);
}
quorumSigSharesManager->AsyncSign(quorum, id, msgHash);
return true;
}
bool CSigningManager::HasRecoveredSig(Consensus::LLMQType llmqType, const uint256& id, const uint256& msgHash)
{
return db.HasRecoveredSig(llmqType, id, msgHash);
}
bool CSigningManager::HasRecoveredSigForId(Consensus::LLMQType llmqType, const uint256& id)
{
return db.HasRecoveredSigForId(llmqType, id);
}
bool CSigningManager::HasRecoveredSigForSession(const uint256& signHash)
{
return db.HasRecoveredSigForSession(signHash);
}
bool CSigningManager::IsConflicting(Consensus::LLMQType llmqType, const uint256& id, const uint256& msgHash)
{
if (!db.HasRecoveredSigForId(llmqType, id)) {
// no recovered sig present, so no conflict
return false;
}
if (!db.HasRecoveredSig(llmqType, id, msgHash)) {
// recovered sig is present, but not for the given msgHash. That's a conflict!
return true;
}
// all good
return false;
}
bool CSigningManager::HasVotedOnId(Consensus::LLMQType llmqType, const uint256& id)
{
return db.HasVotedOnId(llmqType, id);
}
bool CSigningManager::GetVoteForId(Consensus::LLMQType llmqType, const uint256& id, uint256& msgHashRet)
{
return db.GetVoteForId(llmqType, id, msgHashRet);
}
CQuorumCPtr CSigningManager::SelectQuorumForSigning(Consensus::LLMQType llmqType, const uint256& selectionHash, int signHeight, int signOffset)
{
auto& llmqParams = Params().GetConsensus().llmqs.at(llmqType);
size_t poolSize = (size_t)llmqParams.signingActiveQuorumCount;
CBlockIndex* pindexStart;
{
LOCK(cs_main);
if (signHeight == -1) {
signHeight = chainActive.Height();
}
int startBlockHeight = signHeight - signOffset;
if (startBlockHeight > chainActive.Height()) {
return {};
}
pindexStart = chainActive[startBlockHeight];
}
auto quorums = quorumManager->ScanQuorums(llmqType, pindexStart, poolSize);
if (quorums.empty()) {
return nullptr;
}
std::vector<std::pair<uint256, size_t>> scores;
scores.reserve(quorums.size());
for (size_t i = 0; i < quorums.size(); i++) {
CHashWriter h(SER_NETWORK, 0);
h << (uint8_t)llmqType;
h << quorums[i]->qc.quorumHash;
h << selectionHash;
scores.emplace_back(h.GetHash(), i);
}
std::sort(scores.begin(), scores.end());
return quorums[scores.front().second];
}
bool CSigningManager::VerifyRecoveredSig(Consensus::LLMQType llmqType, int signedAtHeight, const uint256& id, const uint256& msgHash, const CBLSSignature& sig)
{
auto quorum = SelectQuorumForSigning(llmqType, id, signedAtHeight);
if (!quorum) {
return false;
}
uint256 signHash = llmq::utils::BuildSignHash(llmqType, quorum->qc.quorumHash, id, msgHash);
return sig.VerifyInsecure(quorum->qc.quorumPublicKey, signHash);
}
} // namespace llmq