|
September 05, 2011, 01:51:40 AM Last edit: September 05, 2011, 03:55:04 AM by Jimmy2011 |
|
I post one example of such algorithms as the following code segment. Just an example, it's not usable directly, some necessary validity changes and modifications, optimization should be added for the actual application.
Anyone can use it as long as you find it useful.
------------------------------------------------------------------
// Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < nInterval-1; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst);
// Limit adjustment step int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
int64 nThisTimespan = nActualTimespan;
if (nActualTimespan < nTargetTimespan/4) nActualTimespan = nTargetTimespan/4; if (nActualTimespan > nTargetTimespan*4) nActualTimespan = nTargetTimespan*4;
const CBlockIndex* pindexPreviousFirst = pindexFirst; for (int i = 0; pindexPreviousFirst && i < nInterval-1; i++) pindexPreviousFirst = pindexPreviousFirst->pprev; assert(pindexPreviousFirst);
int64 nPreviousTimespan = pindexFirst->GetBlockTime() - pindexPreviousFirst->GetBlockTime();
// Retarget CBigNum bnNew; bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan;
if ( ( nPreviousTimespan > nThisTimespan ) && ( nPreviousTimespan < nTargetTimespan ) ) { bnNew *= 2; bnNew /= ( nTargetTimespan + nActualTimespan ); } else if ( ( nPreviousTimespan < nThisTimespan ) && ( nPreviousTimespan > nTargetTimespan ) ) { bnNew *= nActualTimespan; bnNew /= ( nTargetTimespan * nTargetTimespan ); } else { bnNew /= nTargetTimespan; }
if (bnNew > bnProofOfWorkLimit) bnNew = bnProofOfWorkLimit;
/// debug print printf("GetNextWorkRequired RETARGET\n"); printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan); printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str()); printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
return bnNew.GetCompact();
|