| 27 | }; |
| 28 | |
| 29 | ThresholdState AbstractThresholdConditionChecker::GetStateFor(const CBlockIndex* pindexPrev, const Consensus::Params& params, ThresholdConditionCache& cache) const |
| 30 | { |
| 31 | int nPeriod = Period(params); |
| 32 | int nThreshold = Threshold(params); |
| 33 | int64_t nTimeStart = BeginTime(params); |
| 34 | int64_t nTimeTimeout = EndTime(params); |
| 35 | |
| 36 | // A block's state is always the same as that of the first of its period, so it is computed based on a pindexPrev whose height equals a multiple of nPeriod - 1. |
| 37 | if (pindexPrev != NULL) { |
| 38 | pindexPrev = pindexPrev->GetAncestor(pindexPrev->nHeight - ((pindexPrev->nHeight + 1) % nPeriod)); |
| 39 | } |
| 40 | |
| 41 | // Walk backwards in steps of nPeriod to find a pindexPrev whose information is known |
| 42 | std::vector<const CBlockIndex*> vToCompute; |
| 43 | while (cache.count(pindexPrev) == 0) { |
| 44 | if (pindexPrev == NULL) { |
| 45 | // The genesis block is by definition defined. |
| 46 | cache[pindexPrev] = THRESHOLD_DEFINED; |
| 47 | break; |
| 48 | } |
| 49 | if (pindexPrev->GetMedianTimePast() < nTimeStart) { |
| 50 | // Optimization: don't recompute down further, as we know every earlier block will be before the start time |
| 51 | cache[pindexPrev] = THRESHOLD_DEFINED; |
| 52 | break; |
| 53 | } |
| 54 | vToCompute.push_back(pindexPrev); |
| 55 | pindexPrev = pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod); |
| 56 | } |
| 57 | |
| 58 | // At this point, cache[pindexPrev] is known |
| 59 | assert(cache.count(pindexPrev)); |
| 60 | ThresholdState state = cache[pindexPrev]; |
| 61 | |
| 62 | // Now walk forward and compute the state of descendants of pindexPrev |
| 63 | while (!vToCompute.empty()) { |
| 64 | ThresholdState stateNext = state; |
| 65 | pindexPrev = vToCompute.back(); |
| 66 | vToCompute.pop_back(); |
| 67 | |
| 68 | switch (state) { |
| 69 | case THRESHOLD_DEFINED: { |
| 70 | if (pindexPrev->GetMedianTimePast() >= nTimeTimeout) { |
| 71 | stateNext = THRESHOLD_FAILED; |
| 72 | } else if (pindexPrev->GetMedianTimePast() >= nTimeStart) { |
| 73 | stateNext = THRESHOLD_STARTED; |
| 74 | } |
| 75 | break; |
| 76 | } |
| 77 | case THRESHOLD_STARTED: { |
| 78 | if (pindexPrev->GetMedianTimePast() >= nTimeTimeout) { |
| 79 | stateNext = THRESHOLD_FAILED; |
| 80 | break; |
| 81 | } |
| 82 | // We need to count |
| 83 | const CBlockIndex* pindexCount = pindexPrev; |
| 84 | int count = 0; |
| 85 | for (int i = 0; i < nPeriod; i++) { |
| 86 | if (Condition(pindexCount, params)) { |
no test coverage detected