Skip to content

Instantly share code, notes, and snippets.

@akshaynexus
Created August 13, 2019 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akshaynexus/8e3f224c8795a219a33ddc74f54d898f to your computer and use it in GitHub Desktop.
Save akshaynexus/8e3f224c8795a219a33ddc74f54d898f to your computer and use it in GitHub Desktop.
Energi stake
// select a block from the candidate blocks in vSortedByTimestamp, excluding
// already selected blocks in vSelectedBlocks, and with timestamp up to
// nSelectionIntervalStop.
static bool SelectBlockFromCandidates(
vector<pair<int64_t, uint256> >& vSortedByTimestamp,
map<uint256, const CBlockIndex*>& mapSelectedBlocks,
int64_t nSelectionIntervalStop,
uint64_t nStakeModifierPrev,
const CBlockIndex** pindexSelected)
{
bool fSelected = false;
arith_uint256 hashBest{0};
*pindexSelected = nullptr;
for (auto iter = vSortedByTimestamp.begin(); ; ++iter) {
if (iter == vSortedByTimestamp.end()) {
vSortedByTimestamp.clear();
break;
}
if (!mapBlockIndex.count(iter->second))
return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", iter->second.ToString().c_str());
const CBlockIndex* pindex = mapBlockIndex[iter->second];
if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop) {
// No point to re-consider the blocks
vSortedByTimestamp.erase(vSortedByTimestamp.begin(), iter+1);
break;
}
if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
continue;
// compute the selection hash by hashing an input that is unique to that block
uint256 hashProof = pindex->GetBlockHash();
CDataStream ss(SER_GETHASH, 0);
ss << hashProof << nStakeModifierPrev;
arith_uint256 hashSelection = UintToArith256(Hash(ss.begin(), ss.end()));
// the selection hash is divided by 2**32 so that proof-of-stake block
// is always favored over proof-of-work block. this is to preserve
// the energy efficiency property
if (pindex->IsProofOfStake())
hashSelection >>= 32;
if (fSelected && hashSelection < hashBest) {
hashBest = hashSelection;
*pindexSelected = (const CBlockIndex*)pindex;
} else if (!fSelected) {
iter = vSortedByTimestamp.begin();
fSelected = true;
hashBest = hashSelection;
*pindexSelected = (const CBlockIndex*)pindex;
}
}
LogPrint("stake", "%s: selection hash=%s\n", __func__, hashBest.ToString().c_str());
return fSelected;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment