BIP9允许部署多个向后兼容的软分叉,通过旷工在一个目标周期内投票,如果达到激活阈值nRuleChangeActivationThreshold
,就能成功的启用该升级。在实现方面,通过重定义区块头信息中的version字段,将version字段解释为bit vector,每一个bit可以用来跟踪一个独立的部署,在满足激活条件之后,该部署将会生效,同时该bit可以被其他部署使用。目前通过BIP9成功进行软分叉有BIP68, 112, 113
, 于2016-07-04 ,高度:419328成功激活.
每一个进行部署的BIP9,都必须设置bit位、开始时间、过期时间。
struct BIP9Deployment {
int bit;
int64_t nStartTime;
int64_t nTimeout;
};
// namespace:Consensus
struct Params {
...
uint32_t nRuleChangeActivationThreshold;
uint32_t nMinerConfirmationWindow;
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]; // BIP9
uint256 powLimit;
bool fPowAllowMinDifficultyBlocks;
bool fPowNoRetargeting;
int64_t nPowTargetSpacing;
int64_t nPowTargetTimespan;
...
};
bit通过1 << bit
方式转换成一个uint32_t的整数,在检验一个BIP9部署是否成功激活的时候使用了Condition(...)函数,来验证一个区块是否赞成该部署。
bool Condition(const CBlockIndex *pindex, const Consensus::Params ¶ms) const {
return ((
(pindex->nVersion & VERSIONBITS_TOP_MASK) ==VERSIONBITS_TOP_BITS) &&
(pindex->nVersion & Mask(params)) != 0);
}
uint32_t Mask(const Consensus::Params ¶ms) const {
return ((uint32_t)1) << params.vDeployments[id].bit;
}
逻辑分析
开始时间和过期时间主要为了在检查BIP9部署状态时,提供状态判断的依据和临界值。比如如果区块的中位数时间超过了过期时间nTimeTimeout
,则判断该BIP9部署已经失败(后面会详细拆解)。
if (pindexPrev->GetMedianTimePast() >= nTimeTimeout) {
stateNext = THRESHOLD_FAILED;
} else if (pindexPrev->GetMedianTimePast() >= nTimeStart) {
stateNext = THRESHOLD_STARTED;
}
if (pindexPrev->GetMedianTimePast() >= nTimeTimeout) {
stateNext = THRESHOLD_FAILED;
break;
}
BIP9部署中定义了所有软分叉升级的初始状态均为THRESHOLD_DEFINED
,并定义创始区块状态为THRESHOLD_DEFINED
, 另外如果在程序中遇到blockIndex为nullptr
时,均返回THRESHOLD_DEFINED
状态。
具体转换过程如下:THRESHOLD_DEFINED
为软分叉的初始状态,如果过去中位数时间(MTP)大于nStartTIme,则状态转换为THRESHOLD_STARTED
,如果MTP大于等于nTimeout,则状态转换成THRESHOLD_FAILED
;如果在一个目标周期(2016个区块)内赞成升级的区块数量占95%以上(大约1915个区块),则状态转换成THRESHOLD_LOCKED_IN
,否则转换成THRESHOLD_FAILED
;在THRESHOLD_LOCKED_IN
之后的下一个目标周期,状态转换成THRESHOLD_ACTIVE
,同时该部署将保持该状态。
enum ThresholdState {
THRESHOLD_DEFINED,
THRESHOLD_STARTED,
THRESHOLD_LOCKED_IN,
THRESHOLD_ACTIVE,
THRESHOLD_FAILED,
};
基类AbstractThresholdConditionChecker
定义了通过共识规则检查BIP9部署的状态。有如下方法,其中最后两个方法在基类中实现,子类继承了该方法的实现:
class AbstractThresholdConditionChecker {
protected:
virtual bool Condition(const CBlockIndex *pindex, const Consensus::Params ¶ms) const = 0;
virtual int64_t BeginTime(const Consensus::Params ¶ms) const = 0;
virtual int64_t EndTime(const Consensus::Params ¶ms) const = 0;
virtual int Period(const Consensus::Params ¶ms) const = 0;
virtual int Threshold(const Consensus::Params ¶ms) const = 0;
public:
ThresholdState GetStateFor(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, ThresholdConditionCache &cache) const;
int GetStateSinceHeightFor(const CBlockIndex *pindexPrev, const Consensus::Params ¶ms, ThresholdConditionCache &cache) const;
};
类VersionBitsConditionChecker
继承了AbstractThresholdConditionChecker
。实现了:
class VersionBitsConditionChecker : public AbstractThresholdConditionChecker {
private:
// maybe: DEPLOYMENT_TESTDUMMY,DEPLOYMENT_CSV,MAX_VERSION_BITS_DEPLOYMENTS
const Consensus::DeploymentPos id;
protected:
int64_t BeginTime(const Consensus::Params ¶ms) const {
return params.vDeployments[id].nStartTime;
}
int64_t EndTime(const Consensus::Params ¶ms) const {
return params.vDeployments[id].nTimeout;
}
int Period(const Consensus::Params ¶ms) const {
return params.nMinerConfirmationWindow;
}
int Threshold(const Consensus::Params ¶ms) const {
return params.nRuleChangeActivationThreshold;
}
bool Condition(const CBlockIndex *pindex, const Consensus::Params ¶ms) const {
return ((
(pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) && (pindex->nVersion & Mask(params)) != 0);
}
...
}
另个一重要的类VersionBitsCache
,包括一个方法和一个数组。该数组作为内存缓存使用,该数组的成员是一个map,当检查一个BIP9部署的状态时,如果在检查过程中判断出部署状态,该map会以区块索引为键值,以状态信息(int)为值,缓存起来,在下次检查时可以在该区块位置直接得到其状态信息,对程序起到了优化的作用,避免重复的检索。
struct VersionBitsCache {
ThresholdConditionCache caches[Consensus::MAX_VERSION_BITS_DEPLOYMENTS];
void Clear();
};
typedef std::map ThresholdConditionCache;
另外WarningBitsConditionChecker
类也继承了AbstractThresholdConditionChecker
类,实现了对未知升级的追踪与警告。一旦nVersion中有未预料到的位被设置成1,mask将会生成非零的值。当未知升级被检测到处THRESHOLD_LOCKED_IN
状态,软件应该警告用户即将到来未知的软分叉。在下一个目标周期,处于THRESHOLD_ACTIVE
状态是,更应该强调警告用户。
需要说明的是:未知升级只有处于LOCKED_IN或ACTIVE的条件下才会发出警告
...
WarningBitsConditionChecker checker(bit);
ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
if (state == THRESHOLD_ACTIVE) {
std::string strWarning =
strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
SetMiscWarning(strWarning);
if (!fWarned) {
AlertNotify(strWarning);
fWarned = true;
}
} else {
warningMessages.push_back(
strprintf("unknown new rules are about to activate (versionbit %i)", bit));
}
}
...
GetSkipHeight(int height)
函数,能够快速定位到指定高度的区块,优化了执行的效率。CBlockIndex *CBlockIndex::GetAncestor(int height) {
if (height > nHeight || height < 0) {
return nullptr;
}
CBlockIndex *pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (pindexWalk->pskip != nullptr &&
(heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height)))) {
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
assert(pindexWalk->pprev);
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
static inline int GetSkipHeight(int height) {
if (height < 2) {
return 0;
}
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
enum { nMedianTimeSpan = 11 };
int64_t 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];
}
逻辑如下:
VersionBitsCache
结构体中;如果该状态已经存在于缓存中则直接返回结果;最后如果该区块无法得出状态信息,则会依次寻找(pindexPrev.nHeight - nPeriod)高度的状态信息,直到能够得出结果。如果直到nullptr也没有,则返回THRESHOLD_DEFINED
。其中比较重要的是,如果一个区块表明该部署状态处于THRESHOLD_STARTED
,则会进行更为详细的判断,以证明其状态是否以及失败或者可以进入LOCKED_IN阶段。ThresholdState AbstractThresholdConditionChecker::GetStateFor(...){
...
if (pindexPrev != nullptr) {
pindexPrev = pindexPrev->GetAncestor(
pindexPrev->nHeight - ((pindexPrev->nHeight + 1) % nPeriod));
}
std::vector vToCompute;
while (cache.count(pindexPrev) == 0) {
if (pindexPrev == nullptr) {
cache[pindexPrev] = THRESHOLD_DEFINED;
break;
}
if (pindexPrev->GetMedianTimePast() < nTimeStart) {
cache[pindexPrev] = THRESHOLD_DEFINED;
break;
}
vToCompute.push_back(pindexPrev);
pindexPrev = pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod);
}
assert(cache.count(pindexPrev));
ThresholdState state = cache[pindexPrev];
while (!vToCompute.empty()) {
ThresholdState stateNext = state;
pindexPrev = vToCompute.back();
vToCompute.pop_back();
switch (state) {
case THRESHOLD_DEFINED: {
if (pindexPrev->GetMedianTimePast() >= nTimeTimeout) {
stateNext = THRESHOLD_FAILED;
} else if (pindexPrev->GetMedianTimePast() >= nTimeStart) {
stateNext = THRESHOLD_STARTED;
}
break;
}
case THRESHOLD_STARTED: {
if (pindexPrev->GetMedianTimePast() >= nTimeTimeout) {
stateNext = THRESHOLD_FAILED;
break;
}
const CBlockIndex *pindexCount = pindexPrev;
int count = 0;
for (int i = 0; i < nPeriod; i++) {
if (Condition(pindexCount, params)) {
count++;
}
pindexCount = pindexCount->pprev;
}
if (count >= nThreshold) {
stateNext = THRESHOLD_LOCKED_IN;
}
break;
}
case THRESHOLD_LOCKED_IN: {
stateNext = THRESHOLD_ACTIVE;
break;
}
case THRESHOLD_FAILED:
case THRESHOLD_ACTIVE: {
break;
}
}
cache[pindexPrev] = state = stateNext;
}
}
举例说明:
THRESHOLD_DEFINED
,且本轮初始块的时间 >= startTime,将本轮的状态转换为THRESHOLD_STARTED
;THRESHOLD_STARTED
,且本轮初始块的时间 < timeout, 将统计上一轮部署该bit位的区块个数(即从 2016 ->4031),假设部署的个数超过阈值(95%),将本轮的状态转换为LOCKED_IN
;THRESHOLD_LOCKED_IN
,将本轮的状态自动切换为THRESHOLD_ACTIVE
。THRESHOLD_DEFINED
-> THRESHOLD_STARTED
-> THRESHOLD_LOCKED_IN
-> THRESHOLD_ACTIVE
nMinerConfirmationWindow
为一轮进行检测,在本轮之间的所有区块,都与本轮的第一个块状态相同。int AbstractThresholdConditionChecker::GetStateSinceHeightFor(
const CBlockIndex *pindexPrev, const Consensus::Params ¶ms,
ThresholdConditionCache &cache) const {
const ThresholdState initialState = GetStateFor(pindexPrev, params, cache);
// BIP 9 about state DEFINED: "The genesis block is by definition in this
if (initialState == THRESHOLD_DEFINED) {
return 0;
}
const int nPeriod = Period(params);
pindexPrev = pindexPrev->GetAncestor(pindexPrev->nHeight - ((pindexPrev->nHeight + 1) % nPeriod));
const CBlockIndex *previousPeriodParent = pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod);
while (previousPeriodParent != nullptr &&
GetStateFor(previousPeriodParent, params, cache) == initialState) {
pindexPrev = previousPeriodParent;
previousPeriodParent =
pindexPrev->GetAncestor(pindexPrev->nHeight - nPeriod);
}
// Adjust the result because right now we point to the parent block.
return pindexPrev->nHeight + 1;
}
逻辑如下:
THRESHOLD_DEFINED
直接返回0