forked from bitcoin/bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathinstantsend.cpp
1653 lines (1394 loc) · 58.8 KB
/
instantsend.cpp
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 <llmq/instantsend.h>
#include <llmq/chainlocks.h>
#include <llmq/commitment.h>
#include <llmq/quorums.h>
#include <llmq/signing_shares.h>
#include <bls/bls_batchverifier.h>
#include <chainparams.h>
#include <consensus/validation.h>
#include <dbwrapper.h>
#include <index/txindex.h>
#include <masternode/sync.h>
#include <net_processing.h>
#include <node/blockstorage.h>
#include <spork.h>
#include <txmempool.h>
#include <util/irange.h>
#include <util/ranges.h>
#include <util/thread.h>
#include <validation.h>
#include <stats/client.h>
#include <cxxtimer.hpp>
namespace llmq
{
static const std::string_view INPUTLOCK_REQUESTID_PREFIX = "inlock";
static const std::string_view ISLOCK_REQUESTID_PREFIX = "islock";
static const std::string_view DB_ISLOCK_BY_HASH = "is_i";
static const std::string_view DB_HASH_BY_TXID = "is_tx";
static const std::string_view DB_HASH_BY_OUTPOINT = "is_in";
static const std::string_view DB_MINED_BY_HEIGHT_AND_HASH = "is_m";
static const std::string_view DB_ARCHIVED_BY_HEIGHT_AND_HASH = "is_a1";
static const std::string_view DB_ARCHIVED_BY_HASH = "is_a2";
static const std::string_view DB_VERSION = "is_v";
uint256 CInstantSendLock::GetRequestId() const
{
CHashWriter hw(SER_GETHASH, 0);
hw << ISLOCK_REQUESTID_PREFIX;
hw << inputs;
return hw.GetHash();
}
////////////////
CInstantSendDb::CInstantSendDb(bool unitTests, bool fWipe) :
db(std::make_unique<CDBWrapper>(unitTests ? "" : (gArgs.GetDataDirNet() / "llmq/isdb"), 32 << 20, unitTests, fWipe))
{
Upgrade(unitTests);
}
CInstantSendDb::~CInstantSendDb() = default;
void CInstantSendDb::Upgrade(bool unitTests)
{
LOCK(cs_db);
int v{0};
if (!db->Read(DB_VERSION, v) || v < CInstantSendDb::CURRENT_VERSION) {
// Wipe db
db.reset();
db = std::make_unique<CDBWrapper>(unitTests ? "" : (gArgs.GetDataDirNet() / "llmq/isdb"), 32 << 20, unitTests,
/*fWipe=*/true);
CDBBatch batch(*db);
batch.Write(DB_VERSION, CInstantSendDb::CURRENT_VERSION);
// Sync DB changes to disk
db->WriteBatch(batch, /*fSync=*/true);
batch.Clear();
}
}
void CInstantSendDb::WriteNewInstantSendLock(const uint256& hash, const CInstantSendLock& islock)
{
LOCK(cs_db);
CDBBatch batch(*db);
batch.Write(std::make_tuple(DB_ISLOCK_BY_HASH, hash), islock);
batch.Write(std::make_tuple(DB_HASH_BY_TXID, islock.txid), hash);
for (const auto& in : islock.inputs) {
batch.Write(std::make_tuple(DB_HASH_BY_OUTPOINT, in), hash);
}
db->WriteBatch(batch);
islockCache.insert(hash, std::make_shared<CInstantSendLock>(islock));
txidCache.insert(islock.txid, hash);
for (const auto& in : islock.inputs) {
outpointCache.insert(in, hash);
}
}
void CInstantSendDb::RemoveInstantSendLock(CDBBatch& batch, const uint256& hash, CInstantSendLockPtr islock, bool keep_cache)
{
AssertLockHeld(cs_db);
if (!islock) {
islock = GetInstantSendLockByHashInternal(hash, false);
if (!islock) {
return;
}
}
batch.Erase(std::make_tuple(DB_ISLOCK_BY_HASH, hash));
batch.Erase(std::make_tuple(DB_HASH_BY_TXID, islock->txid));
for (auto& in : islock->inputs) {
batch.Erase(std::make_tuple(DB_HASH_BY_OUTPOINT, in));
}
if (!keep_cache) {
islockCache.erase(hash);
txidCache.erase(islock->txid);
for (const auto& in : islock->inputs) {
outpointCache.erase(in);
}
}
}
static std::tuple<std::string, uint32_t, uint256> BuildInversedISLockKey(std::string_view k, int nHeight, const uint256& islockHash)
{
return std::make_tuple(std::string{k}, htobe32_internal(std::numeric_limits<uint32_t>::max() - nHeight), islockHash);
}
void CInstantSendDb::WriteInstantSendLockMined(const uint256& hash, int nHeight)
{
LOCK(cs_db);
CDBBatch batch(*db);
WriteInstantSendLockMined(batch, hash, nHeight);
db->WriteBatch(batch);
}
void CInstantSendDb::WriteInstantSendLockMined(CDBBatch& batch, const uint256& hash, int nHeight)
{
AssertLockHeld(cs_db);
batch.Write(BuildInversedISLockKey(DB_MINED_BY_HEIGHT_AND_HASH, nHeight, hash), true);
}
void CInstantSendDb::RemoveInstantSendLockMined(CDBBatch& batch, const uint256& hash, int nHeight)
{
AssertLockHeld(cs_db);
batch.Erase(BuildInversedISLockKey(DB_MINED_BY_HEIGHT_AND_HASH, nHeight, hash));
}
void CInstantSendDb::WriteInstantSendLockArchived(CDBBatch& batch, const uint256& hash, int nHeight)
{
AssertLockHeld(cs_db);
batch.Write(BuildInversedISLockKey(DB_ARCHIVED_BY_HEIGHT_AND_HASH, nHeight, hash), true);
batch.Write(std::make_tuple(DB_ARCHIVED_BY_HASH, hash), true);
}
std::unordered_map<uint256, CInstantSendLockPtr, StaticSaltedHasher> CInstantSendDb::RemoveConfirmedInstantSendLocks(int nUntilHeight)
{
LOCK(cs_db);
if (nUntilHeight <= best_confirmed_height) {
LogPrint(BCLog::ALL, "CInstantSendDb::%s -- Attempting to confirm height %d, however we've already confirmed height %d. This should never happen.\n", __func__,
nUntilHeight, best_confirmed_height);
return {};
}
best_confirmed_height = nUntilHeight;
auto it = std::unique_ptr<CDBIterator>(db->NewIterator());
auto firstKey = BuildInversedISLockKey(DB_MINED_BY_HEIGHT_AND_HASH, nUntilHeight, uint256());
it->Seek(firstKey);
CDBBatch batch(*db);
std::unordered_map<uint256, CInstantSendLockPtr, StaticSaltedHasher> ret;
while (it->Valid()) {
decltype(firstKey) curKey;
if (!it->GetKey(curKey) || std::get<0>(curKey) != DB_MINED_BY_HEIGHT_AND_HASH) {
break;
}
uint32_t nHeight = std::numeric_limits<uint32_t>::max() - be32toh_internal(std::get<1>(curKey));
if (nHeight > uint32_t(nUntilHeight)) {
break;
}
auto& islockHash = std::get<2>(curKey);
if (auto islock = GetInstantSendLockByHashInternal(islockHash, false)) {
RemoveInstantSendLock(batch, islockHash, islock);
ret.try_emplace(islockHash, std::move(islock));
}
// archive the islock hash, so that we're still able to check if we've seen the islock in the past
WriteInstantSendLockArchived(batch, islockHash, nHeight);
batch.Erase(curKey);
it->Next();
}
db->WriteBatch(batch);
return ret;
}
void CInstantSendDb::RemoveArchivedInstantSendLocks(int nUntilHeight)
{
LOCK(cs_db);
if (nUntilHeight <= 0) {
return;
}
auto it = std::unique_ptr<CDBIterator>(db->NewIterator());
auto firstKey = BuildInversedISLockKey(DB_ARCHIVED_BY_HEIGHT_AND_HASH, nUntilHeight, uint256());
it->Seek(firstKey);
CDBBatch batch(*db);
while (it->Valid()) {
decltype(firstKey) curKey;
if (!it->GetKey(curKey) || std::get<0>(curKey) != DB_ARCHIVED_BY_HEIGHT_AND_HASH) {
break;
}
uint32_t nHeight = std::numeric_limits<uint32_t>::max() - be32toh_internal(std::get<1>(curKey));
if (nHeight > uint32_t(nUntilHeight)) {
break;
}
auto& islockHash = std::get<2>(curKey);
batch.Erase(std::make_tuple(DB_ARCHIVED_BY_HASH, islockHash));
batch.Erase(curKey);
it->Next();
}
db->WriteBatch(batch);
}
void CInstantSendDb::WriteBlockInstantSendLocks(const gsl::not_null<std::shared_ptr<const CBlock>>& pblock,
gsl::not_null<const CBlockIndex*> pindexConnected)
{
LOCK(cs_db);
CDBBatch batch(*db);
for (const auto& tx : pblock->vtx) {
if (tx->IsCoinBase() || tx->vin.empty()) {
// coinbase and TXs with no inputs can't be locked
continue;
}
uint256 islockHash = GetInstantSendLockHashByTxidInternal(tx->GetHash());
// update DB about when an IS lock was mined
if (!islockHash.IsNull()) {
WriteInstantSendLockMined(batch, islockHash, pindexConnected->nHeight);
}
}
db->WriteBatch(batch);
}
void CInstantSendDb::RemoveBlockInstantSendLocks(const gsl::not_null<std::shared_ptr<const CBlock>>& pblock, gsl::not_null<const CBlockIndex*> pindexDisconnected)
{
LOCK(cs_db);
CDBBatch batch(*db);
for (const auto& tx : pblock->vtx) {
if (tx->IsCoinBase() || tx->vin.empty()) {
// coinbase and TXs with no inputs can't be locked
continue;
}
uint256 islockHash = GetInstantSendLockHashByTxidInternal(tx->GetHash());
if (!islockHash.IsNull()) {
RemoveInstantSendLockMined(batch, islockHash, pindexDisconnected->nHeight);
}
}
db->WriteBatch(batch);
}
bool CInstantSendDb::KnownInstantSendLock(const uint256& islockHash) const
{
LOCK(cs_db);
return GetInstantSendLockByHashInternal(islockHash) != nullptr || db->Exists(std::make_tuple(DB_ARCHIVED_BY_HASH, islockHash));
}
size_t CInstantSendDb::GetInstantSendLockCount() const
{
LOCK(cs_db);
auto it = std::unique_ptr<CDBIterator>(db->NewIterator());
auto firstKey = std::make_tuple(std::string{DB_ISLOCK_BY_HASH}, uint256());
it->Seek(firstKey);
size_t cnt = 0;
while (it->Valid()) {
decltype(firstKey) curKey;
if (!it->GetKey(curKey) || std::get<0>(curKey) != DB_ISLOCK_BY_HASH) {
break;
}
cnt++;
it->Next();
}
return cnt;
}
CInstantSendLockPtr CInstantSendDb::GetInstantSendLockByHashInternal(const uint256& hash, bool use_cache) const
{
AssertLockHeld(cs_db);
if (hash.IsNull()) {
return nullptr;
}
CInstantSendLockPtr ret;
if (use_cache && islockCache.get(hash, ret)) {
return ret;
}
ret = std::make_shared<CInstantSendLock>();
bool exists = db->Read(std::make_tuple(DB_ISLOCK_BY_HASH, hash), *ret);
if (!exists || (::SerializeHash(*ret) != hash)) {
ret = std::make_shared<CInstantSendLock>();
exists = db->Read(std::make_tuple(DB_ISLOCK_BY_HASH, hash), *ret);
if (!exists || (::SerializeHash(*ret) != hash)) {
ret = nullptr;
}
}
islockCache.insert(hash, ret);
return ret;
}
uint256 CInstantSendDb::GetInstantSendLockHashByTxidInternal(const uint256& txid) const
{
AssertLockHeld(cs_db);
uint256 islockHash;
if (!txidCache.get(txid, islockHash)) {
if (!db->Read(std::make_tuple(DB_HASH_BY_TXID, txid), islockHash)) {
return {};
}
txidCache.insert(txid, islockHash);
}
return islockHash;
}
CInstantSendLockPtr CInstantSendDb::GetInstantSendLockByTxid(const uint256& txid) const
{
LOCK(cs_db);
return GetInstantSendLockByHashInternal(GetInstantSendLockHashByTxidInternal(txid));
}
CInstantSendLockPtr CInstantSendDb::GetInstantSendLockByInput(const COutPoint& outpoint) const
{
LOCK(cs_db);
uint256 islockHash;
if (!outpointCache.get(outpoint, islockHash)) {
if (!db->Read(std::make_tuple(DB_HASH_BY_OUTPOINT, outpoint), islockHash)) {
return nullptr;
}
outpointCache.insert(outpoint, islockHash);
}
return GetInstantSendLockByHashInternal(islockHash);
}
std::vector<uint256> CInstantSendDb::GetInstantSendLocksByParent(const uint256& parent) const
{
AssertLockHeld(cs_db);
auto it = std::unique_ptr<CDBIterator>(db->NewIterator());
auto firstKey = std::make_tuple(std::string{DB_HASH_BY_OUTPOINT}, COutPoint(parent, 0));
it->Seek(firstKey);
std::vector<uint256> result;
while (it->Valid()) {
decltype(firstKey) curKey;
if (!it->GetKey(curKey) || std::get<0>(curKey) != DB_HASH_BY_OUTPOINT) {
break;
}
const auto& outpoint = std::get<1>(curKey);
if (outpoint.hash != parent) {
break;
}
uint256 islockHash;
if (!it->GetValue(islockHash)) {
break;
}
result.emplace_back(islockHash);
it->Next();
}
return result;
}
std::vector<uint256> CInstantSendDb::RemoveChainedInstantSendLocks(const uint256& islockHash, const uint256& txid, int nHeight)
{
LOCK(cs_db);
std::vector<uint256> result;
std::vector<uint256> stack;
std::unordered_set<uint256, StaticSaltedHasher> added;
stack.emplace_back(txid);
CDBBatch batch(*db);
while (!stack.empty()) {
auto children = GetInstantSendLocksByParent(stack.back());
stack.pop_back();
for (auto& childIslockHash : children) {
auto childIsLock = GetInstantSendLockByHashInternal(childIslockHash, false);
if (!childIsLock) {
continue;
}
RemoveInstantSendLock(batch, childIslockHash, childIsLock, false);
WriteInstantSendLockArchived(batch, childIslockHash, nHeight);
result.emplace_back(childIslockHash);
if (added.emplace(childIsLock->txid).second) {
stack.emplace_back(childIsLock->txid);
}
}
}
RemoveInstantSendLock(batch, islockHash, nullptr, false);
WriteInstantSendLockArchived(batch, islockHash, nHeight);
result.emplace_back(islockHash);
db->WriteBatch(batch);
return result;
}
////////////////
void CInstantSendManager::Start(PeerManager& peerman)
{
// can't start new thread if we have one running already
if (workThread.joinable()) {
assert(false);
}
workThread = std::thread(&util::TraceThread, "isman", [this, &peerman] { WorkThreadMain(peerman); });
sigman.RegisterRecoveredSigsListener(this);
}
void CInstantSendManager::Stop()
{
sigman.UnregisterRecoveredSigsListener(this);
// make sure to call InterruptWorkerThread() first
if (!workInterrupt) {
assert(false);
}
if (workThread.joinable()) {
workThread.join();
}
}
void CInstantSendManager::ProcessTx(const CTransaction& tx, bool fRetroactive, const Consensus::Params& params)
{
if (!m_is_masternode || !IsInstantSendEnabled() || !m_mn_sync.IsBlockchainSynced()) {
return;
}
if (params.llmqTypeDIP0024InstantSend == Consensus::LLMQType::LLMQ_NONE) {
return;
}
if (!CheckCanLock(tx, true, params)) {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: CheckCanLock returned false\n", __func__,
tx.GetHash().ToString());
return;
}
auto conflictingLock = GetConflictingLock(tx);
if (conflictingLock != nullptr) {
auto conflictingLockHash = ::SerializeHash(*conflictingLock);
LogPrintf("CInstantSendManager::%s -- txid=%s: conflicts with islock %s, txid=%s\n", __func__,
tx.GetHash().ToString(), conflictingLockHash.ToString(), conflictingLock->txid.ToString());
return;
}
// Only sign for inlocks or islocks if mempool IS signing is enabled.
// However, if we are processing a tx because it was included in a block we should
// sign even if mempool IS signing is disabled. This allows a ChainLock to happen on this
// block after we retroactively locked all transactions.
if (!IsInstantSendMempoolSigningEnabled() && !fRetroactive) return;
if (!TrySignInputLocks(tx, fRetroactive, params.llmqTypeDIP0024InstantSend, params)) {
return;
}
// We might have received all input locks before we got the corresponding TX. In this case, we have to sign the
// islock now instead of waiting for the input locks.
TrySignInstantSendLock(tx);
}
bool CInstantSendManager::TrySignInputLocks(const CTransaction& tx, bool fRetroactive, Consensus::LLMQType llmqType, const Consensus::Params& params)
{
std::vector<uint256> ids;
ids.reserve(tx.vin.size());
size_t alreadyVotedCount = 0;
for (const auto& in : tx.vin) {
auto id = ::SerializeHash(std::make_pair(INPUTLOCK_REQUESTID_PREFIX, in.prevout));
ids.emplace_back(id);
uint256 otherTxHash;
if (sigman.GetVoteForId(params.llmqTypeDIP0024InstantSend, id, otherTxHash)) {
if (otherTxHash != tx.GetHash()) {
LogPrintf("CInstantSendManager::%s -- txid=%s: input %s is conflicting with previous vote for tx %s\n", __func__,
tx.GetHash().ToString(), in.prevout.ToStringShort(), otherTxHash.ToString());
return false;
}
alreadyVotedCount++;
}
// don't even try the actual signing if any input is conflicting
if (sigman.IsConflicting(params.llmqTypeDIP0024InstantSend, id, tx.GetHash())) {
LogPrintf("CInstantSendManager::%s -- txid=%s: sigman.IsConflicting returned true. id=%s\n", __func__,
tx.GetHash().ToString(), id.ToString());
return false;
}
}
if (!fRetroactive && alreadyVotedCount == ids.size()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: already voted on all inputs, bailing out\n", __func__,
tx.GetHash().ToString());
return true;
}
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: trying to vote on %d inputs\n", __func__,
tx.GetHash().ToString(), tx.vin.size());
for (const auto i : irange::range(tx.vin.size())) {
const auto& in = tx.vin[i];
auto& id = ids[i];
WITH_LOCK(cs_inputReqests, inputRequestIds.emplace(id));
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: trying to vote on input %s with id %s. fRetroactive=%d\n", __func__,
tx.GetHash().ToString(), in.prevout.ToStringShort(), id.ToString(), fRetroactive);
if (sigman.AsyncSignIfMember(llmqType, shareman, id, tx.GetHash(), {}, fRetroactive)) {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: voted on input %s with id %s\n", __func__,
tx.GetHash().ToString(), in.prevout.ToStringShort(), id.ToString());
}
}
return true;
}
bool CInstantSendManager::CheckCanLock(const CTransaction& tx, bool printDebug, const Consensus::Params& params) const
{
if (tx.vin.empty()) {
// can't lock TXs without inputs (e.g. quorum commitments)
return false;
}
return ranges::all_of(tx.vin,
[&](const auto& in) { return CheckCanLock(in.prevout, printDebug, tx.GetHash(), params); });
}
bool CInstantSendManager::CheckCanLock(const COutPoint& outpoint, bool printDebug, const uint256& txHash, const Consensus::Params& params) const
{
int nInstantSendConfirmationsRequired = params.nInstantSendConfirmationsRequired;
if (IsLocked(outpoint.hash)) {
// if prevout was ix locked, allow locking of descendants (no matter if prevout is in mempool or already mined)
return true;
}
auto mempoolTx = mempool.get(outpoint.hash);
if (mempoolTx) {
if (printDebug) {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: parent mempool TX %s is not locked\n", __func__,
txHash.ToString(), outpoint.hash.ToString());
}
return false;
}
uint256 hashBlock;
CTransactionRef tx = GetTransaction(/* block_index */ nullptr, &mempool, outpoint.hash, params, hashBlock);
// this relies on enabled txindex and won't work if we ever try to remove the requirement for txindex for masternodes
if (!tx) {
if (printDebug) {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: failed to find parent TX %s\n", __func__,
txHash.ToString(), outpoint.hash.ToString());
}
return false;
}
const CBlockIndex* pindexMined;
int nTxAge;
{
LOCK(cs_main);
pindexMined = m_chainstate.m_blockman.LookupBlockIndex(hashBlock);
nTxAge = m_chainstate.m_chain.Height() - pindexMined->nHeight + 1;
}
if (nTxAge < nInstantSendConfirmationsRequired && !clhandler.HasChainLock(pindexMined->nHeight, pindexMined->GetBlockHash())) {
if (printDebug) {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: outpoint %s too new and not ChainLocked. nTxAge=%d, nInstantSendConfirmationsRequired=%d\n", __func__,
txHash.ToString(), outpoint.ToStringShort(), nTxAge, nInstantSendConfirmationsRequired);
}
return false;
}
return true;
}
MessageProcessingResult CInstantSendManager::HandleNewRecoveredSig(const CRecoveredSig& recoveredSig)
{
if (!IsInstantSendEnabled()) {
return {};
}
if (Params().GetConsensus().llmqTypeDIP0024InstantSend == Consensus::LLMQType::LLMQ_NONE) {
return {};
}
uint256 txid;
if (LOCK(cs_inputReqests); inputRequestIds.count(recoveredSig.getId())) {
txid = recoveredSig.getMsgHash();
}
if (!txid.IsNull()) {
HandleNewInputLockRecoveredSig(recoveredSig, txid);
} else if (/*isInstantSendLock=*/ WITH_LOCK(cs_creating, return creatingInstantSendLocks.count(recoveredSig.getId()))) {
HandleNewInstantSendLockRecoveredSig(recoveredSig);
}
return {};
}
void CInstantSendManager::HandleNewInputLockRecoveredSig(const CRecoveredSig& recoveredSig, const uint256& txid)
{
if (g_txindex) {
g_txindex->BlockUntilSyncedToCurrentChain();
}
uint256 hashBlock;
CTransactionRef tx = GetTransaction(/* block_index */ nullptr, &mempool, txid, Params().GetConsensus(), hashBlock);
if (!tx) {
return;
}
if (LogAcceptDebug(BCLog::INSTANTSEND)) {
for (const auto& in : tx->vin) {
auto id = ::SerializeHash(std::make_pair(INPUTLOCK_REQUESTID_PREFIX, in.prevout));
if (id == recoveredSig.getId()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: got recovered sig for input %s\n", __func__,
txid.ToString(), in.prevout.ToStringShort());
break;
}
}
}
TrySignInstantSendLock(*tx);
}
void CInstantSendManager::TrySignInstantSendLock(const CTransaction& tx)
{
const auto llmqType = Params().GetConsensus().llmqTypeDIP0024InstantSend;
for (const auto& in : tx.vin) {
auto id = ::SerializeHash(std::make_pair(INPUTLOCK_REQUESTID_PREFIX, in.prevout));
if (!sigman.HasRecoveredSig(llmqType, id, tx.GetHash())) {
return;
}
}
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s: got all recovered sigs, creating CInstantSendLock\n", __func__,
tx.GetHash().ToString());
CInstantSendLock islock;
islock.txid = tx.GetHash();
for (const auto& in : tx.vin) {
islock.inputs.emplace_back(in.prevout);
}
{
const auto &llmq_params_opt = Params().GetLLMQ(llmqType);
assert(llmq_params_opt);
LOCK(cs_main);
const auto dkgInterval = llmq_params_opt->dkgInterval;
const auto quorumHeight = m_chainstate.m_chain.Height() - (m_chainstate.m_chain.Height() % dkgInterval);
islock.cycleHash = m_chainstate.m_chain[quorumHeight]->GetBlockHash();
}
auto id = islock.GetRequestId();
if (sigman.HasRecoveredSigForId(llmqType, id)) {
return;
}
{
LOCK(cs_creating);
auto e = creatingInstantSendLocks.emplace(id, std::move(islock));
if (!e.second) {
return;
}
txToCreatingInstantSendLocks.emplace(tx.GetHash(), &e.first->second);
}
sigman.AsyncSignIfMember(llmqType, shareman, id, tx.GetHash());
}
void CInstantSendManager::HandleNewInstantSendLockRecoveredSig(const llmq::CRecoveredSig& recoveredSig)
{
CInstantSendLockPtr islock;
{
LOCK(cs_creating);
auto it = creatingInstantSendLocks.find(recoveredSig.getId());
if (it == creatingInstantSendLocks.end()) {
return;
}
islock = std::make_shared<CInstantSendLock>(std::move(it->second));
creatingInstantSendLocks.erase(it);
txToCreatingInstantSendLocks.erase(islock->txid);
}
if (islock->txid != recoveredSig.getMsgHash()) {
LogPrintf("CInstantSendManager::%s -- txid=%s: islock conflicts with %s, dropping own version\n", __func__,
islock->txid.ToString(), recoveredSig.getMsgHash().ToString());
return;
}
islock->sig = recoveredSig.sig;
auto hash = ::SerializeHash(*islock);
if (WITH_LOCK(cs_pendingLocks, return pendingInstantSendLocks.count(hash)) || db.KnownInstantSendLock(hash)) {
return;
}
LOCK(cs_pendingLocks);
pendingInstantSendLocks.emplace(hash, std::make_pair(-1, islock));
}
PeerMsgRet CInstantSendManager::ProcessMessage(const CNode& pfrom, PeerManager& peerman, std::string_view msg_type,
CDataStream& vRecv)
{
if (IsInstantSendEnabled() && msg_type == NetMsgType::ISDLOCK) {
const auto islock = std::make_shared<CInstantSendLock>();
vRecv >> *islock;
return ProcessMessageInstantSendLock(pfrom, peerman, islock);
}
return {};
}
bool ShouldReportISLockTiming() {
return g_stats_client->active() || LogAcceptDebug(BCLog::INSTANTSEND);
}
PeerMsgRet CInstantSendManager::ProcessMessageInstantSendLock(const CNode& pfrom, PeerManager& peerman,
const llmq::CInstantSendLockPtr& islock)
{
auto hash = ::SerializeHash(*islock);
WITH_LOCK(::cs_main, peerman.EraseObjectRequest(pfrom.GetId(), CInv(MSG_ISDLOCK, hash)));
if (!islock->TriviallyValid()) {
return tl::unexpected{100};
}
const auto blockIndex = WITH_LOCK(cs_main, return m_chainstate.m_blockman.LookupBlockIndex(islock->cycleHash));
if (blockIndex == nullptr) {
// Maybe we don't have the block yet or maybe some peer spams invalid values for cycleHash
return tl::unexpected{1};
}
// Deterministic islocks MUST use rotation based llmq
auto llmqType = Params().GetConsensus().llmqTypeDIP0024InstantSend;
const auto& llmq_params_opt = Params().GetLLMQ(llmqType);
assert(llmq_params_opt);
if (blockIndex->nHeight % llmq_params_opt->dkgInterval != 0) {
return tl::unexpected{100};
}
if (WITH_LOCK(cs_pendingLocks, return pendingInstantSendLocks.count(hash) || pendingNoTxInstantSendLocks.count(hash))
|| db.KnownInstantSendLock(hash)) {
return {};
}
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s: received islock, peer=%d\n", __func__,
islock->txid.ToString(), hash.ToString(), pfrom.GetId());
if (ShouldReportISLockTiming()) {
auto time_diff = [&] () -> int64_t {
LOCK(cs_timingsTxSeen);
if (auto it = timingsTxSeen.find(islock->txid); it != timingsTxSeen.end()) {
// This is the normal case where we received the TX before the islock
auto diff = GetTimeMillis() - it->second;
timingsTxSeen.erase(it);
return diff;
}
// But if we received the islock and don't know when we got the tx, then say 0, to indicate we received the islock first.
return 0;
}();
::g_stats_client->timing("islock_ms", time_diff);
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock took %dms\n", __func__,
islock->txid.ToString(), time_diff);
}
LOCK(cs_pendingLocks);
pendingInstantSendLocks.emplace(hash, std::make_pair(pfrom.GetId(), islock));
return {};
}
/**
* Handles trivial ISLock verification
* @return returns false if verification failed, otherwise true
*/
bool CInstantSendLock::TriviallyValid() const
{
if (txid.IsNull() || inputs.empty()) {
return false;
}
// Check that each input is unique
std::set<COutPoint> dups;
for (const auto& o : inputs) {
if (!dups.emplace(o).second) {
return false;
}
}
return true;
}
bool CInstantSendManager::ProcessPendingInstantSendLocks(PeerManager& peerman)
{
decltype(pendingInstantSendLocks) pend;
bool fMoreWork{false};
if (!IsInstantSendEnabled()) {
return false;
}
{
LOCK(cs_pendingLocks);
// only process a max 32 locks at a time to avoid duplicate verification of recovered signatures which have been
// verified by CSigningManager in parallel
const size_t maxCount = 32;
// The keys of the removed values are temporaily stored here to avoid invalidating an iterator
std::vector<uint256> removed;
removed.reserve(maxCount);
for (const auto& [islockHash, nodeid_islptr_pair] : pendingInstantSendLocks) {
// Check if we've reached max count
if (pend.size() >= maxCount) {
fMoreWork = true;
break;
}
pend.emplace(islockHash, std::move(nodeid_islptr_pair));
removed.emplace_back(islockHash);
}
for (const auto& islockHash : removed) {
pendingInstantSendLocks.erase(islockHash);
}
}
if (pend.empty()) {
return false;
}
//TODO Investigate if leaving this is ok
auto llmqType = Params().GetConsensus().llmqTypeDIP0024InstantSend;
const auto& llmq_params_opt = Params().GetLLMQ(llmqType);
assert(llmq_params_opt);
const auto& llmq_params = llmq_params_opt.value();
auto dkgInterval = llmq_params.dkgInterval;
// First check against the current active set and don't ban
auto badISLocks = ProcessPendingInstantSendLocks(llmq_params, peerman, /*signOffset=*/0, pend, false);
if (!badISLocks.empty()) {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- doing verification on old active set\n", __func__);
// filter out valid IS locks from "pend"
for (auto it = pend.begin(); it != pend.end(); ) {
if (!badISLocks.count(it->first)) {
it = pend.erase(it);
} else {
++it;
}
}
// Now check against the previous active set and perform banning if this fails
ProcessPendingInstantSendLocks(llmq_params, peerman, dkgInterval, pend, true);
}
return fMoreWork;
}
std::unordered_set<uint256, StaticSaltedHasher> CInstantSendManager::ProcessPendingInstantSendLocks(
const Consensus::LLMQParams& llmq_params, PeerManager& peerman, int signOffset,
const std::unordered_map<uint256, std::pair<NodeId, CInstantSendLockPtr>, StaticSaltedHasher>& pend, bool ban)
{
CBLSBatchVerifier<NodeId, uint256> batchVerifier(false, true, 8);
std::unordered_map<uint256, CRecoveredSig, StaticSaltedHasher> recSigs;
size_t verifyCount = 0;
size_t alreadyVerified = 0;
for (const auto& p : pend) {
const auto& hash = p.first;
auto nodeId = p.second.first;
const auto& islock = p.second.second;
if (batchVerifier.badSources.count(nodeId)) {
continue;
}
if (!islock->sig.Get().IsValid()) {
batchVerifier.badSources.emplace(nodeId);
continue;
}
auto id = islock->GetRequestId();
// no need to verify an ISLOCK if we already have verified the recovered sig that belongs to it
if (sigman.HasRecoveredSig(llmq_params.type, id, islock->txid)) {
alreadyVerified++;
continue;
}
const auto blockIndex = WITH_LOCK(cs_main, return m_chainstate.m_blockman.LookupBlockIndex(islock->cycleHash));
if (blockIndex == nullptr) {
batchVerifier.badSources.emplace(nodeId);
continue;
}
int nSignHeight{-1};
const auto dkgInterval = llmq_params.dkgInterval;
if (blockIndex->nHeight + dkgInterval < m_chainstate.m_chain.Height()) {
nSignHeight = blockIndex->nHeight + dkgInterval - 1;
}
auto quorum = llmq::SelectQuorumForSigning(llmq_params, m_chainstate.m_chain, qman, id, nSignHeight, signOffset);
if (!quorum) {
// should not happen, but if one fails to select, all others will also fail to select
return {};
}
uint256 signHash = BuildSignHash(llmq_params.type, quorum->qc->quorumHash, id, islock->txid);
batchVerifier.PushMessage(nodeId, hash, signHash, islock->sig.Get(), quorum->qc->quorumPublicKey);
verifyCount++;
// We can reconstruct the CRecoveredSig objects from the islock and pass it to the signing manager, which
// avoids unnecessary double-verification of the signature. We however only do this when verification here
// turns out to be good (which is checked further down)
if (!sigman.HasRecoveredSigForId(llmq_params.type, id)) {
recSigs.try_emplace(hash, CRecoveredSig(llmq_params.type, quorum->qc->quorumHash, id, islock->txid, islock->sig));
}
}
cxxtimer::Timer verifyTimer(true);
batchVerifier.Verify();
verifyTimer.stop();
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- verified locks. count=%d, alreadyVerified=%d, vt=%d, nodes=%d\n", __func__,
verifyCount, alreadyVerified, verifyTimer.count(), batchVerifier.GetUniqueSourceCount());
std::unordered_set<uint256, StaticSaltedHasher> badISLocks;
if (ban && !batchVerifier.badSources.empty()) {
LOCK(cs_main);
for (const auto& nodeId : batchVerifier.badSources) {
// Let's not be too harsh, as the peer might simply be unlucky and might have sent us an old lock which
// does not validate anymore due to changed quorums
peerman.Misbehaving(nodeId, 20);
}
}
for (const auto& p : pend) {
const auto& hash = p.first;
auto nodeId = p.second.first;
const auto& islock = p.second.second;
if (batchVerifier.badMessages.count(hash)) {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s: invalid sig in islock, peer=%d\n", __func__,
islock->txid.ToString(), hash.ToString(), nodeId);
badISLocks.emplace(hash);
continue;
}
ProcessInstantSendLock(nodeId, peerman, hash, islock);
// See comment further on top. We pass a reconstructed recovered sig to the signing manager to avoid
// double-verification of the sig.
auto it = recSigs.find(hash);
if (it != recSigs.end()) {
auto recSig = std::make_shared<CRecoveredSig>(std::move(it->second));
if (!sigman.HasRecoveredSigForId(llmq_params.type, recSig->getId())) {
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s: passing reconstructed recSig to signing mgr, peer=%d\n", __func__,
islock->txid.ToString(), hash.ToString(), nodeId);
sigman.PushReconstructedRecoveredSig(recSig);
}
}
}
return badISLocks;
}
void CInstantSendManager::ProcessInstantSendLock(NodeId from, PeerManager& peerman, const uint256& hash,
const CInstantSendLockPtr& islock)
{
LogPrint(BCLog::INSTANTSEND, "CInstantSendManager::%s -- txid=%s, islock=%s: processing islock, peer=%d\n", __func__,
islock->txid.ToString(), hash.ToString(), from);