-
Notifications
You must be signed in to change notification settings - Fork 46
/
witnessvalidation.cpp
1737 lines (1496 loc) · 82.2 KB
/
witnessvalidation.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
// File contains modifications by: The Gulden developers
// All modifications:
// Copyright (c) 2017-2018 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@gmx.com)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#include "validation/validation.h"
#include "validation/witnessvalidation.h"
#include <consensus/validation.h>
#include <witnessutil.h>
#include "timedata.h" // GetAdjustedTime()
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include <boost/foreach.hpp> // reverse_foreach
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/thread.hpp>
#include "alert.h"
CWitViewDB *ppow2witdbview = NULL;
std::shared_ptr<CCoinsViewCache> ppow2witTip = NULL;
SimplifiedWitnessUTXOSet pow2SimplifiedWitnessUTXO;
//fixme: (PHASE5) Can remove this.
int GetPoW2WitnessCoinbaseIndex(const CBlock& block)
{
int commitpos = -1;
if (!block.vtx.empty()) {
for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
if (block.vtx[0]->vout[o].GetType() <= CTxOutType::ScriptLegacyOutput)
{
if (block.vtx[0]->vout[o].output.scriptPubKey.size() == 143 && block.vtx[0]->vout[o].output.scriptPubKey[0] == OP_RETURN && block.vtx[0]->vout[o].output.scriptPubKey[1] == 0x50 && block.vtx[0]->vout[o].output.scriptPubKey[2] == 0x6f && block.vtx[0]->vout[o].output.scriptPubKey[3] == 0x57 && block.vtx[0]->vout[o].output.scriptPubKey[4] == 0xc2 && block.vtx[0]->vout[o].output.scriptPubKey[5] == 0xb2) {
commitpos = o;
}
}
}
}
return commitpos;
}
std::vector<CBlockIndex*> GetTopLevelPoWOrphans(const int64_t nHeight, const uint256& prevHash)
{
LOCK(cs_main);
std::vector<CBlockIndex*> vRet;
for (const auto candidateIter : setBlockIndexCandidates)
{
if (candidateIter->nVersionPoW2Witness == 0)
{
if (candidateIter->nHeight >= nHeight)
{
vRet.push_back(candidateIter);
}
}
}
return vRet;
}
std::vector<CBlockIndex*> GetTopLevelWitnessOrphans(const int64_t nHeight)
{
std::vector<CBlockIndex*> vRet;
// Don't hold up the witness loop if we can't get the lock, it can just check this again next time
TRY_LOCK(cs_main, lockGetOrphans);
if(!lockGetOrphans)
{
return vRet;
}
for (const auto candidateIter : setBlockIndexCandidates)
{
if (candidateIter->nVersionPoW2Witness != 0)
{
if (candidateIter->nHeight >= nHeight)
{
vRet.push_back(candidateIter);
}
}
}
return vRet;
}
CBlockIndex* GetWitnessOrphanForBlock(const int64_t nHeight, const uint256& prevHash, const uint256& powHash)
{
LOCK(cs_main);
for (const auto candidateIter : setBlockIndexCandidates)
{
if (candidateIter->nVersionPoW2Witness != 0)
{
if (candidateIter->nHeight == nHeight && candidateIter->pprev && *candidateIter->pprev->phashBlock == prevHash)
{
if (candidateIter->GetBlockHashLegacy() == powHash)
{
return candidateIter;
}
}
}
}
return NULL;
}
static bool ForceActivateChainStep(CValidationState& state, CChain& currentChain, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, CCoinsViewCache& coinView)
{
AssertLockHeld(cs_main); // Required for ReadBlockFromDisk.
const CBlockIndex *pindexFork = currentChain.FindFork(pindexMostWork);
if (!pindexFork)
{
while (currentChain.Tip() && currentChain.Tip()->nHeight >= pindexMostWork->nHeight - 1)
{
CBlockIndex* pindexNew = currentChain.Tip()->pprev;
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
CBlock& block = *pblock;
if (!ReadBlockFromDisk(block, currentChain.Tip(), chainparams))
return false;
if (DisconnectBlock(block, currentChain.Tip(), coinView) != DISCONNECT_OK)
return false;
currentChain.SetTip(pindexNew);
}
pindexFork = currentChain.FindFork(pindexMostWork);
}
// Disconnect active blocks which are no longer in the best chain.
while (currentChain.Tip() && currentChain.Tip() != pindexFork) {
CBlockIndex* pindexNew = currentChain.Tip()->pprev;
std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
CBlock& block = *pblock;
if (!ReadBlockFromDisk(block, currentChain.Tip(), chainparams))
return false;
if (DisconnectBlock(block, currentChain.Tip(), coinView) != DISCONNECT_OK)
return false;
currentChain.SetTip(pindexNew);
}
// Build list of new blocks to connect.
std::vector<CBlockIndex*> vpindexToConnect;
bool fContinue = true;
int nHeight = pindexFork ? pindexFork->nHeight : -1;
while (fContinue && nHeight != pindexMostWork->nHeight) {
// Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
// a few blocks along the way.
int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
vpindexToConnect.clear();
vpindexToConnect.reserve(nTargetHeight - nHeight);
CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
while (pindexIter && pindexIter->nHeight != nHeight) {
vpindexToConnect.push_back(pindexIter);
pindexIter = pindexIter->pprev;
}
nHeight = nTargetHeight;
// Connect new blocks.
BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
std::shared_ptr<CBlock> pblockConnect = nullptr;
if (pindexConnect != pindexMostWork || !pblock)
{
pblockConnect = std::make_shared<CBlock>();
CBlock& block = *pblockConnect;
if (!ReadBlockFromDisk(block, pindexConnect, chainparams))
return false;
}
bool rv = ConnectBlock(currentChain, pblockConnect?*pblockConnect:*pblock, state, pindexConnect, coinView, chainparams, false, false, false, false);
if (!rv)
return false;
currentChain.SetTip(pindexConnect);
}
}
return true;
}
// pblock is either NULL or a pointer to a CBlock corresponding to pActiveIndex, to bypass loading it again from disk.
bool ForceActivateChain(CBlockIndex* pActivateIndex, std::shared_ptr<const CBlock> pblock, CValidationState& state, const CChainParams& chainparams, CChain& currentChain, CCoinsViewCache& coinView)
{
DO_BENCHMARK("WIT: ForceActivateChain", BCLog::BENCH|BCLog::WITNESS);
CBlockIndex* pindexNewTip = nullptr;
do {
{
LOCK(cs_main);
// Whether we have anything to do at all.
if (pActivateIndex == NULL || pActivateIndex == currentChain.Tip())
return true;
bool fInvalidFound = false;
std::shared_ptr<const CBlock> nullBlockPtr;
if (!ForceActivateChainStep(state, currentChain, chainparams, pActivateIndex, pblock, fInvalidFound, coinView))
return false;
if (fInvalidFound) {
return false;
}
pindexNewTip = currentChain.Tip();
}
// When we reach this point, we switched to a new tip (stored in pindexNewTip).
} while (pindexNewTip != pActivateIndex);
return true;
}
bool ForceActivateChainWithBlockAsTip(CBlockIndex* pActivateIndex, std::shared_ptr<const CBlock> pblock, CValidationState& state, const CChainParams& chainparams, CChain& currentChain, CCoinsViewCache& coinView, CBlockIndex* pnewblockastip)
{
if(!ForceActivateChain(pActivateIndex, pblock, state, chainparams, currentChain, coinView))
return false;
return ForceActivateChain(pnewblockastip, nullptr, state, chainparams, currentChain, coinView);
}
uint64_t expectedWitnessBlockPeriod(uint64_t nWeight, uint64_t networkTotalWeight)
{
if (nWeight == 0 || networkTotalWeight == 0)
return 0;
if (nWeight > networkTotalWeight/100)
nWeight = networkTotalWeight/100;
static const arith_uint256 base = arith_uint256(100000000) * arith_uint256(100000000) * arith_uint256(100000000);
#define BASE(x) (arith_uint256(x)*base)
#define AI(x) arith_uint256(x)
return 100 + std::max(( ((BASE(1)/((BASE(nWeight)/AI(networkTotalWeight))))).GetLow64() * 10 ), (uint64_t)1000);
#undef AI
#undef BASE
}
uint64_t estimatedWitnessBlockPeriod(uint64_t nWeight, uint64_t networkTotalWeight)
{
DO_BENCHMARK("WIT: estimatedWitnessBlockPeriod", BCLog::BENCH|BCLog::WITNESS);
if (nWeight == 0 || networkTotalWeight == 0)
return 0;
if (nWeight > networkTotalWeight/100)
nWeight = networkTotalWeight/100;
static const arith_uint256 base = arith_uint256(100000000) * arith_uint256(100000000) * arith_uint256(100000000);
#define BASE(x) (arith_uint256(x)*base)
#define AI(x) arith_uint256(x)
return 100 + ((BASE(1)/((BASE(nWeight)/AI(networkTotalWeight))))).GetLow64();
#undef AI
#undef BASE
}
bool getAllUnspentWitnessCoins(CChain& chain, const CChainParams& chainParams, const CBlockIndex* pPreviousIndexChain_, std::map<COutPoint, Coin>& allWitnessCoins, CBlock* newBlock, CCoinsViewCache* viewOverride, bool forceIndexBased)
{
DO_BENCHMARK("WIT: getAllUnspentWitnessCoins", BCLog::BENCH|BCLog::WITNESS);
#ifdef ENABLE_WALLET
LOCK2(cs_main, pactiveWallet?&pactiveWallet->cs_wallet:NULL);
#else
LOCK(cs_main);
#endif
assert(pPreviousIndexChain_);
allWitnessCoins.clear();
//fixme: (PHASE5) Add more error handling to this function.
// Sort out pre-conditions.
// We have to make sure that we are using a view and chain that includes the PoW block we are witnessing and all of its transactions as the tip.
// It won't necessarily be part of the chain yet; if we are in the process of witnessing; or if the block is an older one on a fork; because only blocks that have already been witnessed can be part of the chain.
// So we have to temporarily force disconnect/reconnect of blocks as necessary to make a temporary working chain that suits the properties we want.
// NB!!! - It is important that we don't flush either of these before destructing, we want to throw the result away.
CCoinsViewCache viewNew(viewOverride?viewOverride:pcoinsTip);
if ((uint64_t)pPreviousIndexChain_->nHeight < Params().GetConsensus().pow2Phase2FirstBlockHeight)
return true;
// We work on a clone of the chain to prevent modifying the actual chain.
CBlockIndex* pPreviousIndexChain = nullptr;
CCloneChain tempChain(chain, GetPow2ValidationCloneHeight(chain, pPreviousIndexChain_, 2), pPreviousIndexChain_, pPreviousIndexChain);
CValidationState state;
assert(pPreviousIndexChain);
// Force the tip of the chain to the block that comes before the block we are examining.
// For phase 3 this must be a PoW block - from phase 4 it should be a witness block
if (pPreviousIndexChain->nHeight == 0)
{
ForceActivateChain(pPreviousIndexChain, nullptr, state, chainParams, tempChain, viewNew);
}
else
{
if (pPreviousIndexChain->nVersionPoW2Witness==0 || IsPow2Phase4Active(pPreviousIndexChain->pprev))
{
ForceActivateChain(pPreviousIndexChain, nullptr, state, chainParams, tempChain, viewNew);
}
else
{
CBlockIndex* pPreviousIndexChainPoW = new CBlockIndex(*GetPoWBlockForPoSBlock(pPreviousIndexChain));
assert(pPreviousIndexChainPoW);
pPreviousIndexChainPoW->pprev = pPreviousIndexChain->pprev;
ForceActivateChainWithBlockAsTip(pPreviousIndexChain->pprev, nullptr, state, chainParams, tempChain, viewNew, pPreviousIndexChainPoW);
pPreviousIndexChain = tempChain.Tip();
}
}
// If we have been passed a new tip block (not yet part of the chain) then add it to the chain now.
if (newBlock)
{
// Strip any witness information from the block we have been given we want a non-witness block as the tip in order to calculate the witness for it.
if (newBlock->nVersionPoW2Witness != 0)
{
for (unsigned int i = 1; i < newBlock->vtx.size(); i++)
{
if (newBlock->vtx[i]->IsCoinBase() && newBlock->vtx[i]->IsPoW2WitnessCoinBase())
{
while (newBlock->vtx.size() > i)
{
newBlock->vtx.pop_back();
}
break;
}
}
newBlock->nVersionPoW2Witness = 0;
newBlock->nTimePoW2Witness = 0;
newBlock->hashMerkleRootPoW2Witness = uint256();
newBlock->witnessHeaderPoW2Sig.clear();
newBlock->witnessUTXODelta.clear();
}
// Place the block in question at the tip of the chain.
CBlockIndex* indexDummy = new CBlockIndex(*newBlock);
indexDummy->pprev = pPreviousIndexChain;
indexDummy->nHeight = pPreviousIndexChain->nHeight + 1;
if (!ConnectBlock(tempChain, *newBlock, state, indexDummy, viewNew, chainParams, true, false, false, false))
{
//fixme: (PHASE5) If we are inside a GetWitness call ban the peer that sent us this?
return false;
}
tempChain.SetTip(indexDummy);
}
/** Gather a list of all unspent witness outputs.
NB!!! There are multiple layers of cache at play here, with insertions/deletions possibly having taken place at each layer.
Therefore the order of operations is crucial, we must first iterate the lowest layer, then the second lowest and finally the highest layer.
For each iteration we should remove items from allWitnessCoins if they have been deleted in the higher layer as the higher layer overrides the lower layer.
GetAllCoins takes care of all of this automatically.
**/
if (forceIndexBased || (uint64_t)tempChain.Tip()->nHeight >= Params().GetConsensus().pow2WitnessSyncHeight)
{
viewNew.pChainedWitView->GetAllCoinsIndexBased(allWitnessCoins);
}
else
{
viewNew.pChainedWitView->GetAllCoins(allWitnessCoins);
}
return true;
}
//fixme: (PHASE5) Improve error handling.
//fixme: (PHASE5) Handle nodes with excessive pruning. //pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
bool GetWitnessHelper(uint256 blockHash, CGetWitnessInfo& witnessInfo, uint64_t nBlockHeight)
{
DO_BENCHMARK("WIT: GetWitnessHelper", BCLog::BENCH|BCLog::WITNESS);
#ifdef ENABLE_WALLET
LOCK2(cs_main, pactiveWallet?&pactiveWallet->cs_wallet:nullptr);
#else
LOCK(cs_main);
#endif
/** Generate the pool of potential witnesses for the given block index **/
/** Addresses younger than nMinAge blocks are discarded **/
uint64_t nMinAge = gMinimumParticipationAge;
while (true)
{
witnessInfo.witnessSelectionPoolFiltered.clear();
witnessInfo.witnessSelectionPoolFiltered = witnessInfo.witnessSelectionPoolUnfiltered;
/** Eliminate addresses that have witnessed within the last `gMinimumParticipationAge` blocks **/
witnessInfo.witnessSelectionPoolFiltered.erase(std::remove_if(witnessInfo.witnessSelectionPoolFiltered.begin(), witnessInfo.witnessSelectionPoolFiltered.end(), [&](RouletteItem& x){ return (x.nAge <= nMinAge); }), witnessInfo.witnessSelectionPoolFiltered.end());
/** Eliminate addresses that have not witnessed within the expected period of time that they should have **/
witnessInfo.witnessSelectionPoolFiltered.erase(std::remove_if(witnessInfo.witnessSelectionPoolFiltered.begin(), witnessInfo.witnessSelectionPoolFiltered.end(), [&](RouletteItem& x){ return witnessHasExpired(x.nAge, x.nWeight, witnessInfo.nTotalWeightRaw); }), witnessInfo.witnessSelectionPoolFiltered.end());
/** Eliminate addresses that are within 100 blocks from lock period expiring, or whose lock period has expired. **/
witnessInfo.witnessSelectionPoolFiltered.erase(std::remove_if(witnessInfo.witnessSelectionPoolFiltered.begin(), witnessInfo.witnessSelectionPoolFiltered.end(), [&](RouletteItem& x){ CTxOutPoW2Witness details; GetPow2WitnessOutput(x.coin.out, details); return (GetPoW2RemainingLockLengthInBlocks(details.lockUntilBlock, nBlockHeight) <= nMinAge); }), witnessInfo.witnessSelectionPoolFiltered.end());
// We must have at least 100 accounts to keep odds of being selected down below 1% at all times.
if (witnessInfo.witnessSelectionPoolFiltered.size() < 100)
{
if(!Params().IsTestnet() && nBlockHeight > 880000)
CAlert::Notify("Warning network is experiencing low levels of witnessing participants!", true, true);
// NB!! This part of the code should (ideally) never actually be used, it exists only for instances where there are a shortage of witnesses paticipating on the network.
if (nMinAge == 0 || (nMinAge <= 10 && witnessInfo.witnessSelectionPoolFiltered.size() > 5))
{
break;
}
else
{
// Try again to reach 100 candidates with a smaller min age.
nMinAge -= 5;
}
}
else
{
break;
}
}
if (witnessInfo.witnessSelectionPoolFiltered.size() == 0)
{
return error("Unable to determine any witnesses for block.");
}
/** Ensure the pool is sorted deterministically **/
std::sort(witnessInfo.witnessSelectionPoolFiltered.begin(), witnessInfo.witnessSelectionPoolFiltered.end());
/** Calculate total eligible weight **/
witnessInfo.nTotalWeightEligibleRaw = 0;
for (auto& item : witnessInfo.witnessSelectionPoolFiltered)
{
witnessInfo.nTotalWeightEligibleRaw += item.nWeight;
}
uint64_t genesisWeight=0;
if (Params().numGenesisWitnesses > 0)
{
genesisWeight = std::max(witnessInfo.nTotalWeightEligibleRaw / Params().genesisWitnessWeightDivisor, (uint64_t)1000);
witnessInfo.nTotalWeightEligibleRaw += Params().numGenesisWitnesses*genesisWeight;
}
/** Reduce larger weightings to a maximum weighting of 1% of network weight. **/
/** NB!! this actually will end up a little bit more than 1% as the overall network weight will also be reduced as a result. **/
/** This is however unimportant as 1% is in and of itself also somewhat arbitrary, simpler code is favoured here over exactness. **/
/** So we delibritely make no attempt to compensate for this. **/
witnessInfo.nMaxIndividualWeight = witnessInfo.nTotalWeightEligibleRaw / 100;
witnessInfo.nTotalWeightEligibleAdjusted = 0;
for (auto& item : witnessInfo.witnessSelectionPoolFiltered)
{
if (item.nWeight == 0)
item.nWeight = genesisWeight;
if (item.nWeight > witnessInfo.nMaxIndividualWeight)
item.nWeight = witnessInfo.nMaxIndividualWeight;
witnessInfo.nTotalWeightEligibleAdjusted += item.nWeight;
item.nCumulativeWeight = witnessInfo.nTotalWeightEligibleAdjusted;
}
/** sha256 as random roulette spin/seed - NB! We delibritely use sha256 and -not- the normal PoW hash here as the normal PoW hash is biased towards certain number ranges by -design- (block target) so is not a good RNG... **/
arith_uint256 rouletteSelectionSeed = UintToArith256(blockHash);
//fixme: (PHASE5) Update whitepaper then delete this code.
/** ensure random seed exceeds one full spin of the wheel to prevent any possible bias towards low numbers **/
//while (rouletteSelectionSeed < witnessInfo.nTotalWeightEligibleAdjusted)
//{
//rouletteSelectionSeed = rouletteSelectionSeed * 2;
//}
/** Reduce selection number to fit within possible range of values **/
if (rouletteSelectionSeed > arith_uint256(witnessInfo.nTotalWeightEligibleAdjusted))
{
// 'BigNum' Modulo operator via mathematical identity: a % b = a - (b * int(a/b))
rouletteSelectionSeed = rouletteSelectionSeed - (arith_uint256(witnessInfo.nTotalWeightEligibleAdjusted) * arith_uint256(rouletteSelectionSeed/arith_uint256(witnessInfo.nTotalWeightEligibleAdjusted)));
}
/** Perform selection **/
auto selectedWitness = std::lower_bound(witnessInfo.witnessSelectionPoolFiltered.begin(), witnessInfo.witnessSelectionPoolFiltered.end(), rouletteSelectionSeed.GetLow64());
witnessInfo.selectedWitnessTransaction = selectedWitness->coin.out;
witnessInfo.selectedWitnessIndex = selectedWitness-(witnessInfo.witnessSelectionPoolFiltered.begin());
#ifdef DEBUG
assert((witnessInfo.witnessSelectionPoolFiltered[witnessInfo.selectedWitnessIndex].coin.out == selectedWitness->coin.out));
#endif
witnessInfo.selectedWitnessBlockHeight = selectedWitness->coin.nHeight;
witnessInfo.selectedWitnessOutpoint = selectedWitness->outpoint;
return true;
}
bool GetWitnessInfo(CChain& chain, const CChainParams& chainParams, CCoinsViewCache* viewOverride, CBlockIndex* pPreviousIndexChain, CBlock block, CGetWitnessInfo& witnessInfo, uint64_t nBlockHeight)
{
DO_BENCHMARK("WIT: GetWitnessInfo", BCLog::BENCH|BCLog::WITNESS);
#ifdef DISABLE_WALLET
LOCK2(cs_main, pactiveWallet?&pactiveWallet->cs_wallet:nullptr);
#else
LOCK(cs_main);
#endif
// Fetch all unspent witness outputs for the chain in which -block- acts as the tip.
if (!getAllUnspentWitnessCoins(chain, chainParams, pPreviousIndexChain, witnessInfo.allWitnessCoins, &block, viewOverride))
return false;
bool outputsShouldBeHashes = (nBlockHeight < Params().GetConsensus().pow2WitnessSyncHeight);
// Gather all witnesses that exceed minimum weight and count the total witness weight.
for (auto coinIter : witnessInfo.allWitnessCoins)
{
//fixme: (PHASE5) Unit tests
uint64_t nAge = nBlockHeight - coinIter.second.nHeight;
COutPoint outPoint = coinIter.first;
assert(outPoint.isHash == outputsShouldBeHashes);
Coin coin = coinIter.second;
if (coin.out.nValue >= (gMinimumWitnessAmount*COIN))
{
uint64_t nUnused1, nUnused2;
int64_t nWeight = GetPoW2RawWeightForAmount(coin.out.nValue, pPreviousIndexChain->nHeight, GetPoW2LockLengthInBlocksFromOutput(coin.out, coin.nHeight, nUnused1, nUnused2));
if (nWeight < gMinimumWitnessWeight)
continue;
witnessInfo.witnessSelectionPoolUnfiltered.push_back(RouletteItem(outPoint, coin, nWeight, nAge));
witnessInfo.nTotalWeightRaw += nWeight;
}
else if (coin.out.output.witnessDetails.lockFromBlock == 1)
{
int64_t nWeight = 0;
witnessInfo.witnessSelectionPoolUnfiltered.push_back(RouletteItem(outPoint, coin, nWeight, nAge));
}
}
return true;
}
bool GetWitness(CChain& chain, const CChainParams& chainParams, CCoinsViewCache* viewOverride, CBlockIndex* pPreviousIndexChain, CBlock block, CGetWitnessInfo& witnessInfo)
{
DO_BENCHMARK("WIT: GetWitness", BCLog::BENCH|BCLog::WITNESS);
#ifdef ENABLE_WALLET
LOCK2(cs_main, pactiveWallet?&pactiveWallet->cs_wallet:nullptr);
#else
LOCK(cs_main);
#endif
// Fetch all the chain info (for specific block) we will need to calculate the witness.
uint64_t nBlockHeight = pPreviousIndexChain->nHeight + 1;
if (!GetWitnessInfo(chain, chainParams, viewOverride, pPreviousIndexChain, block, witnessInfo, nBlockHeight))
return false;
return GetWitnessHelper(block.GetHashLegacy(), witnessInfo, nBlockHeight);
}
bool GetWitnessFromSimplifiedUTXO(SimplifiedWitnessUTXOSet simplifiedWitnessUTXO, const CBlockIndex* pBlockIndex, CGetWitnessInfo& witnessInfo)
{
DO_BENCHMARK("WIT: GetWitnessFromSimplifiedUTXO", BCLog::BENCH|BCLog::WITNESS);
#ifdef ENABLE_WALLET
LOCK2(cs_main, pactiveWallet?&pactiveWallet->cs_wallet:nullptr);
#else
LOCK(cs_main);
#endif
// Populate the witness info from the utxo
uint64_t nBlockHeight = pBlockIndex->nHeight;
// Equivalent of GetWitnessInfo
{
// Gather all witnesses that exceed minimum weight and count the total witness weight.
for (auto simplifiedRouletteItem : simplifiedWitnessUTXO.witnessCandidates)
{
// We delibritely leave failCount, actionNonce and spendingKeyId unset here, as they aren't used by the code that follows.
CTxOutPoW2Witness simplifiedWitnessInfo;
simplifiedWitnessInfo.witnessKeyID = simplifiedRouletteItem.witnessPubKeyID;
simplifiedWitnessInfo.lockFromBlock = simplifiedRouletteItem.lockFromBlock;
simplifiedWitnessInfo.lockUntilBlock = simplifiedRouletteItem.lockUntilBlock;
// Set our partially filled in coin item (we have filled in all the parts that GetWitnessHelper touches)
Coin rouletteCoin = Coin(CTxOut(simplifiedRouletteItem.nValue, CTxOutPoW2Witness(simplifiedWitnessInfo)), simplifiedRouletteItem.blockNumber, 0, false, false);
COutPoint rouletteOutpoint = COutPoint(simplifiedRouletteItem.blockNumber, simplifiedRouletteItem.transactionIndex, simplifiedRouletteItem.transactionOutputIndex);
RouletteItem item(rouletteOutpoint, rouletteCoin, 0, 0);
item.nAge = nBlockHeight - simplifiedRouletteItem.blockNumber;
if (simplifiedRouletteItem.nValue >= (gMinimumWitnessAmount*COIN))
{
item.nWeight = GetPoW2RawWeightForAmount(item.coin.out.nValue, nBlockHeight, simplifiedRouletteItem.GetLockLength());
if (item.nWeight < gMinimumWitnessWeight)
continue;
witnessInfo.witnessSelectionPoolUnfiltered.push_back(item);
witnessInfo.nTotalWeightRaw += item.nWeight;
}
else if (simplifiedRouletteItem.lockFromBlock == 1)
{
item.nWeight = 0;
witnessInfo.witnessSelectionPoolUnfiltered.push_back(item);
}
}
}
return GetWitnessHelper(pBlockIndex->GetBlockHashLegacy(), witnessInfo, nBlockHeight);
}
bool GetWitnessFromUTXO(std::vector<RouletteItem> witnessUtxo, CBlockIndex* pBlockIndex, CGetWitnessInfo& witnessInfo)
{
DO_BENCHMARK("WIT: GetWitnessFromUTXO", BCLog::BENCH|BCLog::WITNESS);
#ifdef ENABLE_WALLET
LOCK2(cs_main, pactiveWallet?&pactiveWallet->cs_wallet:nullptr);
#else
LOCK(cs_main);
#endif
// Populate the witness info from the utxo
uint64_t nBlockHeight = pBlockIndex->nHeight;
// Equivalent of GetWitnessInfo
{
// Gather all witnesses that exceed minimum weight and count the total witness weight.
for (auto rouletteItem : witnessUtxo)
{
//uint64_t nAge = nBlockHeight - coinIter.second.nHeight;
assert(!rouletteItem.outpoint.isHash);
//COutPoint outPoint = coinIter.first;
if (rouletteItem.coin.out.nValue >= (gMinimumWitnessAmount*COIN))
{
uint64_t nUnused1, nUnused2;
int64_t nWeight = GetPoW2RawWeightForAmount(rouletteItem.coin.out.nValue, nBlockHeight, GetPoW2LockLengthInBlocksFromOutput(rouletteItem.coin.out, rouletteItem.coin.nHeight, nUnused1, nUnused2));
if (nWeight < gMinimumWitnessWeight)
continue;
witnessInfo.witnessSelectionPoolUnfiltered.push_back(rouletteItem);
witnessInfo.nTotalWeightRaw += nWeight;
}
else if (rouletteItem.coin.out.output.witnessDetails.lockFromBlock == 1)
{
rouletteItem.nWeight = 0;
witnessInfo.witnessSelectionPoolUnfiltered.push_back(rouletteItem);
}
}
}
return GetWitnessHelper(pBlockIndex->GetBlockHashLegacy(), witnessInfo, nBlockHeight);
}
// Ideally this should have been some hybrid of witInfo.nTotalWeight / witInfo.nReducedTotalWeight - as both independantly aren't perfect.
// Total weight is prone to be too high if there are lots of large >1% witnesses, nReducedTotalWeight is prone to be too low if there is one large witness who has recently witnessed.
// However on a large network with lots of participants this should not matter - and technical constraints make the total the best compromise
// As we need to call this from within the witness algorithm from before nReducedTotalWeight is even known.
bool witnessHasExpired(uint64_t nWitnessAge, uint64_t nWitnessWeight, uint64_t nNetworkTotalWitnessWeight)
{
if (nWitnessWeight == 0)
return false;
uint64_t nExpectedWitnessPeriod = expectedWitnessBlockPeriod(nWitnessWeight, nNetworkTotalWitnessWeight);
return ( nWitnessAge > gMaximumParticipationAge ) || ( nWitnessAge > nExpectedWitnessPeriod );
}
const char changeTypeCreation = 0;
const char changeTypeSpend = 1;
const char changeTypeRenew = 2;
const char changeTypeRearrange = 3;
const char changeTypeIncrease = 4;
const char changeTypeChangeKey = 5;
const char changeTypeWitnessAction = 6;
struct deltaItem
{
public:
int changeType;
std::vector<SimplifiedWitnessRouletteItem> removedItems;
std::vector<SimplifiedWitnessRouletteItem> addedItems;
};
bool GenerateSimplifiedWitnessUTXODeltaUndoForHeader(std::vector<unsigned char>& undoWitnessUTXODelta, SimplifiedWitnessUTXOSet& pow2SimplifiedWitnessUTXOUndo, std::vector<deltaItem>& deltaItems)
{
CVectorWriter deltaUndoStream(SER_NETWORK, 0, undoWitnessUTXODelta, 0);
// Play back the changes to generate the undo info
// Note that we have to actually perform the changes as we go, and not just serialise them
// The reason for this is that each operation that does an insert/remove can change the index of all future insert/removes
// So if we just serialise the indexes will be wrong when we replay the changes later
// First handle the witness that signed the block as a special case, as there is always only one of these at the start, then loop for everything else.
{
// Remove the updated witness item and put back the original one
const auto& deltaWitnessItem = deltaItems[0];
assert(deltaWitnessItem.addedItems.size() == 1);
assert(deltaWitnessItem.removedItems.size() == 1);
assert(deltaWitnessItem.changeType == changeTypeWitnessAction);
const auto& addedItemIter = pow2SimplifiedWitnessUTXOUndo.witnessCandidates.find(deltaWitnessItem.addedItems[0]);
deltaUndoStream << VARINT(pow2SimplifiedWitnessUTXOUndo.witnessCandidates.index_of(addedItemIter));
deltaUndoStream << COMPRESSEDAMOUNT(deltaWitnessItem.removedItems[0].nValue);
deltaUndoStream << VARINT(deltaWitnessItem.removedItems[0].blockNumber);
deltaUndoStream << VARINT(deltaWitnessItem.removedItems[0].transactionIndex);
deltaUndoStream << COMPACTSIZE(deltaWitnessItem.removedItems[0].transactionOutputIndex);
pow2SimplifiedWitnessUTXOUndo.witnessCandidates.erase(addedItemIter);
pow2SimplifiedWitnessUTXOUndo.witnessCandidates.insert(deltaWitnessItem.removedItems[0]);
deltaItems.erase(deltaItems.begin());
}
// Loop for remaining changes, and serialise along with change type identifier
for (const auto& deltaItem : deltaItems)
{
switch(deltaItem.changeType)
{
case changeTypeWitnessAction:
{
continue;
}
case changeTypeCreation:
{
// We delete the created item
assert(deltaItem.addedItems.size() == 1);
assert(deltaItem.removedItems.size() == 0);
auto addedItemIter = pow2SimplifiedWitnessUTXOUndo.witnessCandidates.find(deltaItem.addedItems[0]);
deltaUndoStream << changeTypeCreation;
deltaUndoStream << VARINT(pow2SimplifiedWitnessUTXOUndo.witnessCandidates.index_of(addedItemIter));
pow2SimplifiedWitnessUTXOUndo.witnessCandidates.erase(addedItemIter);
break;
}
case changeTypeSpend:
{
// We add the spent item back into the set
assert(deltaItem.addedItems.size() == 0);
assert(deltaItem.removedItems.size() == 1);
auto originalItem = deltaItem.removedItems[0];
pow2SimplifiedWitnessUTXOUndo.witnessCandidates.insert(originalItem);
deltaUndoStream << changeTypeSpend;
deltaUndoStream << VARINT(originalItem.blockNumber);
deltaUndoStream << VARINT(originalItem.transactionIndex);
deltaUndoStream << COMPACTSIZE(originalItem.transactionOutputIndex);
deltaUndoStream << COMPRESSEDAMOUNT(originalItem.nValue);
deltaUndoStream << VARINT(originalItem.lockFromBlock);
deltaUndoStream << VARINT(originalItem.lockUntilBlock);
deltaUndoStream << originalItem.witnessPubKeyID;
break;
}
case changeTypeRenew:
{
// Revert the renewed item to its original state/position
assert(deltaItem.addedItems.size() == 1);
assert(deltaItem.removedItems.size() == 1);
auto& renewedItem = deltaItem.addedItems[0];
auto renewedItemIter = pow2SimplifiedWitnessUTXOUndo.witnessCandidates.find(renewedItem);
auto& originalItem = deltaItem.removedItems[0];
pow2SimplifiedWitnessUTXOUndo.witnessCandidates.erase(renewedItemIter);
pow2SimplifiedWitnessUTXOUndo.witnessCandidates.insert(originalItem);
deltaUndoStream << changeTypeRenew;
deltaUndoStream << VARINT(pow2SimplifiedWitnessUTXOUndo.witnessCandidates.index_of(renewedItemIter));
deltaUndoStream << VARINT(originalItem.blockNumber);
deltaUndoStream << VARINT(originalItem.transactionIndex);
deltaUndoStream << COMPACTSIZE(originalItem.transactionOutputIndex);
break;
}
case changeTypeRearrange:
{
// Remove all the rearranged items and put back the originals
assert(deltaItem.addedItems.size() > 0);
assert(deltaItem.removedItems.size() > 0);
deltaUndoStream << changeTypeRearrange << COMPACTSIZE(deltaItem.addedItems.size()) << COMPACTSIZE(deltaItem.removedItems.size());
for (const auto& addItem : deltaItem.addedItems)
{
auto addIter = pow2SimplifiedWitnessUTXOUndo.witnessCandidates.find(addItem);
deltaUndoStream << VARINT(pow2SimplifiedWitnessUTXOUndo.witnessCandidates.index_of(addIter));
pow2SimplifiedWitnessUTXOUndo.witnessCandidates.erase(addIter);
}
for (const auto& removeItem : deltaItem.removedItems)
{
deltaUndoStream << VARINT(removeItem.blockNumber);
deltaUndoStream << VARINT(removeItem.transactionIndex);
deltaUndoStream << COMPACTSIZE(removeItem.transactionOutputIndex);
deltaUndoStream << COMPRESSEDAMOUNT(removeItem.nValue);
pow2SimplifiedWitnessUTXOUndo.witnessCandidates.insert(removeItem);
}
break;
}
case changeTypeIncrease:
{
// Remove all the increased items and put back the originals
assert(deltaItem.addedItems.size() > 0);
assert(deltaItem.removedItems.size() > 0);
deltaUndoStream << changeTypeIncrease << COMPACTSIZE(deltaItem.addedItems.size()) << COMPACTSIZE(deltaItem.removedItems.size()) << VARINT(deltaItem.removedItems[0].lockUntilBlock);
for (const auto& addItem : deltaItem.addedItems)
{
auto addIter = pow2SimplifiedWitnessUTXOUndo.witnessCandidates.find(addItem);
deltaUndoStream << VARINT(pow2SimplifiedWitnessUTXOUndo.witnessCandidates.index_of(addIter));
pow2SimplifiedWitnessUTXOUndo.witnessCandidates.erase(addIter);
}
for (const auto& removeItem : deltaItem.removedItems)
{
deltaUndoStream << VARINT(removeItem.blockNumber);
deltaUndoStream << VARINT(removeItem.transactionIndex);
deltaUndoStream << COMPACTSIZE(removeItem.transactionOutputIndex);
deltaUndoStream << COMPRESSEDAMOUNT(removeItem.nValue);
deltaUndoStream << VARINT(removeItem.lockFromBlock);
pow2SimplifiedWitnessUTXOUndo.witnessCandidates.insert(removeItem);
}
break;
}
case changeTypeChangeKey:
{
// Remove all the updated items and put back the items with their original key
assert(deltaItem.addedItems.size() > 0);
assert(deltaItem.removedItems.size() > 0);
assert(deltaItem.addedItems.size() == deltaItem.removedItems.size());
deltaUndoStream << changeTypeChangeKey << COMPACTSIZE(deltaItem.removedItems.size()) << deltaItem.removedItems[0].witnessPubKeyID;
for (uint64_t i=0; i < deltaItem.addedItems.size(); ++i)
{
// Remove added item
auto addIter = pow2SimplifiedWitnessUTXOUndo.witnessCandidates.find(deltaItem.addedItems[i]);
deltaUndoStream << VARINT(pow2SimplifiedWitnessUTXOUndo.witnessCandidates.index_of(addIter));
pow2SimplifiedWitnessUTXOUndo.witnessCandidates.erase(addIter);
auto [insertIter, didInsert] = pow2SimplifiedWitnessUTXOUndo.witnessCandidates.insert(deltaItem.removedItems[i]);
(unused) insertIter;
if (!didInsert)
return false;
// Place back original item
deltaUndoStream << VARINT(deltaItem.removedItems[i].blockNumber);
deltaUndoStream << VARINT(deltaItem.removedItems[i].transactionIndex);
deltaUndoStream << COMPACTSIZE(deltaItem.removedItems[i].transactionOutputIndex);
}
break;
}
}
}
return true;
}
bool UndoSimplifiedWitnessUTXODeltaForHeader(SimplifiedWitnessUTXOSet& pow2SimplifiedWitnessUTXO, std::vector<unsigned char>& undoWitnessUTXODelta)
{
VectorReader deltaUndoStream(SER_NETWORK, 0, undoWitnessUTXODelta, 0);
// First handle the witness that signed the block as a special case, as there is always only one of these at the start, then loop for everything else.
{
uint64_t selectedWitnessIndex;
deltaUndoStream >> VARINT(selectedWitnessIndex);
auto witnessIter = pow2SimplifiedWitnessUTXO.witnessCandidates.nth(selectedWitnessIndex);
SimplifiedWitnessRouletteItem witnessItem = *witnessIter;
SimplifiedWitnessRouletteItem updatedWitnessItem = witnessItem;
deltaUndoStream >> COMPRESSEDAMOUNT(updatedWitnessItem.nValue);
deltaUndoStream >> VARINT(updatedWitnessItem.blockNumber);
deltaUndoStream >> VARINT(updatedWitnessItem.transactionIndex);
deltaUndoStream >> COMPACTSIZE(updatedWitnessItem.transactionOutputIndex);
pow2SimplifiedWitnessUTXO.witnessCandidates.erase(witnessIter);
auto [insertIter, didInsert] = pow2SimplifiedWitnessUTXO.witnessCandidates.insert(updatedWitnessItem);
(unused) insertIter;
if (!didInsert)
return false;
}
// Rest of the changes are encoded with a type
char changeType;
while (!deltaUndoStream.empty())
{
deltaUndoStream >> changeType;
switch(changeType)
{
// Delete the created item
case changeTypeCreation:
{
uint64_t createdItemIndex;
deltaUndoStream >> VARINT(createdItemIndex);
pow2SimplifiedWitnessUTXO.witnessCandidates.erase(pow2SimplifiedWitnessUTXO.witnessCandidates.nth(createdItemIndex));
break;
}
// Recreate the deleted/spent item
case changeTypeSpend:
{
SimplifiedWitnessRouletteItem item;
deltaUndoStream >> VARINT(item.blockNumber);
deltaUndoStream >> VARINT(item.transactionIndex);
deltaUndoStream >> COMPACTSIZE(item.transactionOutputIndex);
deltaUndoStream >> COMPRESSEDAMOUNT(item.nValue);
deltaUndoStream >> VARINT(item.lockFromBlock);
deltaUndoStream >> VARINT(item.lockUntilBlock);
deltaUndoStream >> item.witnessPubKeyID;
auto [insertIter, didInsert] = pow2SimplifiedWitnessUTXO.witnessCandidates.insert(item);
(unused) insertIter;
if (!didInsert)
return false;
break;
}
// Remove the renewed item and place back the original item
case changeTypeRenew:
{
uint64_t renewedItemIndex;
deltaUndoStream >> VARINT(renewedItemIndex);
auto itemIter = pow2SimplifiedWitnessUTXO.witnessCandidates.nth(renewedItemIndex);
SimplifiedWitnessRouletteItem item = *itemIter;
SimplifiedWitnessRouletteItem modifiedItem = item;
deltaUndoStream >> VARINT(modifiedItem.blockNumber);
deltaUndoStream >> VARINT(modifiedItem.transactionIndex);
deltaUndoStream >> COMPACTSIZE(modifiedItem.transactionOutputIndex);
pow2SimplifiedWitnessUTXO.witnessCandidates.erase(itemIter);
auto [insertIter, didInsert] = pow2SimplifiedWitnessUTXO.witnessCandidates.insert(modifiedItem);
(unused) insertIter;
if (!didInsert)
return false;
break;
}
// Perform the re-arrangement but in reverse
case changeTypeRearrange:
{
uint64_t numItemsToRemove;
uint64_t numItemsToAdd;
deltaUndoStream >> COMPACTSIZE(numItemsToRemove) >> COMPACTSIZE(numItemsToAdd);
SimplifiedWitnessRouletteItem item;
for (uint64_t i=0; i<numItemsToRemove; ++i)
{
uint64_t outputIndex;
deltaUndoStream >> VARINT(outputIndex);
auto itemIter = pow2SimplifiedWitnessUTXO.witnessCandidates.nth(outputIndex);
if (i == 0)
{
item = *itemIter;
}
pow2SimplifiedWitnessUTXO.witnessCandidates.erase(itemIter);
}
for (uint64_t i=0; i<numItemsToAdd; ++i)
{
deltaUndoStream >> VARINT(item.blockNumber);
deltaUndoStream >> VARINT(item.transactionIndex);
deltaUndoStream >> COMPACTSIZE(item.transactionOutputIndex);
deltaUndoStream >> COMPRESSEDAMOUNT(item.nValue);
auto [insertIter, didInsert] = pow2SimplifiedWitnessUTXO.witnessCandidates.insert(item);
(unused) insertIter;
if (!didInsert)
return false;
}
break;
}
// Reverse the increase/re-arrangement
case changeTypeIncrease:
{
uint64_t numItemsToRemove;
uint64_t numItemsToAdd;
uint64_t originalLockUntilBlock;
deltaUndoStream >> COMPACTSIZE(numItemsToRemove) >> COMPACTSIZE(numItemsToAdd) >> VARINT(originalLockUntilBlock);
SimplifiedWitnessRouletteItem item;
for (uint64_t i=0; i<numItemsToRemove; ++i)
{
uint64_t outputIndex;
deltaUndoStream >> VARINT(outputIndex);
auto itemIter = pow2SimplifiedWitnessUTXO.witnessCandidates.nth(outputIndex);
if (i == 0)
{
item = *itemIter;
item.lockUntilBlock = originalLockUntilBlock;
}
pow2SimplifiedWitnessUTXO.witnessCandidates.erase(itemIter);
}
for (uint64_t i=0; i<numItemsToAdd; ++i)
{
deltaUndoStream >> VARINT(item.blockNumber);
deltaUndoStream >> VARINT(item.transactionIndex);
deltaUndoStream >> COMPACTSIZE(item.transactionOutputIndex);
deltaUndoStream >> COMPRESSEDAMOUNT(item.nValue);
deltaUndoStream >> VARINT(item.lockFromBlock);
auto [insertIter, didInsert] = pow2SimplifiedWitnessUTXO.witnessCandidates.insert(item);
(unused) insertIter;
if (!didInsert)
return false;
}
break;
}
// Change the key back
case changeTypeChangeKey:
{
uint64_t numItems;
deltaUndoStream >> COMPACTSIZE(numItems);
CKeyID witnessKeyID;
deltaUndoStream >> witnessKeyID;
for (uint64_t i=0; i < numItems; ++i )
{
uint64_t itemIndex;
deltaUndoStream >> VARINT(itemIndex);
auto itemIter = pow2SimplifiedWitnessUTXO.witnessCandidates.nth(itemIndex);
SimplifiedWitnessRouletteItem item = *itemIter;
item.witnessPubKeyID = witnessKeyID;