forked from PIVX-Project/PIVX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchain.cpp
355 lines (310 loc) · 11.1 KB
/
chain.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
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016-2021 The PIVX Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "legacy/stakemodifier.h" // for ComputeNextStakeModifier
/**
* CChain implementation
*/
void CChain::SetTip(CBlockIndex* pindex)
{
if (pindex == nullptr) {
vChain.clear();
return;
}
vChain.resize(pindex->nHeight + 1);
while (pindex && vChain[pindex->nHeight] != pindex) {
vChain[pindex->nHeight] = pindex;
pindex = pindex->pprev;
}
}
CBlockLocator CChain::GetLocator(const CBlockIndex* pindex) const
{
int nStep = 1;
std::vector<uint256> vHave;
vHave.reserve(32);
if (!pindex)
pindex = Tip();
while (pindex) {
vHave.push_back(pindex->GetBlockHash());
// Stop when we have added the genesis block.
if (pindex->nHeight == 0)
break;
// Exponentially larger steps back, plus the genesis block.
int nHeight = std::max(pindex->nHeight - nStep, 0);
if (Contains(pindex)) {
// Use O(1) CChain index if possible.
pindex = (*this)[nHeight];
} else {
// Otherwise, use O(log n) skiplist.
pindex = pindex->GetAncestor(nHeight);
}
if (vHave.size() > 10)
nStep *= 2;
}
return CBlockLocator(vHave);
}
const CBlockIndex* CChain::FindFork(const CBlockIndex* pindex) const
{
if (pindex == nullptr)
return nullptr;
if (pindex->nHeight > Height())
pindex = pindex->GetAncestor(Height());
while (pindex && !Contains(pindex))
pindex = pindex->pprev;
return pindex;
}
CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const
{
std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime,
[](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; });
return (lower == vChain.end() ? nullptr : *lower);
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height)
{
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
if (height > nHeight || height < 0) {
return nullptr;
}
const CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
assert(pindexWalk->pprev);
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
return const_cast<CBlockIndex*>(static_cast<const CBlockIndex*>(this)->GetAncestor(height));
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
CBlockIndex::CBlockIndex(const CBlock& block):
nVersion{block.nVersion},
hashMerkleRoot{block.hashMerkleRoot},
hashFinalSaplingRoot(block.hashFinalSaplingRoot),
nTime{block.nTime},
nBits{block.nBits},
nNonce{block.nNonce}
{
if(block.nVersion > 3 && block.nVersion < 7)
nAccumulatorCheckpoint = block.nAccumulatorCheckpoint;
if (block.IsProofOfStake())
SetProofOfStake();
}
std::string CBlockIndex::ToString() const
{
return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, nHeight,
hashMerkleRoot.ToString(),
GetBlockHash().ToString());
}
FlatFilePos CBlockIndex::GetBlockPos() const
{
FlatFilePos ret;
if (nStatus & BLOCK_HAVE_DATA) {
ret.nFile = nFile;
ret.nPos = nDataPos;
}
return ret;
}
FlatFilePos CBlockIndex::GetUndoPos() const
{
FlatFilePos ret;
if (nStatus & BLOCK_HAVE_UNDO) {
ret.nFile = nFile;
ret.nPos = nUndoPos;
}
return ret;
}
CBlockHeader CBlockIndex::GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
if (pprev) block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
if (nVersion > 3 && nVersion < 7) block.nAccumulatorCheckpoint = nAccumulatorCheckpoint;
if (nVersion >= 8) block.hashFinalSaplingRoot = hashFinalSaplingRoot;
return block;
}
int64_t CBlockIndex::MaxFutureBlockTime() const
{
return GetAdjustedTime() + Params().GetConsensus().FutureBlockTimeDrift(nHeight+1);
}
int64_t CBlockIndex::MinPastBlockTime() const
{
const Consensus::Params& consensus = Params().GetConsensus();
// Time Protocol v1: pindexPrev->MedianTimePast + 1
if (!consensus.IsTimeProtocolV2(nHeight+1))
return GetMedianTimePast();
// on the transition from Time Protocol v1 to v2
// pindexPrev->nTime might be in the future (up to the allowed drift)
// so we allow the nBlockTimeProtocolV2 (PIVX v4.0) to be at most (180-14) seconds earlier than previous block
if (nHeight + 1 == consensus.vUpgrades[Consensus::UPGRADE_V4_0].nActivationHeight)
return GetBlockTime() - consensus.FutureBlockTimeDrift(nHeight) + consensus.FutureBlockTimeDrift(nHeight + 1);
// Time Protocol v2: pindexPrev->nTime
return GetBlockTime();
}
enum { nMedianTimeSpan = 11 };
int64_t CBlockIndex::GetMedianTimePast() const
{
int64_t pmedian[nMedianTimeSpan];
int64_t* pbegin = &pmedian[nMedianTimeSpan];
int64_t* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin) / 2];
}
unsigned int CBlockIndex::GetStakeEntropyBit() const
{
unsigned int nEntropyBit = ((GetBlockHash().GetCheapHash()) & 1);
return nEntropyBit;
}
bool CBlockIndex::SetStakeEntropyBit(unsigned int nEntropyBit)
{
if (nEntropyBit > 1)
return false;
nFlags |= (nEntropyBit ? BLOCK_STAKE_ENTROPY : 0);
return true;
}
// Sets V1 stake modifier (uint64_t)
void CBlockIndex::SetStakeModifier(const uint64_t nStakeModifier, bool fGeneratedStakeModifier)
{
vStakeModifier.clear();
const size_t modSize = sizeof(nStakeModifier);
vStakeModifier.resize(modSize);
std::memcpy(vStakeModifier.data(), &nStakeModifier, modSize);
if (fGeneratedStakeModifier)
nFlags |= BLOCK_STAKE_MODIFIER;
}
// Generates and sets new V1 stake modifier
void CBlockIndex::SetNewStakeModifier()
{
// compute stake entropy bit for stake modifier
if (!SetStakeEntropyBit(GetStakeEntropyBit()))
LogPrintf("%s : SetStakeEntropyBit() failed\n", __func__);
uint64_t nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pprev, nStakeModifier, fGeneratedStakeModifier))
LogPrintf("%s : ComputeNextStakeModifier() failed \n", __func__);
return SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
}
// Sets V2 stake modifiers (uint256)
void CBlockIndex::SetStakeModifier(const uint256& nStakeModifier)
{
vStakeModifier.clear();
vStakeModifier.insert(vStakeModifier.begin(), nStakeModifier.begin(), nStakeModifier.end());
}
// Generates and sets new V2 stake modifier
void CBlockIndex::SetNewStakeModifier(const uint256& prevoutId)
{
// Shouldn't be called on V1 modifier's blocks (or before setting pprev)
if (!Params().GetConsensus().NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V3_4)) return;
if (!pprev) throw std::runtime_error(strprintf("%s : ERROR: null pprev", __func__));
// Generate Hash(prevoutId | prevModifier) - switch with genesis modifier (0) on upgrade block
CHashWriter ss(SER_GETHASH, 0);
ss << prevoutId;
ss << pprev->GetStakeModifierV2();
SetStakeModifier(ss.GetHash());
}
// Returns V1 stake modifier (uint64_t)
uint64_t CBlockIndex::GetStakeModifierV1() const
{
if (vStakeModifier.empty() || Params().GetConsensus().NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V3_4))
return 0;
uint64_t nStakeModifier;
std::memcpy(&nStakeModifier, vStakeModifier.data(), vStakeModifier.size());
return nStakeModifier;
}
// Returns V2 stake modifier (uint256)
uint256 CBlockIndex::GetStakeModifierV2() const
{
if (vStakeModifier.empty() || !Params().GetConsensus().NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V3_4))
return UINT256_ZERO;
uint256 nStakeModifier;
std::memcpy(nStakeModifier.begin(), vStakeModifier.data(), vStakeModifier.size());
return nStakeModifier;
}
void CBlockIndex::SetChainSaplingValue()
{
// Sapling, update chain value
if (pprev) {
if (pprev->nChainSaplingValue) {
nChainSaplingValue = *pprev->nChainSaplingValue + nSaplingValue;
} else {
nChainSaplingValue = nullopt;
}
} else {
nChainSaplingValue = nSaplingValue;
}
}
//! Check whether this block index entry is valid up to the passed validity level.
bool CBlockIndex::IsValid(enum BlockStatus nUpTo) const
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
return ((nStatus & BLOCK_VALID_MASK) >= nUpTo);
}
//! Raise the validity level of this block index entry.
//! Returns true if the validity was changed.
bool CBlockIndex::RaiseValidity(enum BlockStatus nUpTo)
{
assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed.
if (nStatus & BLOCK_FAILED_MASK)
return false;
if ((nStatus & BLOCK_VALID_MASK) < nUpTo) {
nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo;
return true;
}
return false;
}
/** Find the last common ancestor two blocks have.
* Both pa and pb must be non-nullptr. */
const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb)
{
if (pa->nHeight > pb->nHeight) {
pa = pa->GetAncestor(pb->nHeight);
} else if (pb->nHeight > pa->nHeight) {
pb = pb->GetAncestor(pa->nHeight);
}
while (pa != pb && pa && pb) {
pa = pa->pprev;
pb = pb->pprev;
}
// Eventually all chain branches meet at the genesis block.
assert(pa == pb);
return pa;
}