Changeset View
Changeset View
Standalone View
Standalone View
src/avalanche.h
Show First 20 Lines • Show All 49 Lines • ▼ Show 20 Lines | |||||
private: | private: | ||||
// Historical record of votes. | // Historical record of votes. | ||||
uint16_t votes; | uint16_t votes; | ||||
// confidence's LSB bit is the result. Higher bits are actual confidence | // confidence's LSB bit is the result. Higher bits are actual confidence | ||||
// score. | // score. | ||||
uint16_t confidence; | uint16_t confidence; | ||||
/** | |||||
* Return the number of bits set in an integer value. | |||||
* TODO: There are compiler intrinsics to do that, but we'd need to get them | |||||
* detected so this will do for now. | |||||
*/ | |||||
static uint32_t countBits(uint32_t value) { | |||||
uint32_t count = 0; | |||||
while (value) { | |||||
// If the value is non zero, then at least one bit is set. | |||||
count++; | |||||
// Clear the rightmost bit set. | |||||
value &= (value - 1); | |||||
} | |||||
return count; | |||||
} | |||||
public: | public: | ||||
VoteRecord(bool accepted) : votes(0xaaaa), confidence(accepted) {} | VoteRecord(bool accepted) : votes(0xaaaa), confidence(accepted) {} | ||||
bool isAccepted() const { return confidence & 0x01; } | bool isAccepted() const { return confidence & 0x01; } | ||||
uint16_t getConfidence() const { return confidence >> 1; } | uint16_t getConfidence() const { return confidence >> 1; } | ||||
bool hasFinalized() const { | bool hasFinalized() const { | ||||
return getConfidence() >= AVALANCHE_FINALIZATION_SCORE; | return getConfidence() >= AVALANCHE_FINALIZATION_SCORE; | ||||
} | } | ||||
/** | /** | ||||
* Register a new vote for an item and update confidence accordingly. | * Register a new vote for an item and update confidence accordingly. | ||||
* Returns true if the acceptance or finalization state changed. | * Returns true if the acceptance or finalization state changed. | ||||
*/ | */ | ||||
bool registerVote(bool vote) { | bool registerVote(bool vote); | ||||
votes = (votes << 1) | vote; | |||||
auto bits = countBits(votes & 0xff); | |||||
bool yes = bits > 6; | |||||
bool no = bits < 2; | |||||
if (!yes && !no) { | |||||
// The vote is inconclusive. | |||||
return false; | |||||
} | |||||
if (isAccepted() == yes) { | |||||
// If the vote is in agreement with our internal status, increase | |||||
// confidence. | |||||
confidence += 2; | |||||
return getConfidence() == AVALANCHE_FINALIZATION_SCORE; | |||||
} | |||||
// The vote did not agree with our internal state, in that case, reset | |||||
// confidence. | |||||
confidence = yes; | |||||
return true; | |||||
} | |||||
}; | }; | ||||
class AvalancheVote { | class AvalancheVote { | ||||
uint32_t error; | uint32_t error; | ||||
uint256 hash; | uint256 hash; | ||||
public: | public: | ||||
AvalancheVote() : error(-1), hash() {} | AvalancheVote() : error(-1), hash() {} | ||||
▲ Show 20 Lines • Show All 208 Lines • Show Last 20 Lines |